Why Two Pointer Technique Beats Brute Force in DSA Python - Performance Analysis
We want to see why using two pointers is faster than checking every pair one by one.
How does the number of steps change when input grows?
Analyze the time complexity of the following code snippet.
def two_sum_sorted(arr, target):
left, right = 0, len(arr) - 1
while left < right:
current_sum = arr[left] + arr[right]
if current_sum == target:
return True
elif current_sum < target:
left += 1
else:
right -= 1
return False
This code checks if two numbers in a sorted list add up to a target using two pointers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop moves pointers through the array.
- How many times: At most, each pointer moves across the array once, so up to n steps total.
As the list gets bigger, the steps grow roughly in a straight line with the size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The steps increase directly with input size, not faster.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the list gets bigger.
[X] Wrong: "Two pointers still check every pair, so it's as slow as brute force."
[OK] Correct: Two pointers smartly skip many pairs by moving inward, so they do fewer checks than brute force.
Knowing why two pointers are faster helps you explain your choices clearly and shows you understand efficient problem solving.
"What if the input array was not sorted? How would the time complexity change if we still tried two pointers?"
Practice
Solution
Step 1: Understand brute force approach
Brute force often uses nested loops, leading to higher time complexity like O(n²).Step 2: Analyze two pointer technique
Two pointers move through the array in a single pass, reducing time complexity to O(n).Final Answer:
It reduces time complexity by avoiding nested loops -> Option DQuick Check:
Two pointer = faster than brute force [OK]
- Thinking two pointer always sorts the array
- Confusing memory use with speed
- Assuming recursion is needed
arr in Python?Solution
Step 1: Identify valid indices in Python list
Python lists start at index 0 and end at len(arr) - 1.Step 2: Check pointer initialization
Left pointer should be 0 (start), right pointer should be len(arr) - 1 (end).Final Answer:
left = 0; right = len(arr) - 1 -> Option AQuick Check:
Start = 0, End = length-1 [OK]
- Starting pointers outside valid index range
- Using 1-based indexing in Python
- Setting right pointer to len(arr) instead of len(arr)-1
def two_sum_sorted(arr, target):
left, right = 0, len(arr) - 1
while left < right:
current_sum = arr[left] + arr[right]
if current_sum == target:
return [left, right]
elif current_sum < target:
left += 1
else:
right -= 1
return [-1, -1]
print(two_sum_sorted([1, 3, 4, 5, 7, 10], 9))Solution
Step 1: Trace the execution step-by-step
arr = [1,3,4,5,7,10]
left=0 (1), right=5 (10), sum=11 >9 -> right=4
left=0 (1), right=4 (7), sum=8 <9 -> left=1
left=1 (3), right=4 (7), sum=10 >9 -> right=3
left=1 (3), right=3 (5), sum=8 <9 -> left=2
left=2 (4), right=3 (5), sum=9 ==9 -> return [2, 3]Final Answer:
[2, 3] -> Option CQuick Check:
arr[2] + arr[3] = 4 + 5 = 9 [OK]
- Not updating pointers correctly
- Returning wrong indices
- Confusing array values with indices
def has_pair(arr, target):
left, right = 0, len(arr)
while left < right:
if arr[left] + arr[right] == target:
return True
elif arr[left] + arr[right] < target:
left += 1
else:
right -= 1
return FalseSolution
Step 1: Check pointer initialization
right is set to len(arr), which is out of valid index range (max index is len(arr)-1).Step 2: Correct pointer initialization
right should be len(arr) - 1 to point to last element.Final Answer:
right should be initialized to len(arr) - 1 -> Option BQuick Check:
Valid indices = 0 to length-1 [OK]
- Using len(arr) as index causes IndexError
- Changing left pointer start incorrectly
- Misusing while loop condition
arr and a target sum, how does the two pointer technique efficiently find all unique pairs that add up to the target compared to brute force?Solution
Step 1: Understand brute force approach
Brute force checks every pair with nested loops, O(n²) time.Step 2: Explain two pointer efficiency
Two pointers start at ends, move inward based on sum comparison, skipping duplicates to avoid repeats, achieving O(n) time.Final Answer:
By moving pointers inward and skipping duplicates, it avoids checking all pairs -> Option AQuick Check:
Two pointer skips pairs, brute force checks all [OK]
- Thinking sorting happens multiple times
- Confusing recursion with two pointer
- Assuming nested loops are used in two pointer
Ready to prove it?
Pass the test and this pattern moves unknown
