Remove Duplicates From Sorted Array Ii
To solve this coding challenge, we need to modify the input array
in-place to ensure that each element appears at most twice while maintaining the order of the elements. The goal is to return the length of the modified array where each unique element appears at most twice.
nums
Explanation
- Understanding the Problem :
-
The input array
nums
- We need to ensure that no element appears more than two times in the modified array.
-
The modification should be done in-place, which means we should not use any additional arrays or storage; instead, we should transform
nums
-
We need to return the length
k
- Example Analysis :
-
Example 1: For
nums = [1,1,1,2,2,3]
[1,1,2,2,3, _]
k = 5
-
Example 2: For
nums = [0,0,1,1,1,1,2,3,3]
[0,0,1,1,2,3,3,_,_]
k = 7
- Approach :
-
If the length of
nums
-
Use a pointer
count
-
Iterate through the array starting from the third element. If the current element is different from the element
count - 2
count
-
Increment
count
- Initial Setup :
- Check if the length of the array is less than or equal to 2. If true, return the length of the array directly.
- Using a Count Pointer :
-
Initialize
count
- Iterate over the array starting from index 2.
-
If the current element is different from the element at
count - 2
count
- Iteration Logic :
-
For each element starting from index 2, compare it with the element at
count - 2
-
Update the element at
count
count
- Continue this process until the end of the array is reached.
- Return the Result :
-
Return the value of
count
- Checking Length :
-
Before proceeding, we check if the length of
nums
nums
- Initial Setup :
-
We start with
count
- Main Loop :
- We iterate from the third element (index 2) to the end of the array.
-
In the loop, for each element at index
i
count - 2
-
If they are different, it means that this element can be added to our modified array. We place the element at the position
count
count
- Returning Result :
-
Finally, we return the value of
count
Detailed Steps in Pseudocode
Pseudocode
# Function to remove duplicates from sorted array
function removeDuplicates(nums):
# If the array length is less than or equal to 2, return its length
if length of nums <= 2:
return length of nums # Array is already valid
# Initialize the pointer for placing non-duplicate elements
count = 2
# Traverse the array starting from the third element
for i from 2 to length of nums - 1:
# Check if the current element is different from the element `count - 2` positions back
if nums[i] != nums[count - 2]:
# Place the current element at the position `count`
nums[count] = nums[i]
# Increment the count
count += 1
# Return the count, which is the length of the modified array
return count