Skip to content

Instantly share code, notes, and snippets.

@croespino
Last active May 2, 2023 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save croespino/cb23d83f6fb7141dc71efd97e1289ca9 to your computer and use it in GitHub Desktop.
Save croespino/cb23d83f6fb7141dc71efd97e1289ca9 to your computer and use it in GitHub Desktop.
Given a non-empty array containing only non-negative integers, return the list with trailing and leading zeroes removed.
import { equal } from "https://deno.land/x/equal/mod.ts";
function getArrayWithZeroesRemoved(arr, startIndex, endIndex) {
const arrayWithZeroesRemoved = new Array(endIndex - startIndex + 1);
let i = 0;
while (startIndex <= endIndex) {
arrayWithZeroesRemoved[i] = arr[startIndex];
i++;
startIndex++;
}
return arrayWithZeroesRemoved;
}
// O(n) time & O(n) space - where n is the length of the input array
export default function removeZeroes(arr: number[]): number[] {
let leftPointer = 0;
let rightPointer = arr.length - 1;
let startIndex = leftPointer;
let endIndex = rightPointer;
let startIndexFound = false;
let endIndexFound = false;
while (leftPointer <= rightPointer) {
if (arr[leftPointer] !== 0 && !startIndexFound) {
startIndex = leftPointer;
startIndexFound = true;
}
if (arr[rightPointer] !== 0 && !endIndexFound) {
endIndex = rightPointer;
endIndexFound = true;
}
if (startIndexFound && endIndexFound) {
return getArrayWithZeroesRemoved(arr, startIndex, endIndex);
}
if (!endIndexFound) {
rightPointer--;
}
if (!startIndexFound) {
leftPointer++;
}
}
return [];
}
console.assert(equal(removeZeroes([0, 0, 0, 3, 1, 4, 1, 5, 9, 0, 0, 0, 0]), [3, 1, 4, 1, 5, 9]));
console.assert(equal(removeZeroes([0, 0, 0]), []));
console.assert(equal(removeZeroes([8]), [8]));
console.assert(equal(removeZeroes([0, 3, 0, 4, 0]), [3, 0, 4]));
console.assert(equal(removeZeroes([0, 3, 4]), [3, 4]));
console.assert(equal(removeZeroes([3, 4, 0]), [3, 4]));
console.assert(equal(removeZeroes([3, 4]), [3, 4]));
console.assert(equal(removeZeroes([2, 3, 4]), [2, 3, 4]));
console.assert(equal(removeZeroes([0]), []));
console.assert(equal(removeZeroes([0, 0, 0, 1, 23]), [1, 23]));
console.assert(equal(removeZeroes([22, 2, 0, 0]), [22, 2]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment