Pergunta de entrevista da empresa Meta

remove all zeros of an array to the right

Respostas da entrevista

Sigiloso

10 de dez. de 2015

private static int[] moveZerosToRight(int[] a) { for(int i = 0; i

Sigiloso

1 de abr. de 2016

#include using namespace std; //swap two elements template void swap(T arr[], int val1, int val2) { T temp = arr[val1]; arr[val1] = arr[val2]; arr[val2] = temp; } //move all zeros of the array to the left void moveZeros(int arr[], int init, int end) { int p = end; for (int i = end-1; i >= init; --i) { if (arr[i] == 0) { --p; swap(arr, i, p); } } }

Sigiloso

21 de ago. de 2016

The other solution is correct given the description, but almost every single time I've seen this question the requirement is that you maintain the relative order of the rest of the elements. It's still very simple, keep a counter going forward noting how many zeroes you have countered, move each non-zero element backwords by that many, and once you hit the end, fill from the last overwritten index onwards with zeroes. [1, 0, 2, 0, 3] Loop thru index of array 1. [1, 0, 2, 0, 3] - the first element is put into 0 index before it 2. [1, 0, 2, 0, 3] - counter = 1 3. [1, 2, 2, 0, 3] - the 3rd element is put into 1 index before it 4. [1, 2, 2, 0, 3] - counter = 2 5. [1, 2, 3, 0, 3] - the 5th element is put into 2 index before it Reached end, start feeling zeroes from end - counter 4. [1, 2, 3, 0, 3] - lucky 0 5. [1, 2, 3, 0, 0] - done