Top Interview 150
When working with sorted arrays, one common interview problem is removing duplicates in-place while maintaining the relative order of elements. Letβs break down LeetCode 26: Remove Duplicates from Sorted Array and walk through an efficient solution in JavaScript.
π Problem Description
Given an integer array nums
sorted in non-decreasing order, remove duplicates in-place so that each unique element appears only once. Return the count of unique elements (k
) and modify the array so the first k
elements contain the unique values.
The rest of the array doesn't matter.
π‘ Examples
Example 1
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Example 2
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
π§ Key Insights
- Sorted input: Since the array is sorted, duplicates will always appear consecutively.
- Two-pointer technique: Use two pointers to traverse and overwrite the array while identifying unique elements.
π JavaScript Solution: Two-Pointer Approach
Hereβs the implementation:
var removeDuplicates = function(nums) {
if (nums.length === 0) return 0; // Handle edge case
let k = 1; // Pointer for the next unique element position
for (let i = 1; i < nums.length; i++) {
if (nums[i] !== nums[i - 1]) {
nums[k] = nums[i];
k++;
}
}
return k; // Count of unique elements
};
π How It Works
- Initialize pointers:
- Start
k
at 1 to represent the position of the next unique element.
- Start
- Iterate through the array:
- If
nums[i]
is different from the previous element, itβs unique. Copy it tonums[k]
and incrementk
.
- If
- Return
k
:- This is the count of unique elements. The first
k
elements innums
now hold these values.
- This is the count of unique elements. The first
π Complexity Analysis
Time Complexity: O(n)
, where n is the length of the array. We traverse the array once.
Space Complexity: O(1)
, since no extra space is used.
π Dry Run
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: k = 5, nums = [0,1,2,3,4,_,_,_,_,_]
β¨ Pro Tips for Interviews
- Ask clarifying questions:
- Confirm if the order of elements must be preserved.
- Consider edge cases:
- Empty array.
- Array with all identical elements.
- Explain the two-pointer logic clearly:
- Itβs simple but highly effective for problems requiring in-place modifications.
π Learn More
Check out the full explanation and code walkthrough on Dev.to:
π Remove Element - JavaScript Solution
How would you approach this problem? Let me know in the comments! π
Top comments (0)