Bird
Raised Fist0
DSA C++programming

Two Pointer Technique on Arrays in DSA C++

Choose your learning style10 modes available
Mental Model
Use two markers moving through the array to find pairs or conditions efficiently without checking all pairs.
Analogy: Imagine two friends starting at opposite ends of a hallway, walking towards each other to find a matching pair of shoes quickly.
Array: [1] -> [3] -> [5] -> [7] -> [9]
Pointers:  ↑                 ↑
           left              right
Dry Run Walkthrough
Input: array: [1, 3, 5, 7, 9], find if any two numbers sum to 12
Goal: Find two numbers in the array that add up to 12 using two pointers
Step 1: Initialize left pointer at index 0 and right pointer at index 4
1 [left] -> 3 -> 5 -> 7 -> 9 [right]
Why: Start checking pairs from both ends to cover all possibilities efficiently
Step 2: Calculate sum: 1 + 9 = 10, which is less than 12, move left pointer right
1 -> 3 [left] -> 5 -> 7 -> 9 [right]
Why: Sum too small, need a bigger number, so move left pointer forward
Step 3: Calculate sum: 3 + 9 = 12, found the target sum
1 -> 3 [left] -> 5 -> 7 -> 9 [right]
Why: Sum matches target, so we found the pair
Result:
1 -> 3 [left] -> 5 -> 7 -> 9 [right]
Pair found: 3 + 9 = 12
Annotated Code
DSA C++
#include <iostream>
#include <vector>
using namespace std;

bool twoPointerSum(const vector<int>& arr, int target) {
    int left = 0;
    int right = arr.size() - 1;
    while (left < right) {
        int sum = arr[left] + arr[right];
        if (sum == target) {
            cout << "Pair found: " << arr[left] << " + " << arr[right] << " = " << target << "\n";
            return true;
        } else if (sum < target) {
            left++; // increase sum by moving left pointer right
        } else {
            right--; // decrease sum by moving right pointer left
        }
    }
    cout << "No pair found that sums to " << target << "\n";
    return false;
}

