Fewest Leading Digits Needed to Rearrange Into Each Word
StringsAuto-graded · 22 test casesLast 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
qis 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(includingsourceitself) can assemble every rearrangement ofq, the answer for that query is-1. - Queries are answered independently, and
sourceis never changed.
Constraints
1 <= len(source) <= 1000001 <= len(queries) <= 1000001 <= len(queries[i]) <= 100000, and the combined length of all strings inqueriesis at most200000.- Every character in
sourceand in every query is a digit from'0'to'9'. - Each returned value is either
-1or an integer betweenlen(q)andlen(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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every rearrangement of a query q uses the same multiset of characters, so a prefix can assemble one rearrangement exactly when it can assemble all of them. That holds precisely when, for every digit d, the prefix has at least as many copies of d as q does. Rearrangements are built separately, so counts are never multiplied.
For a single digit d needed c times, the shortest prefix with at least c copies ends at the c-th occurrence of d in source. If positions[d] lists the indices of d in increasing order, that prefix has length positions[d][c-1] + 1.
All digits must be satisfied at once, so the answer is the maximum of these lengths across the distinct digits of q. If any digit is needed more times than it appears in source, the answer is -1.
Steps:
- In one pass over
source, buildpositionsfor each of the 10 digits. - For each query, count its digits. For each digit, check availability, then take the maximum of
positions[d][c-1] + 1.
Why it is correct
- Necessity: a valid prefix of length
Lhas at leastccopies ofd, so it must reach thec-th occurrence ofd, givingL >= positions[d][c-1] + 1for everyd. - Sufficiency: the prefix of length equal to the maximum of these values contains the first
coccurrences of every needed digit, so all count requirements hold. - Monotonicity: longer prefixes never lose characters, so "shortest" is well defined.
Complexity
- Preprocessing:
O(|source|)time and space. - Each query: counting costs
O(|q|)and there are at most 10 distinct digits, each looked up inO(1). - Total time:
O(|source| + sum of |q|). Space:O(|source|)plus the output.
Reference solution
from collections import Counter
def min_prefix_for_rearrangements(source: str, queries: list[str]) -> list[int]:
# positions[d] = increasing indices where digit d appears in source
positions = {d: [] for d in '0123456789'}
for i, ch in enumerate(source):
positions[ch].append(i)
result = []
for q in queries:
best = 0
feasible = True
for d, need in Counter(q).items():
occ = positions[d]
if need > len(occ):
feasible = False
break
# prefix containing `need` copies of d ends at the need-th occurrence
best = max(best, occ[need - 1] + 1)
result.append(best if feasible else -1)
return result