Interview Question

Software Engineering New Grad Interview

-London, England

Meta

Phone interview questions: Given an array of numbers (1,2,3,8,0,2,2,0,10), move all 0s to the right end and all other numbers to the left while keeping relative order of non-zero numbers. Has to be linear in time and in-place.

AnswerAdd Tags

Interview Answers

5 Answers

0

Similar to quickSelect algo.

Anonymous on

0

Same idea that in-place partition for quicksort, swap them if the number is 0, at the end you will have all the 0's in the right side

Saúl on

0

array = [1,2,3,4,0,5,6,0,7,8] for (i = 0, z = 0, l = array.length; i < l; i++) { if (i < l - z) { if (array[i] === 0) z++ else array[i - z] = array[i] } else { array[i] = 0 } }

Alexander Holman on

0

function moveZeroesToEnd(array $array) { for ($i = 0, $z = 0, $l = count($array); $i < $l; $i++) { if ($array[$i] === 0) { $z++; } elseif ($z) { $array[$i - $z] = $array[$i]; $array[$i] = 0; } } return $array; }

Alexander Holman on

0

$arr = array(1,2,3,8,0,2,2,0,10); $nonz = $zeros = array(); foreach($arr as $singleElement) { if($singleElement == 0) { $zeros[] = 0; } else { $nonz[] = $singleElement; } } print_r(array_merge($zeros,$nonz));

Tareq Al-Zubaidi on

Add Answers or Comments

To comment on this, Sign In or Sign Up.