Challenge - 5 Problems
Two Pointer Duplicate Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Two Pointer Duplicate Removal
What is the output array after removing duplicates using the two-pointer method on the sorted array?
DSA Javascript
function removeDuplicates(nums) {
let i = 0;
for (let j = 1; j < nums.length; j++) {
if (nums[j] !== nums[i]) {
i++;
nums[i] = nums[j];
}
}
return nums.slice(0, i + 1);
}
const input = [1,1,2,2,3,4,4,5];
console.log(removeDuplicates(input));Attempts:
2 left
💡 Hint
Focus on how the two pointers move and how duplicates are skipped.
✗ Incorrect
The two-pointer method moves through the array, copying unique elements forward. The final array slice contains only unique values.
❓ Predict Output
intermediateLength of Array After Duplicate Removal
What is the length of the array after removing duplicates using the two-pointer method on this sorted array?
DSA Javascript
function removeDuplicates(nums) {
let i = 0;
for (let j = 1; j < nums.length; j++) {
if (nums[j] !== nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
const input = [0,0,1,1,1,2,2,3,3,4];
console.log(removeDuplicates(input));Attempts:
2 left
💡 Hint
Count how many unique numbers are in the array.
✗ Incorrect
The unique numbers are 0,1,2,3,4 so length is 5. The slow pointer i advances to 4 after placing the 5th unique element (0 at 0,1 at1,2 at2,3 at3,4 at4), returning i+1=5.
🔧 Debug
advancedIdentify the Error in Two Pointer Duplicate Removal
What error does this code produce when run?
DSA Javascript
function removeDuplicates(nums) {
let i = 0;
for (let j = 1; j <= nums.length; j++) {
if (nums[j] !== nums[i]) {
i++;
nums[i] = nums[j];
}
}
return nums.slice(0, i + 1);
}
const input = [1,1,2];
console.log(removeDuplicates(input));Attempts:
2 left
💡 Hint
Check the loop boundary condition carefully.
✗ Incorrect
The loop runs with j <= nums.length, so nums[j] is undefined on last iteration causing TypeError.
❓ Predict Output
advancedFinal Array State After Duplicate Removal
What is the final state of the array after running this two-pointer duplicate removal code?
DSA Javascript
function removeDuplicates(nums) {
let i = 0;
for (let j = 1; j < nums.length; j++) {
if (nums[j] !== nums[i]) {
i++;
nums[i] = nums[j];
}
}
return nums;
}
const input = [2,2,2,3,3,4,5,5];
console.log(removeDuplicates(input));Attempts:
2 left
💡 Hint
Only the first part of the array is overwritten with unique values.
✗ Incorrect
The unique elements are moved to the front: 2,3,4,5. The rest of the array remains unchanged.
🧠 Conceptual
expertWhy Two Pointer Method Works for Sorted Arrays
Why does the two-pointer method effectively remove duplicates only when the array is sorted?
Attempts:
2 left
💡 Hint
Think about how duplicates appear in sorted arrays.
✗ Incorrect
In sorted arrays, duplicates are next to each other, so comparing neighbors detects duplicates efficiently.
