Split a string into blocks that match the prefix's letter counts
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Amazon. It tests strings, hashing and prefix sums.
You get a string s of uppercase letters A-Z.
Call a positive length L valid when:
-
L <= len(s)andscan be cut into consecutive, non-overlapping blocks of exactlyLcharacters with nothing left over, and - every block contains each letter the same number of times as the prefix
s[:L]does.
The blocks do not have to be equal strings; only their letter counts must match the prefix.
Implement valid_prefix_lengths(s: str) -> list[int] that returns all valid lengths in increasing order. (len(s) is always valid.)
Constraints: 1 <= len(s) <= 10^5.
Example 1
s = "ABCCBAACB"
output: [3, 9]
With L = 3 the blocks are ABC, CBA, ACB, each with one A, one B and one C. L = 1 fails because B differs from A.
Example 2
s = "ABBAAABB"
output: [4, 8]
L = 2 fails: the prefix AB has one of each letter, but the block AA does not. L = 4 works: ABBA and AABB each have two As and two Bs.
Clarifying questions
- Only lengths that divide
len(s)can be valid: is that the intended reading of "nothing left over"? - Are the letters only uppercase
AtoZ? - Is
len(s)always in the output, even when no shorter length works? - Does the output need to be sorted ascending?
What a strong answer covers
- Tries only the divisors
Lofn; for each, the whole-string letter counts must equaln / Ltimes the prefix counts, a quick filter. - Builds prefix count arrays (26 counts per position) so any block's counts take
O(26)to read. - Checks each block against the prefix and stops at the first mismatch; the total work is
26 * sum(n / L)over divisors, close to linear. - Tests both examples, a string of one repeated letter (every divisor works), and a prime length (only
n).
Follow-ups
- Return the blocks for the smallest valid
L. - Blocks only need the same set of letters, not the same counts.
- Answer the same question for many substrings of
s.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
