Chat app~35 min2s · 256 MBtarget O(n) time, O(n) spaceprefix-sum-hashmap
A group chat lets members answer a poll with one of three choices, numbered 0, 1 and 2. The votes are kept in the order they arrived.
The organiser wants to know when the group was split evenly. She asks for the longest stretch of consecutive votes in which all three choices received the same number of votes.
Write longest_equal_stretch(votes).
votes[i] is 0, 1 or 2, the choice of the i-th vote.0 when no stretch is equal.Input: votes = [0, 1, 2, 0, 0, 1, 2, 1]
Output: 6The trace counts the votes for each choice so far: a for choice 0, b for choice 1 and c for choice 2. Two positions have an equal stretch between them exactly when the pair of differences (a − b, b − c) is the same at both. The table keeps the first position of each pair. Position 0 is before any vote, with the pair (0, 0).
| Position | Vote | Pair (a − b, b − c) |
Seen before at | Stretch length | Best |
|---|---|---|---|---|---|
| 0 | start | (0, 0) | 0 | ||
| 1 | 0 | (1, 0) | not seen, store position 1 | 0 | |
| 2 | 1 | (0, 1) | not seen, store position 2 | 0 | |
| 3 | 2 | (0, 0) | position 0 | 3 | 3 |
| 4 | 0 | (1, 0) | position 1 | 3 | 3 |
| 5 | 0 | (2, 0) | not seen, store position 5 | 3 | |
| 6 | 1 | (1, 1) | not seen, store position 6 | 3 | |
| 7 | 2 | (1, 0) | position 1 | 6 | 6 |
| 8 | 1 | (0, 1) | position 2 | 6 | 6 |
The votes at positions 2 to 7, 1, 2, 0, 0, 1, 2, hold two votes for each choice. The output is 6.
Input: votes = [1, 1, 1]
Output: 0Only choice 1 appears, so no stretch holds all three choices equally.
Input: votes = [2, 1, 0]
Output: 3The whole list holds one vote for each choice.
0 ≤ votes.length ≤ 100,000 (votes in one poll)votes[i] is 0, 1 or 2Trying every start and extending the stretch one vote at a time costs about n × n / 2 steps. For 100,000 votes that is about 5 × 10^9, far over the budget of about 10^8 a second. One pass with a table of pairs costs n steps.