Earliest Second the Secret Is Beyond Repair
StringsAuto-graded · 29 test casesLast updated
Find the first second at which at least m substrings of a string contain a corrupted character, using complement counting and a reverse-time merge of clean runs.
A secret is a string secret of length n. It may already contain '*' characters, which mark corrupted positions. An attacker then corrupts it one position per second, following hits, a permutation of 1..n with 1-indexed positions. At second t (for t = 1..n), the character at position hits[t-1] becomes '*'. If that position is already '*', nothing changes.
A substring is a contiguous range of positions. Substrings are counted by their start and end positions, not by their text. Two equal substrings at different positions count separately, so a string of length n has n(n+1)/2 substrings in total.
The secret is beyond repair once at least k substrings contain at least one '*'.
Return the minimum number of seconds t after which the secret is beyond repair, following these rules:
- If
k <= 0, return1. - If
kis greater than the total number of substringsn(n+1)/2, return-1, because the condition can never hold. - If the secret is already beyond repair before any attack (for example because of the
'*'characters it starts with), return1. - Otherwise, return the smallest
tin1..nsuch that the secret is beyond repair after the firsttattacks.
Constraints
1 <= n <= 10^5secretconsists of lowercase letters and possibly'*'.hitsis a permutation of1..n.kmay be any integer, including values<= 0or larger thann(n+1)/2.- Counts can exceed 32 bits, so use a suitably wide integer type if your language needs one.
Examples
Example 1
Input: find_min_corrupt_time('abc', [1, 2, 3], 1)
Output: 1
Example 2
Input: find_min_corrupt_time('abc', [1, 2, 3], 5)
Output: 2
Example 3
Input: find_min_corrupt_time('abcd', [2, 4, 1, 3], 8)
Output: 2
Example 4
Input: find_min_corrupt_time('abcde', [2, 4, 1, 3, 5], 13)
Output: 3
Hints
Hint 1
Counting substrings that contain a '*' directly is awkward. Count the complement instead: substrings with no '*'. A run of L clean characters contributes L(L+1)/2 of them.
Hint 2
The number of corrupted substrings never decreases as time passes, so there is a single threshold time. Splitting runs going forward is hard, but merging runs going backward is easy.
Hint 3
Run time in reverse, restoring positions from the last attack to the first. When position p becomes clean between a clean run of length a on its left and one of length b on its right, exactly (a+1)*(b+1) new clean substrings appear. Track run lengths with union-find, and use sentinel positions 0 and n+1 to avoid boundary cases.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Let total = n(n+1)/2. The number of corrupted substrings after t attacks is total - clean(t), where clean(t) is the number of substrings with no '*'. A maximal run of L clean characters contributes L(L+1)/2 clean substrings.
First handle the special cases from the statement:
- If
k <= 0, return1. - If
k > total, return-1. - Compute the clean count of the original string. If the corrupted count is already at least
k, return1.
Going forward, an attack splits a clean run, which is awkward to track. Going backward, restoring a position merges runs, which union-find handles easily. So we replay time in reverse:
- Start from the fully attacked state, where
clean = 0. - For
t = ndown to1, restore positionp = hits[t-1]. This turns the state aftertattacks into the state aftert-1attacks. - If
pwas originally'*', it stays corrupted, so the state does not change and we skip it. - Otherwise
pjoins a clean run of lengthlefton its left and one of lengthrighton its right. Every newly created clean substring containsp, withleft+1choices for its start andright+1choices for its end. Socleanincreases by(left+1)*(right+1). Then unionpwith its active neighbours. - After the restoration, if
total - clean < k, the state aftert-1attacks is still recoverable while the state aftertattacks is not. Returnt.
Why it is correct
The corrupted count is non-decreasing in t, so the answer is a single threshold. The backward scan finds the largest t whose predecessor state is recoverable. By monotonicity, the state at t is beyond repair and the state at t-1 is not, so t is the minimum. A step that hits an originally corrupted position never changes the state, so it can never be that threshold step. Skipping those steps is therefore safe. Since k <= total and the initial state is recoverable, the scan always finds such a t. The final return 1 is only a fallback.
Complexity
- Time:
O(n * alpha(n)), effectively linear. There is one pass for the initial count and one backward pass with a few union-find operations per step. - Space:
O(n)for the union-find arrays.
An alternative is to binary search on t and recompute the clean count in O(n) for each guess, which gives O(n log n).
Reference solution
from typing import List
def find_min_corrupt_time(secret: str, hits: List[int], k: int) -> int:
n = len(secret)
total = n * (n + 1) // 2
if k <= 0:
return 1
if k > total:
return -1
# Clean substrings (no '*') in the initial string.
initial_clean = 0
run = 0
for ch in secret:
if ch == '*':
initial_clean += run * (run + 1) // 2
run = 0
else:
run += 1
initial_clean += run * (run + 1) // 2
if total - initial_clean >= k:
return 1
# Union-find over positions 1..n with never-active sentinels 0 and n+1.
parent = list(range(n + 2))
size = [1] * (n + 2)
active = [False] * (n + 2)
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a: int, b: int) -> None:
ra, rb = find(a), find(b)
if ra == rb:
return
if size[ra] < size[rb]:
ra, rb = rb, ra
parent[rb] = ra
size[ra] += size[rb]
clean = 0
for t in range(n, 0, -1):
p = hits[t - 1]
if secret[p - 1] != '*':
left = size[find(p - 1)] if active[p - 1] else 0
right = size[find(p + 1)] if active[p + 1] else 0
clean += (left + 1) * (right + 1)
active[p] = True
if active[p - 1]:
union(p, p - 1)
if active[p + 1]:
union(p, p + 1)
# State is now "after t-1 attacks".
if total - clean < k:
return t
return 1