Google Interview Question for SDE1s


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).

- Alex December 14, 2017 | Flag Reply
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;
}

- Anonymous December 17, 2017 | Flag Reply
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;
}

- lxfuhuo January 08, 2018 | Flag Reply
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
}

- BW January 24, 2021 | Flag Reply


Add a Comment
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.

Learn More

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.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More