arcbjorn

thoughtbook

Friday, January 6, 2023

Remove duplicates from sorted array

Leetcode 26 problem.

Typescript

  • Time complexity: O(n)O(n) - n is a length of numbers' array
  • Auxiliary space: O(1)O(1) - constant amount of space
function removeDuplicates(nums: number[]): number {
    let count = 0;
    
    for (let i = 0; i < nums.length; i++) {
        // skip already registered number
        if (i < nums.length - 1 && nums[i] == nums[i + 1]) {
            continue;
        }

        // register number
        nums[count] = nums[i];
        // increment total
        count++;
    }
    
    return count;
};
Creative Commons Licence