Problem Description
Given a circular array of integers, in one second every position can adopt one of three values: its own, its left neighbor’s, or its right neighbor’s value. Find the minimum number of seconds needed to make all the array elements equal.
Key Insights
- The operation allows a value to “propagate” one step per second in both directions, effectively filling gaps between indices containing the same value.
- For a candidate value (one present initially), identify every index where it occurs.
- In a circular array, the longest contiguous segment (gap) that does not contain the candidate value determines how long it takes for that value to propagate across the entire array.
- The minimal seconds required for a candidate is ceil(max_gap/2), where max_gap is the maximum gap (considering circularity) between consecutive indices holding that candidate.
- Evaluate all candidate values and return the minimum seconds required.
Space and Time Complexity
Time Complexity: O(n) – We traverse the array to build the mapping and then iterate over each candidate's indices. Space Complexity: O(n) – To store the indices for each unique value.
Solution
We solve this problem by considering each candidate value that initially appears in the array. For each candidate, we:
- Store the indices of its occurrence in sorted order.
- Compute the gaps between consecutive indices (adjusting for circularity with the wrap-around gap).
- The propagation time needed for that candidate is the ceiling of half of the maximum gap.
- The answer is the minimum propagation time among all candidates.
Key steps include:
- Use a hash table (or dictionary) to group indices by their value.
- For each group, determine the maximum gap between indices. Don’t forget the gap between the last occurrence and the first occurrence in the circular array.
- Use the formula (max_gap + 1) // 2 for computing the number of seconds (this equals the ceiling of max_gap/2).
- Return the smallest computed seconds among all candidates.