Meta Interview Question

Move all zeroes to end of array with minimum assignment operations

Interview Answers

Anonymous

Feb 16, 2015

public static void moveZeroesToEnd(int[] arr) { if (arr == null || arr.length == 0) return; int start = 0, end = arr.length - 1; while (start < end) { if (arr[start] == 0) { while (arr[end] == 0) { end--; } if (start < end) { swap(arr, start, end); end--; } } start++; } }

3

Anonymous

Feb 14, 2015

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { class Class1 { public static void MoveAllZeroesToEnd(int []data) { // 1) skip all non-zeros at start // 2) skip all zeros at end // 3) move non-zero elements forward & // 4) put zeroes at end int i1, i2, i3, i4; for (i1 = 0; i1 i1 && data[i2] == 0; i2--); if (i1 >= i2) return; // no work // i3 - non-zero elements index for (i4 = i1, i3 = i1; i4 <= i2; i4++) { // skip zeros; if (data[i4] == 0) continue; data[i3++] = data[i4]; } for (int i = i3; i <= i2; i++) data[i] = 0; } public static void printArray(int []data) { Console.WriteLine(string.Join(", ", data)); } public static void Main() { int[][] data = { new int [] { 1, 2, 3, 0, 0, 0 }, new int [] { 1, 2, 3 }, new int [] { 1, 2, 0, 0, 3, 0, 0}, new int [] { 1, 2, 0, 3, 0, 0, 4, 0, 0, 0 } }; for (var i = 0; i < data.Length; i++) { Console.WriteLine("input {0}::", i + 1); printArray(data[i]); var input = (int [])data[i].Clone(); MoveAllZeroesToEnd(input); Console.WriteLine("output {0}::", i + 1); printArray(input); } } } }

1

Anonymous

Feb 24, 2015

simple! int f(int[] arr, int n) { int e = n; for(int i = 0; i < e; i++) { if(arr[i] == 0) { e--; arr[i] = arr[e]; arr[e] = 0; i--; } } }

Anonymous

Oct 11, 2015

Run two pointers through the array. iterate first one to find the zero and other one to find the nonzero from the first pointer. Do exchange. Till the second pointer reach end of array.