Two Pointer Technique on Arrays in DSA Python - Time & Space Complexity
We want to understand how fast the two pointer technique works when scanning arrays.
How does the number of steps grow as the array gets bigger?
Analyze the time complexity of the following code snippet.
def two_pointer_example(arr, target):
left = 0
right = 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 any two numbers in a sorted array add up to a target value using two pointers.
- Primary operation: The while loop moves the left and right pointers through the array.
- How many times: Each pointer moves at most from one end to the other, so together they move at most n steps.
As the array size grows, the total steps grow roughly in a straight line with the number of elements.
| 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 or slower.
Time Complexity: O(n)
This means the time to run grows in a straight line with the size of the array.
[X] Wrong: "The two pointer method checks every pair, so it must be O(n²)."
[OK] Correct: The pointers move inward without repeating pairs, so total steps are only about n, not n squared.
Understanding this technique shows you can solve problems efficiently by scanning arrays smartly, a skill many interviews value.
"What if the array was not sorted? How would the time complexity change if we still tried this two pointer approach?"
Practice
Two Pointer Technique when used on arrays?Solution
Step 1: Understand the two pointer concept
The technique uses two pointers (indices) to traverse the array, often starting from opposite ends or different positions.Step 2: Recognize the purpose
This helps solve problems efficiently by reducing the number of iterations compared to nested loops.Final Answer:
Use two indices to scan the array from different ends or positions simultaneously -> Option CQuick Check:
Two pointers scan array ends or positions [OK]
- Confusing two pointers with using two separate arrays
- Assuming sorting is always required
- Thinking recursion is part of two pointer technique
left and right for an array arr in Python?Solution
Step 1: Identify valid pointer positions
In Python, array indices start at 0, so the left pointer should start at 0.Step 2: Set right pointer correctly
The right pointer should be at the last valid index, which is length of array minus 1.Final Answer:
left = 0; right = len(arr) - 1 -> Option AQuick Check:
Start left at 0 and right at last index [OK]
- Setting right pointer to len(arr) causes index error
- Starting left pointer at 1 misses first element
- Using negative indices incorrectly
arr = [1, 3, 5, 7, 9]
left, right = 0, 4
result = []
while left < right:
result.append(arr[left] + arr[right])
left += 1
right -= 1
print(result)Solution
Step 1: Trace the loop iterations
Initial pointers: left=0, right=4 - Iteration 1: arr[0]+arr[4] = 1+9=10, result=[10] - left=1, right=3 - Iteration 2: arr[1]+arr[3] = 3+7=10, result=[10,10] - left=2, right=2 (loop ends because left is not less than right)Step 2: Check loop condition and final result
Loop stops when left == right (2), so only two sums added: [10, 10]Final Answer:
[10, 10] -> Option DQuick Check:
Sum pairs from ends until pointers meet [OK]
- Including middle element sum when pointers meet
- Not updating pointers correctly
- Confusing indices causing wrong sums
def is_palindrome(arr):
left, right = 0, len(arr)
while left < right:
if arr[left] != arr[right]:
return False
left += 1
right -= 1
return True
print(is_palindrome([1, 2, 3, 2, 1]))Solution
Step 1: Check pointer initialization
In Python, last index is len(arr) - 1, but code sets right = len(arr), which is out of range.Step 2: Correct pointer initialization
Change right to len(arr) - 1 to avoid index error and correctly compare elements.Final Answer:
right should be initialized as len(arr) - 1 -> Option BQuick Check:
Last index = length - 1 [OK]
- Setting right pointer to length causes index error
- Changing loop condition incorrectly
- Returning True too early inside loop
arr and a target sum target, how can you use the two pointer technique to find if there exists two numbers that add up to target? Choose the correct approach.Solution
Step 1: Set pointers at array ends
Start left pointer at 0 (start) and right pointer at last index (len(arr)-1).Step 2: Move pointers based on sum
Calculate sum of arr[left] + arr[right]. If sum equals target, return True. If sum is less, move left pointer right to increase sum. If sum is more, move right pointer left to decrease sum.Final Answer:
Initialize left at 0 and right at len(arr)-1; move pointers inward based on sum comparison -> Option AQuick Check:
Two pointers from ends adjust to find target sum [OK]
- Moving only one pointer without condition
- Using nested loops instead of two pointers
- Not starting pointers at array ends
Ready to prove it?
Pass the test and this pattern moves unknown
