Sobes.tech
Senior

Difficulty: EASY Given a sorted array of numbers with duplicates, remove duplicates in-place 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 has 5 unique elements. Place them at the first five positions and return 5. Remaining elements can be any.

sobes.tech AI

Answer from AI

To remove duplicates from a sorted array in-place, you can use two pointers: one for iterating through the array, and another for recording unique elements. The idea is that when a new unique element is encountered, it is written at the position of the next unique index.

Example in Go:

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

// Usage:
// nums := []int{0,0,1,1,1,2,2,3,3,4}
// length := removeDuplicates(nums)
// now the first length elements of nums are the unique ones

Thus, the function returns the number of unique elements, and the first elements of the array contain these unique values. The remaining elements of the array can be any values.

Difficulty: EASY Given a sorted array of numbers with… - sobes.tech