← Questions

Earliest time a password becomes irrecoverable

0
AmazonCodingLast asked Sep 2025

A coding interview question asked in Amazon's online assessment, last asked Sep 2025. It tests binary-search, strings and counting.

A virus attacks a password of length n one character per second: at second i (1-indexed) it replaces the character at position attack_order[i] with '*'. The password becomes irrecoverable once at least m of its substrings (contiguous, counted by position) contain at least one '*'. Return the earliest second after which the password is irrecoverable. If m == 0, return 1.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • earliest_irrecoverable(password: str, attack_order: list[int], m: int) -> int — attack_order is a permutation of 1..n (1-indexed positions).

Example

password = "abcd", attack_order = [2, 4, 1, 3]     # 10 substrings in all
earliest_irrecoverable(password, attack_order, 6)   ->  1
# after second 1, "a*cd": clean runs of length 1 and 2 hold 1 + 3 = 4
# substrings, so 10 - 4 = 6 contain a '*'
earliest_irrecoverable(password, attack_order, 7)   ->  2    # "a*c*": 10 - 2 = 8
earliest_irrecoverable(password, attack_order, 9)   ->  3    # "**c*": 10 - 1 = 9
earliest_irrecoverable(password, attack_order, 0)   ->  1

Constraints

  • 1 <= n <= 8 · 10^5; lowercase letters.
  • 0 <= m <= n(n + 1) / 2, so counts need 64-bit integers.

Clarifying questions

  • Are attack_order positions 0- or 1-indexed? (1-indexed.)
  • Are substrings counted by position, so equal substrings at different places count separately? (Yes.)
  • Is m always reachable? (Yes: after n seconds every substring contains a '*'.)

What a strong answer covers

  • Count the complement: substrings with no '*' lie inside clean runs, and a run of length L holds L(L + 1) / 2 of them, so the starred count is n(n + 1)/2 minus the sum over runs.
  • Binary search on t: the count only grows over time, and each check rebuilds the runs in O(n), for O(n log n) overall.
  • Or one pass forward in time: each new '*' splits one clean run into two, so the count changes by the difference of the triangular numbers; find the run with a sorted set of starred positions (O(n log n)), or run time backwards with union-find to merge runs in near O(n).
  • 64-bit arithmetic and the m == 0 rule.

Follow-ups

  • Answer many values of m for the same attack order.
  • Count only distinct substrings containing a '*'.

Where it's asked

  • Amazon · Online assessment · Last asked Sep 2025Coding problems plus a repository bug-fix section with a built-in assistant or a design scenario, then a work-style survey · AI only inside the bug-fix section's built-in assistant

What it tests

binary-search · strings · counting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding