Mental Model
Use two pointers to keep track of unique elements and overwrite duplicates in place.
Analogy: Imagine sorting your bookshelf and moving only unique books forward, skipping duplicates as you go.
[1, 1, 2, 2, 3, 4, 4] ↑ ↑ slow fast
[1, 1, 2, 2, 3, 4, 4] ↑ ↑ slow fast
[1, 1, 2, 2, 3] slow=0 ↑ fast=1 ↑
[1, 1, 2, 2, 3] slow=0 ↑ fast=2 ↑
[1, 2, 2, 2, 3] slow=1 ↑ fast=2 ↑
[1, 2, 2, 2, 3] slow=1 ↑ fast=3 ↑
[1, 2, 2, 2, 3] slow=1 ↑ fast=4 ↑
[1, 2, 3, 2, 3] slow=2 ↑ fast=4 ↑
[1, 2, 3, 2, 3] slow=2 ↑ fast=4 ↑
[1, 2, 3, 2, 3] Unique elements count: 3
class Solution { removeDuplicates(nums) { if (nums.length === 0) return 0; let slow = 0; for (let fast = 1; fast < nums.length; fast++) { if (nums[fast] !== nums[slow]) { slow++; nums[slow] = nums[fast]; } } return slow + 1; } } // Driver code const nums = [1, 1, 2, 2, 3]; const solution = new Solution(); const length = solution.removeDuplicates(nums); let output = ''; for (let i = 0; i < length; i++) { output += nums[i] + (i < length - 1 ? ' -> ' : ' -> null'); } console.log(output); console.log('Unique elements count:', length);
if (nums.length === 0) return 0;for (let fast = 1; fast < nums.length; fast++) {if (nums[fast] !== nums[slow]) {slow++;nums[slow] = nums[fast];return slow + 1;if (nums.length === 0) return 0;
if (nums[fast] !== nums[slow]) {if (nums[fast] !== nums[slow]) {nums in JavaScript?nums = [1, 1, 2, 2, 3]?nums. What is the bug?
let i = 0;
for (let j = 1; j < nums.length; j++) {
if (nums[j] !== nums[i]) {
i = j;
nums[i] = nums[j];
}
}
return i + 1;nums = [0,0,1,1,1,2,2,3,3,4], what will be the length of the array after removing duplicates using the two-pointer method, and what will the first part of the array look like?Pass the test and this pattern moves unknown