int main() {
    vector<int> arr = {1, 3, 5, 7, 9};
    int target = 12;
    twoPointerSum(arr, target);
    return 0;
}
int left = 0; int right = arr.size() - 1;
Initialize two pointers at the start and end of the array
while (left < right) {
Loop until pointers cross, checking pairs
int sum = arr[left] + arr[right];
Calculate sum of elements at pointers
if (sum == target) {
Check if sum matches target
left++;
Increase left pointer to get a larger sum when current sum is too small
right--;
Decrease right pointer to get a smaller sum when current sum is too large
OutputSuccess
Pair found: 3 + 9 = 12
Complexity Analysis
Time: O(n) because each pointer moves at most n steps through the array once
Space: O(1) because only two pointers and a few variables are used regardless of input size
vs Alternative: Compared to checking all pairs with nested loops (O(n^2)), two pointers reduce time to linear by smartly moving pointers based on sum
Edge Cases
empty array
No pairs found, function returns false immediately
DSA C++
int right = arr.size() - 1;
array with one element
No pairs possible, function returns false
DSA C++
while (left < right) {
no pair sums to target
Function completes loop and prints no pair found message
DSA C++
cout << "No pair found that sums to " << target << "\n";
When to Use This Pattern
When you need to find pairs or conditions involving two elements in a sorted array, use two pointers moving inward to reduce time from quadratic to linear.
Common Mistakes
Mistake: Not moving pointers correctly based on sum comparison
Fix: Move left pointer right when sum is less than target, move right pointer left when sum is greater
Mistake: Using two pointers on unsorted array without sorting
Fix: Ensure array is sorted before applying two pointer technique
Summary
Find pairs in a sorted array efficiently using two pointers moving from both ends.
Use when searching for pairs or conditions involving two elements in sorted arrays.
The key is moving pointers inward based on comparison to target to avoid checking all pairs.

Practice

(1/5)
1. What is the main idea behind the Two Pointer Technique when used on arrays?
easy
A. Use two indices to scan the array from different ends or positions simultaneously
B. Use two nested loops to compare every pair of elements
C. Sort the array first and then use binary search
D. Use a single pointer to iterate through the array

Solution

  1. Step 1: Understand the technique

    The Two Pointer Technique uses two indices to traverse the array, often from opposite ends or different positions, to solve problems efficiently.
  2. Step 2: Compare with other options

    Options B and C describe different methods, and D uses only one pointer, so they do not match the Two Pointer Technique.
  3. Final Answer:

    Use two indices to scan the array from different ends or positions simultaneously -> Option A
  4. Quick Check:

    Two pointers = two indices scanning array [OK]
Hint: Two pointers move independently to cover array efficiently [OK]
Common Mistakes:
  • Thinking it always requires sorting first
  • Confusing with nested loops approach
  • Using only one pointer instead of two
2. Which of the following is the correct syntax to initialize two pointers left and right for an array arr of size n in C++?
easy
A. int left = n - 1, right = 0;
B. int left = 1, right = n;
C. int left = n, right = 0;
D. int left = 0, right = n - 1;

Solution

  1. Step 1: Understand pointer initialization

    For two pointers scanning from start and end, left starts at 0 and right at n-1 (last index).
  2. Step 2: Check each option

    int left = 0, right = n - 1; correctly sets left=0 and right=n-1. Options A, B, and C have incorrect indices that may cause out-of-bound errors.
  3. Final Answer:

    int left = 0, right = n - 1; -> Option D
  4. Quick Check:

    Start = 0, End = n-1 [OK]
Hint: Start left at 0 and right at n-1 for full array scan [OK]
Common Mistakes:
  • Setting right pointer to n (out of bounds)
  • Swapping left and right initial values
  • Starting left pointer at 1 instead of 0
3. What will be the output of the following C++ code snippet?
int arr[] = {1, 2, 3, 4, 5, 6};
int left = 0, right = 5;
int sum = 0;
while (left < right) {
    sum += arr[left] + arr[right];
    left++;
    right--;
}
std::cout << sum << std::endl;
medium
A. 27
B. 18
C. 21
D. 15

Solution

  1. Step 1: Trace the loop iterations

    Initial pointers: left=0, right=5
    Iteration 1: sum=0+arr[0]+arr[5]=0+1+6=7, left=1, right=4
    Iteration 2: sum=7+arr[1]+arr[4]=7+2+5=14, left=2, right=3
    Iteration 3: sum=14+arr[2]+arr[3]=14+3+4=21, left=3, right=2 (loop ends)
  2. Step 2: Final sum value

    Sum after loop is 21.
  3. Final Answer:

    21 -> Option C
  4. Quick Check:

    Sum pairs (1+6)+(2+5)+(3+4) = 21 [OK]
Hint: Add pairs from ends moving inward until pointers cross [OK]
Common Mistakes:
  • Including middle element when pointers cross
  • Adding elements twice
  • Incorrect loop condition (<= instead of <)
4. Identify the error in the following code that uses the two pointer technique to find if a sorted array contains two numbers that sum to a target value.
bool hasPairSum(int arr[], int n, int target) {
    int left = 0, right = n - 1;
    while (left <= right) {
        int sum = arr[left] + arr[right];
        if (sum == target) return true;
        else if (sum < target) left++;
        else right--;
    }
    return false;
}
medium
A. The loop condition should be left < right instead of left <= right
B. The pointers should be initialized as left = 1 and right = n
C. The sum calculation should be arr[left] - arr[right]
D. The function should return false inside the loop

Solution

  1. Step 1: Analyze loop condition

    The loop runs while left <= right, which allows pointers to be equal, causing sum of same element twice.
  2. Step 2: Correct loop condition

    Changing condition to left < right ensures pointers do not overlap, avoiding incorrect sum calculation.
  3. Final Answer:

    The loop condition should be left < right instead of left <= right -> Option A
  4. Quick Check:

    Pointers must not cross or overlap [OK]
Hint: Use left < right to avoid using same element twice [OK]
Common Mistakes:
  • Allowing pointers to be equal causing wrong sums
  • Incorrect pointer initialization
  • Returning false too early inside loop
5. Given a sorted array arr of size n, how can you use the two pointer technique to find all unique pairs that sum up to a target value t? Which approach is correct?
hard
A. Use nested loops to check every pair and store unique pairs in a set
B. Initialize left = 0 and right = n - 1, move pointers inward, skip duplicates after finding a pair
C. Sort the array, then use binary search for each element to find complement
D. Initialize left = 1 and right = n, move pointers outward

Solution

  1. Step 1: Set pointers and move inward

    Start with left at 0 and right at n-1. Move pointers inward based on sum compared to target.
  2. Step 2: Skip duplicates to find unique pairs

    After finding a pair, increment left and decrement right while skipping duplicate values to avoid repeated pairs.
  3. Final Answer:

    Initialize left = 0 and right = n - 1, move pointers inward, skip duplicates after finding a pair -> Option B
  4. Quick Check:

    Two pointers inward + skip duplicates = unique pairs [OK]
Hint: Skip duplicates after finding pairs to avoid repeats [OK]
Common Mistakes:
  • Not skipping duplicates causing repeated pairs
  • Using nested loops causing higher time complexity
  • Incorrect pointer initialization or movement
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard