Google Interview Question
SDE1sCountry: United States
int inner_min_swap(vector<int> &vec){
int l = 0;
int sum = 0;
for (int i = 0; i < vec.size(); ++i){
if (vec[i] == 0){
sum += i - l;
++l;
}
}
return sum;
}
int min_swap(vector<int> vec){
int ans = inner_Min_swap(vec);
reverse(vec.begin(), vec.end());
ans = min(inner_min_swap(vec));
return ans;
}
Iterate from the right side of the array towards the left. When zero is encountered, add the number of moves it would take to move it to the right of all the 1s to its right.
func minSwaps(arr []int) {
n := len(arr)
onesSeen := 0
moves := 0
for i:=n-1; i>=0; i-- {
if arr[i]==1 {
onesSeen++
} else {
moves += onesSeen
}
}
return moves
}
Whenever we see i-th 1 at index idx, we increase the counter by (idx - i).
- Alex December 14, 2017E.g. for 0, 1, 1, 0, 0, we find the 0-th 1 at index 1, and we find the 1-st 1 at index 2: (1 - 0) + (2 - 1) = 2.
Why? Because an increment in index of 1 increments number of swaps needed, and increment in amount of ones decrements number of swaps needed (because 1s gather at the left side).