Sponsored
Sponsored
This approach uses the two-pointer technique to traverse the array and modify it in-place. The 'write' pointer tracks where the next unique element should be written, ensuring each appears at most twice. The 'read' pointer goes through the array, checking each element.
Time Complexity: O(n), Space Complexity: O(1), where n is the length of the input array.
1def removeDuplicates(nums):
2 if len(nums) <= 2:
3 return len(nums)
4
5 write = 2
6
7 for read in range(2, len(nums)):
8 if nums[read] != nums[write - 2]:
9 nums[write] = nums[read]
10 write += 1
11
12 return write
13
This Python solution uses two pointers: 'write' initialized at position 2 and 'read' iterating from 2 to the end of the array. The condition nums[read] != nums[write - 2]
ensures that we only allow two instances of each element.
This approach utilizes a variable to track the count of each duplicate as we iterate through the sorted array. The array is overwritten by resetting the duplicate counter each time a new element is found.
Time Complexity: O(n), Space Complexity: O(1).
1int removeDuplicates(int* nums, int numsSize)
The C solution uses a count variable to keep track of consecutive duplicates. For each element checked, the count is updated, and elements are copied based on whether they meet the condition of appearing at most twice.