Given a sorted array nums, remove the duplicates in-place such that duplicates are allowed at most twice and return the new length. Do not allocate extra space for another array; you must do this by modifying the input array in-place with O(1) extra memory.
Input: nums = [1,1,1,2,2,3]
Output: 5, nums = [1,1,2,2,3,_]
Input: nums = [0,0,1,1,1,1,2,3,3]
Output: 7, nums = [0,0,1,1,2,3,3,_,_]
1 <= nums.length <= 3 * 10^4-10^4 <= nums[i] <= 10^4nums is sorted in non-decreasing order.1 <= nums.length).-10^4 to 10^4.We’ll use a two-pointer approach to efficiently manage the in-place updates:
insert_pos starting at index 0.nums array.insert_pos-2.insert_pos is less than 2, directly insert the element as we need at least two items to compare.insert_pos-2.
insert_pos and increment insert_pos.insert_pos will be the new length of the modified array.def removeDuplicates(nums):
if not nums:
return 0
insert_pos = 0
for num in nums:
if insert_pos < 2 or num != nums[insert_pos - 2]:
nums[insert_pos] = num
insert_pos += 1
return insert_pos
nums is empty, immediately return 0.insert_pos serves as the place to insert the next valid element for the modified array.nums:
insert_pos is less than 2: Directly insert the element, as there are fewer than 2 elements to compare.num is not equal to the element located at insert_pos - 2, insert num at position insert_pos and increment insert_pos.n is the number of elements in the input array nums. This is because we iterate through each element exactly once.This solution leverages the sorted property of the array and uses constant space for efficient in-place modifications.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?