Skip to content

Instantly share code, notes, and snippets.

@shalomsam
Created July 18, 2021 18:17
Show Gist options
  • Select an option

  • Save shalomsam/ba42a582fd7e117ed762656ba33ae422 to your computer and use it in GitHub Desktop.

Select an option

Save shalomsam/ba42a582fd7e117ed762656ba33ae422 to your computer and use it in GitHub Desktop.

Arrays: move zeros to the left Given an integer array, move all elements that are 0 to the left while maintaining the order of other elements in the array. The array has to be modified in-place.

Example:

Given - [1, 10, 20, 0, 59, 63, 0, 88, 0]

Result - [0, 0, 0, 1, 10, 20, 59, 63, 88]

function moveZerosToLeft(arr) {
let vaccantIndex = undefined;
let zerors = [];
for(let i = 0; i < arr.length; i++) {
let curr = arr[i];
if (curr === 0) {
for (j = i; j >= 0; j--) {
if (arr[j - 1] && (curr < arr[j - 1])) {
let interim = arr[j - 1];
arr[j - 1] = curr;
arr[j] = interim;
}
}
}
}
return arr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment