To solve the problem of finding the minimum cost required to make an array unique by removing at most one subarray, we can follow an efficient approach using several key observations and steps. Below is a detailed explanation of the approach along with the corresponding C++ implementation.
Approach:
-
First Occurrence Mapping:
- Traverse the array from left to right to record the first occurrence of each element. This helps in determining the earliest index where a duplicate appears.
-
Suffix Uniqueness:
- Iterate through the array from right to left to determine if the suffix starting at each index is unique (i.e., contains no duplicates). Store these indices for further processing.
-
Minimum First Occurrence:
- For each index where the suffix is unique, compute the minimum first occurrence of any element within that suffix. This helps in determining the split point where the prefix and suffix do not share any common elements.
-
Maximum Unique Prefix:
- Identify the maximum length of the unique prefix in the array. This is the largest possible prefix where all elements are distinct.
-
Compute Minimum Cost:
- For each valid suffix, determine the smallest removal subarray that ensures the combined prefix and suffix are unique and non-overlapping. Update the minimum cost accordingly.
-
Edge Cases:
- Handle cases where the array is already unique by returning a cost of
0.
C++ Implementation:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int uniqueArray(int n, vector<int> &arr) {
// Step 1: Compute first occurrence
// Shift elements by 100000 to handle negative values
int OFFSET = 100000;
const int MAX_VAL = 200001;
vector<int> first_occ_map(MAX_VAL, n); // Initialize with n
for(int i =0; i <n; ++i){
int x = arr[i];
int index = x + OFFSET;
if(first_occ_map[index] == n){
first_occ_map[index] = i;
}
}
// Step 2: Compute suffix_unique
vector<bool> suffix_unique(n, false);
vector<bool> seen_suffix(MAX_VAL, false);
for(int j = n-1; j >=0; --j){
int x = arr[j];
int index = x + OFFSET;
if(!seen_suffix[index]){
suffix_unique[j] = true;
seen_suffix[index] = true;
}
else{
suffix_unique[j] = false;
}
}
// Step 3: Compute min_first_occ[j]
// min_first_occ[j] = min(first_occ[x] for x in [j,n) where [j,n) is unique
// Initialize min_first_occ[n] to a large value
vector<int> min_first_occ(n+1, n*2);
for(int j = n-1; j >=0; --j){
if(suffix_unique[j]){
int x = arr[j];
int index = x + OFFSET;
min_first_occ[j] = min(first_occ_map[index], min_first_occ[j +1]);
}
else{
min_first_occ[j] = min_first_occ[j +1];
}
}
// Step 4: Find max_unique_prefix
vector<bool> seen_prefix(MAX_VAL, false);
int max_unique_prefix = n;
for(int i =0; i <n; ++i){
int x = arr[i];
int index = x + OFFSET;
if(seen_prefix[index]){
max_unique_prefix = i;
break;
}
seen_prefix[index] = true;
}
// Step 5: Iterate through j's and compute min_cost
int min_cost = n;
for(int j =0; j <=n; ++j){
if(j < n && suffix_unique[j]){
int i_val = min_first_occ[j];
if(i_val <= max_unique_prefix){
min_cost = min(min_cost, j - i_val);
}
}
// Handle j =n separately
if(j ==n){
// [j,n) is empty, i should be <= max_unique_prefix
// i can be from 0 to max_unique_prefix
// Removal [i,j) with cost =j -i
// To minimize, choose i = max_unique_prefix
// But need to ensure [0,i) is unique
// Since [0,max_unique_prefix) is unique
min_cost = min(min_cost, j - max_unique_prefix);
}
}
return min_cost;
}
};
// Driver code to test the solution
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<int> arr(n);
for(auto &x: arr) cin>>x;
Solution sol;
cout<<sol.uniqueArray(n, arr)<<'\n';
}
}
Explanation of the Code:
-
First Occurrence Mapping:
- We shift the array elements by
100000 to accommodate negative values and store their first occurrences in first_occ_map.
-
Suffix Uniqueness:
- Using a
seen_suffix boolean array, we mark each index j as true in suffix_unique if the suffix [j, n) is unique.
-
Minimum First Occurrence:
- We compute
min_first_occ[j] by iterating from the end of the array to the beginning. If the suffix [j, n) is unique, we update min_first_occ[j] with the minimum of the first occurrence of arr[j] and min_first_occ[j + 1].
-
Maximum Unique Prefix:
- By iterating through the array from the start, we determine the maximum length
max_unique_prefix where the prefix [0, i) is unique.
-
Compute Minimum Cost:
- We iterate through all valid suffix starting points
j and calculate the corresponding i using min_first_occ[j]. If i is within the max_unique_prefix, we update the min_cost with the smallest removal subarray length j - i.
-
Edge Case Handling:
- The code also handles cases where the entire array or large portions of it are unique, ensuring the minimum cost is correctly identified as
0.
Complexity Analysis:
- Time Complexity: O(n), where n is the length of the array. Each step involves linear traversals.
- Space Complexity: O(n), primarily for auxiliary arrays used to store occurrences and uniqueness information.
Example:
Consider the array [1, 2, 3, 1, 2]:
- First Occurrence:
{1: 0, 2: 1, 3: 2}
- Suffix Unique:
[False, False, True, True, True]
- Min First Occurrence:
[0, 0, 0, 0, 1, INF]
- Max Unique Prefix:
3
- Minimum Cost: The algorithm correctly identifies that removing the subarray
[0,1] (cost 2) results in a unique array [3, 1, 2].
Conclusion:
This approach efficiently computes the minimum cost required to make the array unique by leveraging prefix and suffix uniqueness properties along with careful tracking of element occurrences. The implementation ensures optimal performance even for large input sizes.