Sobes.tech
Senior

Given a sorted array of numbers that contains duplicate elements, remove the duplicates in-place (directly in the original array) and return the size of the resulting array. Example: Input: nums = [0,0,1,1,1,2,2,3,3,4] Output: 5, nums = [0,1,2,3,4,_,_,_,_,_] Explanation: The array contains 5 unique elements. Place them in the first five positions of the array and return the number 5. The remaining elements in the array can be any values.

sobes.tech AI

Answer from AI

To remove duplicates from a sorted array in-place, you can use two pointers: one for traversing the array, and the other for recording the position of unique elements.

Idea:

  • Initialize writeIndex at 1 (the first unique element is already in place).
  • Traverse the array with readIndex from 1 to the end.
  • If the current element is not equal to the previous one, write it to nums[writeIndex] and increment writeIndex.

In the end, writeIndex is the count of unique elements.

Example in Go:

func removeDuplicates(nums []int) int {
    if len(nums) == 0 {
        return 0
    }
    writeIndex := 1
    for readIndex := 1; readIndex < len(nums); readIndex++ {
        if nums[readIndex] != nums[readIndex-1] {
            nums[writeIndex] = nums[readIndex]
            writeIndex++
        }
    }
    return writeIndex
}

// Usage:
// nums := []int{0,0,1,1,1,2,2,3,3,4}
// length := removeDuplicates(nums)
// fmt.Println(length) // 5
// fmt.Println(nums[:length]) // [0 1 2 3 4]