Bank app~10 min2s · 256 MBtarget O(n) time, O(1) spacesliding-window-variable
A bank produces a settlement file at the end of each day. Every entry in the file carries a status code, such as settled, pending or rejected, and each code is a number from 1 to 1000.
The operations team looks for long runs of consecutive entries that share one status code. A very long run of rejected entries, for example, often points to one failed batch.
For each file they want two numbers: the length of the longest run, and how many separate runs have exactly that length.
Write longest_status_run(statuses).
statuses[i] is the status code of entry i, in file order.Input: statuses = [4, 4, 7, 7, 7, 2, 7, 7, 7, 1]
Output: [3, 2]The window starts at left, and right moves forward. When the entry at right differs from the entry at left, the run from left to right - 1 is finished. After the last entry, a sentinel position closes the final run.
| right | Entry | Closes a run? | Run length | Longest | Runs of that length | left after |
|---|---|---|---|---|---|---|
| 1 | 4 | no | 0 | 0 | 0 | |
| 2 | 7 | yes, 4 | 2 | 2 | 1 | 2 |
| 3 | 7 | no | 2 | 1 | 2 | |
| 4 | 7 | no | 2 | 1 | 2 | |
| 5 | 2 | yes, 7 | 3 | 3 | 1 | 5 |
| 6 | 7 | yes, 2 | 1 | 3 | 1 | 6 |
| 7 | 7 | no | 3 | 1 | 6 | |
| 8 | 7 | no | 3 | 1 | 6 | |
| 9 | 1 | yes, 7 | 3 | 3 | 2 | 9 |
| 10 | end | yes, 1 | 1 | 3 | 2 | 10 |
The longest runs are the two blocks of three 7s, so the answer is [3, 2].
Input: statuses = [9]
Output: [1, 1]One entry is one run of length 1.
Input: statuses = [5, 5, 5, 5]
Output: [4, 1]The whole file is one run.
1 ≤ statuses.length ≤ 100,000 (entries in the file)1 ≤ statuses[i] ≤ 1000 (status code)Starting at every entry and extending until the code changes is O(n^2) in the worst case. When every entry has the same code, that is about 5 × 10^9 steps. Aim for O(n).
The answer is at most n, so it fits in a 32-bit integer.