1232. Running Favourite
A live dashboard receives one reading at a time and wants to show the most common reading seen so far after every arrival. You are given the integer array stream in arrival order. Return an array of the same length whose element i is the favourite of the prefix stream[0..i]: the value that occurs the most times in that prefix.
If several values share the highest count, the favourite is the smallest of them. Keep the counts in a hash map and update the leader as each value arrives, so every step costs constant time on average.
The intended solution runs in O(n) time and O(n) extra space.
Example 1
- Input:
- stream = [9,4,4,9,2,2,2,4,9,9]
- Output:
- [9,4,4,4,4,2,2,2,2,9]
- Explanation:
The favourite is 9, then 4 from index 1 on (it ties 9 at two sightings and is smaller), then 2 from index 5 where 2, 4 and 9 all have two sightings, and 9 retakes the lead only at index 9 with four sightings.
Example 2
- Input:
- stream = [-8,15,-8,40,40,15,40,-8,15,15,-8]
- Output:
- [-8,-8,-8,-8,-8,-8,40,-8,-8,15,-8]
- Explanation:
The value -8 leads early, 40 takes the lead alone at index 6 with three sightings, then ties with -8 and loses to the smaller value, and 15 leads alone at index 9 with four sightings before -8 ties it at index 10.
Constraints
1 ≤ stream.length ≤ 1000
-109 ≤ stream[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(n)