Challenge - 5 Problems
Two Pointer Mastery
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 C++
int removeDuplicates(vector<int>& nums) { if (nums.empty()) return 0; int i = 0; for (int j = 1; j < nums.size(); j++) { if (nums[j] != nums[i]) { i++; nums[i] = nums[j]; } } return i + 1; } vector<int> nums = {1,1,2,2,3,4,4,5}; int length = removeDuplicates(nums); for (int k = 0; k < length; k++) { cout << nums[k] << " "; }
Attempts:
2 left
💡 Hint
Focus on how the two pointers move and overwrite duplicates.
✗ Incorrect
The two-pointer method moves the slow pointer only when a new unique element is found, overwriting duplicates. The final array up to the returned length contains unique elements.
🧠 Conceptual
intermediateUnderstanding Two Pointer Roles
In the two-pointer approach to remove duplicates from a sorted array, what is the main role of the slow pointer?
Attempts:
2 left
💡 Hint
Think about how the array is modified in-place.
✗ Incorrect
The slow pointer marks the position where the next unique element is placed, effectively building the array of unique elements at the start.
🔧 Debug
advancedIdentify the Bug in Duplicate Removal Code
What error will this code cause when removing duplicates from a sorted array?
int removeDuplicates(vector& nums) {
int i = 0;
for (int j = 1; j < nums.size(); j++) {
if (nums[j] != nums[i]) {
i++;
nums[j] = nums[i];
}
}
return i + 1;
}
Attempts:
2 left
💡 Hint
Check the assignment inside the if condition carefully.
✗ Incorrect
The assignment should be nums[i] = nums[j], but the code assigns nums[j] = nums[i], overwriting the wrong element and corrupting data.
❓ Predict Output
advancedOutput Length After Removing Duplicates
What is the returned length after removing duplicates from the sorted array using the two-pointer method?
DSA C++
vector<int> nums = {0,0,1,1,1,2,2,3,3,4}; int removeDuplicates(vector<int>& nums) { if (nums.empty()) return 0; int i = 0; for (int j = 1; j < nums.size(); j++) { if (nums[j] != nums[i]) { i++; nums[i] = nums[j]; } } return i + 1; } int length = removeDuplicates(nums); cout << length;
Attempts:
2 left
💡 Hint
Count unique elements in the array.
✗ Incorrect
The unique elements are 0,1,2,3,4 so the length is 5.
🚀 Application
expertApplying Two Pointer Method on Large Sorted Array
Given a sorted array of 1 million elements with many duplicates, which is the best reason to use the two-pointer method to remove duplicates in-place?
Attempts:
2 left
💡 Hint
Think about memory and time efficiency for large data.
✗ Incorrect
The two-pointer method removes duplicates in-place with O(1) extra space and O(n) time, ideal for large arrays.
