← Questions

Split a string into blocks that match the prefix's letter counts

0
AmazonCoding

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) and s can be cut into consecutive, non-overlapping blocks of exactly L characters 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 A to Z?
  • 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 L of n; for each, the whole-string letter counts must equal n / L times 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

strings · hashing · prefix sums · divisors

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding