Skip to content

26. Remove Duplicates from Sorted Array

https://leetcode.com/problems/remove-duplicates-from-sorted-array/

js
/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {
  if (!nums || !nums.length) {
    return 0
  }

  var prev = 0
  var current = 1

  while (current < nums.length) {
    if (nums[prev] !== nums[current]) {
      nums[++prev] = nums[current]
    }
    current++
  }

  return prev + 1
}
py
class Solution(object):

    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0

        prev, current = 0, 1
        while current < len(nums):
            if nums[prev] != nums[current]:
                prev += 1
                nums[prev] = nums[current]
            current += 1

        return prev + 1