Challenge - 5 Problems
Two Pointer Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
ā Predict Output
intermediateOutput of Brute Force vs Two Pointer Sum Check
Given the two functions below that check if any two numbers in a sorted array sum to a target, what is the output when called with array [1, 2, 3, 4, 6] and target 8?
DSA Go
func bruteForce(arr []int, target int) bool { for i := 0; i < len(arr); i++ { for j := i + 1; j < len(arr); j++ { if arr[i]+arr[j] == target { return true } } } return false } func twoPointer(arr []int, target int) bool { left, right := 0, len(arr)-1 for left < right { sum := arr[left] + arr[right] if sum == target { return true } else if sum < target { left++ } else { right-- } } return false } fmt.Println(bruteForce([]int{1, 2, 3, 4, 6}, 8)) fmt.Println(twoPointer([]int{1, 2, 3, 4, 6}, 8))
Attempts:
2 left
š” Hint
Think about how both methods check pairs and if they find the sum 8.
ā Incorrect
Both brute force and two pointer methods find the pair (2,6) that sums to 8, so both return true.
š§ Conceptual
intermediateWhy Two Pointer is More Efficient Than Brute Force
Why does the two pointer technique usually run faster than brute force when checking pairs in a sorted array?
Attempts:
2 left
š” Hint
Think about how many pairs each method checks.
ā Incorrect
Two pointer moves from both ends inward, checking pairs in linear time, while brute force checks all pairs, which is quadratic time.
š§ Debug
advancedIdentify the Bug in Two Pointer Implementation
What error will this two pointer code produce when run on array [1, 3, 5, 7] with target 10?
DSA Go
func twoPointerBug(arr []int, target int) bool { left, right := 0, len(arr)-1 for left < right { sum := arr[left] + arr[right] if sum == target { return true } else if sum < target { left++ } else { right-- } } return false }
Attempts:
2 left
š” Hint
Check how the right pointer is initialized.
ā Incorrect
The right pointer is set to len(arr), which is outside valid index range (0 to len(arr)-1), causing index out of range error.
š Application
advancedUsing Two Pointer to Find All Unique Pairs Summing to Target
Given a sorted array, which code snippet correctly prints all unique pairs that sum to the target 7?
Attempts:
2 left
š” Hint
Check loop conditions and pointer movements carefully.
ā Incorrect
Option D correctly uses left < right and moves pointers inward after printing pairs. Option D uses <= which can cause duplicate or invalid pairs. Option D moves pointers in wrong directions. Option D is brute force.
š§ Conceptual
expertWhy Two Pointer Technique Requires Sorted Input
Why does the two pointer technique require the input array to be sorted to work correctly?
Attempts:
2 left
š” Hint
Think about how the pointers decide which way to move.
ā Incorrect
Two pointer moves left or right pointer based on whether sum is less or greater than target, which only works if array is sorted.
