You are given an array arr of n integers. In one operation, you choose any two distinct values x and y that appear in arr and replace every occurrence of x with y. Return the minimum number of operations needed to make the array valid.
An array is valid if every distinct value forms exactly one contiguous block. This means that for any value v, all occurrences of v must appear next to each other in a single continuous segment. Values do not all need to be the same. For example,
[1, 1, 2, 2, 3]is valid because each distinct value appears in one contiguous block.[1, 2, 1, 3]is not valid because value1appears in two separated blocks, with value2between them.
If arr is already valid, return 0.
arr = [1, 2, 1] return = 1
Value 1 appears at two positions with value 2 between them. Replacing every occurrence of 2 with 1 yields [1, 1, 1], where 1 forms a single contiguous block. One operation is sufficient.
arr = [1, 2, 3, 1, 2, 3] return = 2
One way to make the array valid is:
- Replace every occurrence of
2with1, giving[1, 1, 3, 1, 1, 3]. - Replace every occurrence of
3with1, giving[1, 1, 1, 1, 1, 1].
Now the only remaining distinct value is 1, so it forms a single contiguous block
arr = [1, 2, 1, 2] return = 1
- 1 ≤
n≤ 1000 - 1 ≤
arr[i]≤ 1000
- Get the Fewest Moves (~Operations~)~Seen Jun 2026
- Create Array Generator ServiceSeen Jun 2026
- Minimum Merge ConflictsOA · Seen Jun 2026
- Get Minimum AmountOA · Seen Jun 2026
- Drone Delivery RouteOA · Seen Jun 2026
- Sort Bug Report FrequenciesOA · Seen Jun 2026
- Maximum Equal Parts for PrefixesOA · Seen Jun 2026
- Count Promotional PeriodsOA · Seen Jun 2026
public int minimumOperationsToMakeArrayValid(int[] arr) {
// write your code here
}