Monitoring~25 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-424sliding-window-variable · window-counts
A monitoring system writes one log line per second, and each line carries a severity letter from A to Z. A stretch of lines with the same letter is easy to read, so engineers like to compare them.
A review tool can correct up to k letters in the log. A correction changes one line to any letter the engineer chooses, and the choice of the final letter is free.
The team wants to know how long a run of one identical letter can become after at most k corrections. The run must be a block of consecutive lines.
Write longest_after_replacing(levels, k).
levels[i] is the severity letter of line i, an uppercase letter from A to Z.k letters, each to any uppercase letter.k is 0, the answer is the longest run that already exists.Input: levels = "XXYXZZXXYX", k = 2
Output: 5A window of right - left + 1 lines can become one letter when its length minus the count of its most common letter is at most k. The loop keeps top, the highest count any letter has reached in a window, and shrinks the window from the left while length - top > k.
| right | Joins | Counts after the step | top | Leaves | left after | Length | Best |
|---|---|---|---|---|---|---|---|
| 0 | X | X→1 | 1 | none | 0 | 1 | 1 |
| 1 | X | X→2 | 2 | none | 0 | 2 | 2 |
| 2 | Y | X→2, Y→1 | 2 | none | 0 | 3 | 3 |
| 3 | X | X→3, Y→1 | 3 | none | 0 | 4 | 4 |
| 4 | Z | X→3, Y→1, Z→1 | 3 | none | 0 | 5 | 5 |
| 5 | Z | X→2, Y→1, Z→2 | 3 | X | 1 | 5 | 5 |
| 6 | X | X→2, Y→1, Z→2 | 3 | X | 2 | 5 | 5 |
| 7 | X | X→3, Z→2 | 3 | Y | 3 | 5 | 5 |
| 8 | Y | X→2, Y→1, Z→2 | 3 | X | 4 | 5 | 5 |
| 9 | X | X→3, Y→1, Z→1 | 3 | Z | 5 | 5 | 5 |
The first five lines XXYXZ hold three X, so two corrections turn them into XXXXX.
Input: levels = "AAAB", k = 1
Output: 4One correction changes the B into an A, and the whole log becomes one run.
Input: levels = "ABC", k = 0
Output: 1With no corrections, the longest existing run is a single line.
1 ≤ levels.length ≤ 100,000 (log lines)levels[i] is an uppercase letter, A to Z0 ≤ k ≤ 100,000Trying every start and every end costs about n^2 / 2 windows. Finding the top count of each window costs up to 26 steps more. That is about 1.3 × 10^11 steps at n = 100,000. Aim for O(n).
The answer is at most n, so it fits in a 32-bit integer.