Skip to content

Instantly share code, notes, and snippets.

@chalu
Last active February 3, 2024 01:21
Show Gist options
  • Save chalu/9ea7f93f23bb2363d5ad56e83798eea0 to your computer and use it in GitHub Desktop.
Save chalu/9ea7f93f23bb2363d5ad56e83798eea0 to your computer and use it in GitHub Desktop.
Remove Duplicates From Sorted Array II
// Leetcode Question
// https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/?envType=study-plan-v2&envId=top-interview-150
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
// ASC [1, 1, 1, 1, 1, 2, 2, 3, 4, 4, 5]
// index 0 1 2 3 4 5 6 7 8 9 10
let index = 0;
const MAX_UNIQUE_ITEM_COUNT = 2;
while (index < nums.length) {
if(
// do we have anything two steps ahead in the array
nums[index + MAX_UNIQUE_ITEM_COUNT]
// and if current element is same as the element two steps ahead
&& (nums[index] == nums[index + MAX_UNIQUE_ITEM_COUNT])
) {
pruneArray(nums, index + MAX_UNIQUE_ITEM_COUNT, nums[index]);
}
index += 1;
}
};
const pruneArray = (arr, startIndex, num) => {
let deleteCount = 0;
let index = startIndex;
while (index < arr.length && arr[index] == num) {
deleteCount += 1;
index += 1;
}
if (deleteCount >= 1) {
arr.splice(startIndex, deleteCount);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment