Problem Statement

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Remove Duplicates from Sorted Array - LeetCode

Approach

  1. Keep a pointer to the last unique element. Set it to 0 initially.
  2. Iterate through the array from the second element.
  3. If the current element is different from the last unique element, increment the pointer. Set the element at pointer equal to the current element.
  4. Continue until the end of the array.
  5. The number of unique elements is the pointer + 1.

Solution in Swift

class Solution {
    func removeDuplicates(_ nums: inout [Int]) -> Int {        
        guard nums.count > 1 else { return nums.count }

        var lastUniqueIndex = 0

        for currentIndex in 1..<nums.count where nums[currentIndex] != nums[lastUniqueIndex] {
            lastUniqueIndex += 1
            nums[lastUniqueIndex] = nums[currentIndex]
        }

        return lastUniqueIndex + 1
    }
}

Complexity

  • Time complexity: \(O(n)\)
  • Space complexity: \(O(1)\)