AmazonOA #256
Make Value Groups Contiguous
Estimated MediumJudge-ready
Topics (AI-labelled)Prefix & RangesUnion-Find
One operation chooses two different values x and y and replaces every x in the array with y simultaneously. In the end, all occurrences of each value must lie in one contiguous block; find the minimum number of operations. You cannot change just one occurrence, nor delete elements.
Input
The first line contains n; the second line contains the array. This site uses 1≤n≤200000, −10^9≤element≤10^9.
Output
Output a single integer, the answer.
Example 1
Input:
4
1 2 3 1
Output:
2
Example 2
Input:
3
1 2 3
Output:
0
Example 3
Input:
6
1 2 1 3 4 3
Output:
2
Example notes
The answers are 2, 0 and 2. The first example is not only about handling the repeated 1s; the 2 and 3 sandwiched between the two 1s must also be merged in the end.
Editorial
Loading solution…