## Google Interview Question for SDE1s

• 0

Country: United States

Comment hidden because of low score. Click to expand.
0
of 0 vote

Whenever we see i-th 1 at index idx, we increase the counter by (idx - i).
E.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).

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````int swap_count(int nums[], int cnt)
{
int swap=0;
int i =0;
int zero = 0;

for(zero=0;zero < cnt; zero++)
{
if(nums[zero] == 0) break;
}

for(i = zero; i < cnt; i++)
{
if(nums[i] == 1) {
swap += (i - zero);
zero++;
}
}
return swap;
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````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;
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

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
}``````

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.