KatInterview

Fewest Leading Digits Needed to Rearrange Into Each Word

StringsAuto-graded · 22 test cases
MediumAuto-gradedStringsstringshashingcounting

Last updated

For each query digit string, find the shortest prefix of a digit string containing enough of each digit to form it, using per-digit occurrence lists and a max over digits.

You are given a string source made up only of the characters '0' through '9', and a list of strings queries, each also made up only of digit characters.

For every string q in queries, determine the smallest number of leading characters of source (that is, the length of a prefix starting at index 0) from which you can assemble every rearrangement of q. Return these numbers as a list, in the same order as queries.

Rules

  • To assemble a string from a prefix, select characters from that prefix and arrange them in any order. Each position in the prefix may be used at most once for a single assembled string.
  • Each rearrangement of q is assembled on its own, always starting again from the same prefix. The prefix does not need to hold enough characters to assemble several rearrangements simultaneously.
  • If no prefix of source (including source itself) can assemble every rearrangement of q, the answer for that query is -1.
  • Queries are answered independently, and source is never changed.

Constraints

  • 1 <= len(source) <= 100000
  • 1 <= len(queries) <= 100000
  • 1 <= len(queries[i]) <= 100000, and the combined length of all strings in queries is at most 200000.
  • Every character in source and in every query is a digit from '0' to '9'.
  • Each returned value is either -1 or an integer between len(q) and len(source) inclusive, and it is uniquely determined by the input.

Examples

Example 1

Input: min_prefix_for_rearrangements('1213321', ['12', '113', '2233'])

Output: [2, 4, 6]

Example 2

Input: min_prefix_for_rearrangements('9080', ['00', '000', '89', '7'])

Output: [4, -1, 3, -1]

Hints

Hint 1

All rearrangements of a string contain exactly the same multiset of characters, so 'every rearrangement' reduces to a single count check per digit.

Hint 2

For one digit that must appear c times, the shortest prefix with at least c copies ends exactly at the c-th occurrence of that digit in the source. Precompute the positions of each digit once.

Hint 3

The prefix must satisfy all digits simultaneously, so combine the per-digit lengths with a maximum; if any digit occurs fewer than c times in the whole source, the answer is -1.