KatInterview

Earliest Second the Secret Is Beyond Repair

StringsAuto-graded · 29 test cases
MediumAuto-gradedStringsstringsunion-findcounting

Last 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, return 1.
  • If k is greater than the total number of substrings n(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), return 1.
  • Otherwise, return the smallest t in 1..n such that the secret is beyond repair after the first t attacks.

Constraints

  • 1 <= n <= 10^5
  • secret consists of lowercase letters and possibly '*'.
  • hits is a permutation of 1..n.
  • k may be any integer, including values <= 0 or larger than n(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.