Ctrl K

Heaviest Picks of Distinct Letters

Hard
You are given a string text of lowercase English letters and an integer size. The weight of a letter is the number of times it occurs in the whole of text. Pick size positions in the string so that all the letters at those positions are different. The weight of a pick is the sum of the weights of its letters. Two picks are different if their sets of positions differ, even when they spell the same string. Find the largest possible weight and return how many picks have exactly that weight. The count can be large, so return it modulo 10⁹ + 7. If size distinct letters cannot be picked, return 0.
Example 1
text="xyyz", size=2 → 4

The frequencies are x 1, y 2, z 1. The top weight of 3 comes from x+y and from y+z. Each y can be any of two positions, so there are 2 + 2 = 4 picks.

Example 2
text="moon", size=3 → 2

All three letters m, o, n must be taken; the weight is 1 + 2 + 1 = 4, and the o can come from either of two positions, so the answer is 2.

Example 3
text="aaa", size=2 → 0

There is only one distinct letter, so two different letters cannot be picked: the answer is 0.

Constraints
  • 1 ≤ len(text) ≤ 2·10⁵
  • 1 ≤ size ≤ len(text)
  • text contains only lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEqual Letters Kept Apart HardSimplify a Letter Polynomial HardWord Topping Duel HardBalanced Stretches of a String HardLargest Palindrome That Is a Multiple Hard
loading Python…
Input
text="xyyz", size=2
Expected
4

Run checks the first 3 tests in your browser. Submit checks all 5 tests on the server, hidden ones included.