Remove Duplicates Solution for Cognizant
Company: Cognizant · Difficulty: Easy · Topics: Array, Two Pointers
Problem Statement
Given a sorted array, remove duplicates in-place and return the new length.
Examples
Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Approach
Use two pointers: one to track the position for next unique element, another to scan the array.
Time and Space Complexity
- Time Complexity: O(n)
- Space Complexity: O(1)