A constellation of n communication satellites orbits a planet along a single fixed ring, numbered 0 through n - 1 in order around the ring, so that satellite n - 1 sits immediately next to satellite 0. Each satellite is currently transmitting an integer broadcast code. Every minute, mission control issues one synchronized command to the entire ring: simultaneously, every satellite either keeps transmitting its own current code, or switches to transmit whichever code the satellite immediately clockwise from it was transmitting, or whichever code the satellite immediately counter-clockwise from it was transmitting — using the codes exactly as they stood the instant before that minute began. Mission control wants to reach a minute after which every satellite in the ring is transmitting the exact same code (it does not matter in advance which code that ends up being). Determine the minimum number of minutes mission control needs to guarantee this.
Line 1: a single integer n, the number of satellites. Line 2: n space-separated integers code_0, code_1, ..., code_{n-1}, the current broadcast code of each satellite in ring order.
Print a single integer: the minimum number of minutes needed until every satellite transmits the same code.
Example 1
Input
4 1 2 1 2
Expected
1
Explanation
Code 1 sits at positions 0 and 2, splitting the 4-satellite ring into two equal circular gaps of length 2; code 2 sits at positions 1 and 3 with the same symmetric gaps. Either code needs only 1 minute to fill its gap, since the satellite exactly between two occurrences is a single hop from the nearer one, so the answer is 1.
Example 2
Input
5 2 1 3 3 2
Expected
2
Explanation
Code 1 appears only once (position 1), so on its own it must spread all the way around the 5-satellite ring, taking floor(5/2) = 2 minutes to reach the farthest satellite. Codes 2 and 3 each appear twice with a largest circular gap of 4 between consecutive occurrences, also needing floor(4/2) = 2 minutes. The best available option is 2, so that is the answer.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →