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

0
Sign in

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.

Reconstructed from the reported question; details may differ from what interviewers ask.

AmazonCodingEasy

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.