Bird
Raised Fist0
DSA Pythonprogramming~20 mins

Two Pointer Technique on Arrays in DSA Python - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Two Pointer Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Two Pointer Sum Check
What is the output of this code that checks if any two numbers in the sorted array sum to 10?
DSA Python
def two_sum(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

print(two_sum([1, 2, 4, 5, 6, 8], 10))
AError
BFalse
CNone
DTrue
Attempts:
2 left
💡 Hint
Think about pairs that add up to 10 in the array.
❓ Predict Output
intermediate
2:00remaining
Result of Merging Two Sorted Arrays
What is the printed output after merging two sorted arrays using two pointers?
DSA Python
def merge_sorted(arr1, arr2):
    i, j = 0, 0
    merged = []
    while i < len(arr1) and j < len(arr2):
        if arr1[i] < arr2[j]:
            merged.append(arr1[i])
            i += 1
        else:
            merged.append(arr2[j])
            j += 1
    merged.extend(arr1[i:])
    merged.extend(arr2[j:])
    return merged

print(merge_sorted([1, 3, 5], [2, 4, 6]))
A[1, 2, 3, 4, 5, 6]
B[2, 4, 6, 1, 3, 5]
C[1, 3, 5, 2, 4, 6]
D[1, 2, 4, 3, 5, 6]
Attempts:
2 left
💡 Hint
Two pointers pick the smaller element from each array step by step.
❓ Predict Output
advanced
2:00remaining
Output of Removing Duplicates from Sorted Array
What is the output list after removing duplicates from a sorted array using two pointers?
DSA Python
def remove_duplicates(nums):
    if not nums:
        return []
    write = 1
    for read in range(1, len(nums)):
        if nums[read] != nums[read - 1]:
            nums[write] = nums[read]
            write += 1
    return nums[:write]

print(remove_duplicates([1, 1, 2, 3, 3, 4, 5, 5]))
A[1, 2, 3, 3, 4, 5]
B[1, 1, 2, 3, 4, 5]
C[1, 2, 3, 4, 5]
D[1, 2, 3, 4, 5, 5]
Attempts:
2 left
💡 Hint
Two pointers track unique elements and overwrite duplicates.
❓ Predict Output
advanced
2:00remaining
Output of Partitioning Array by Pivot
What is the output array after partitioning around pivot 5 using two pointers?
DSA Python
def partition(arr, pivot):
    left, right = 0, len(arr) - 1
    while left <= right:
        while left <= right and arr[left] < pivot:
            left += 1
        while left <= right and arr[right] >= pivot:
            right -= 1
        if left < right:
            arr[left], arr[right] = arr[right], arr[left]
            left += 1
            right -= 1
    return arr

print(partition([7, 2, 5, 3, 8, 1, 6], 5))
A[2, 3, 1, 5, 8, 7, 6]
B[7, 6, 8, 5, 3, 2, 1]
C[1, 2, 3, 5, 6, 7, 8]
D[7, 2, 3, 1, 5, 8, 6]
Attempts:
2 left
💡 Hint
Elements less than pivot move left, others right.
🧠 Conceptual
expert
2:00remaining
Number of Unique Pairs with Given Sum
Given a sorted array, how many unique pairs of numbers sum to 7 using the two pointer technique?
DSA Python
def count_pairs(arr, target):
    left, right = 0, len(arr) - 1
    count = 0
    while left < right:
        current_sum = arr[left] + arr[right]
        if current_sum == target:
            count += 1
            left += 1
            right -= 1
            while left < right and arr[left] == arr[left - 1]:
                left += 1
            while left < right and arr[right] == arr[right + 1]:
                right -= 1
        elif current_sum < target:
            left += 1
        else:
            right -= 1
    return count

print(count_pairs([1, 2, 2, 3, 4, 4, 5], 7))
A4
B2
C1
D3
Attempts:
2 left
💡 Hint
Count pairs without counting duplicates multiple times.

Practice

(1/5)
1. What is the main idea behind the Two Pointer Technique when used on arrays?
easy
A. Use two arrays to store temporary results
B. Sort the array twice before processing
C. Use two indices to scan the array from different ends or positions simultaneously
D. Use recursion to divide the array into two parts

Solution

  1. 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.
  2. Step 2: Recognize the purpose

    This helps solve problems efficiently by reducing the number of iterations compared to nested loops.
  3. Final Answer:

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

    Two pointers scan array ends or positions [OK]
Hint: Think of two fingers moving inward or outward on the array [OK]
Common Mistakes:
  • Confusing two pointers with using two separate arrays
  • Assuming sorting is always required
  • Thinking recursion is part of two pointer technique
2. Which of the following is the correct syntax to initialize two pointers left and right for an array arr in Python?
easy
A. left = 0; right = len(arr) - 1
B. left = 1; right = len(arr)
C. left = -1; right = len(arr)
D. left = 0; right = len(arr)

Solution

  1. Step 1: Identify valid pointer positions

    In Python, array indices start at 0, so the left pointer should start at 0.
  2. Step 2: Set right pointer correctly

    The right pointer should be at the last valid index, which is length of array minus 1.
  3. Final Answer:

    left = 0; right = len(arr) - 1 -> Option A
  4. Quick Check:

    Start left at 0 and right at last index [OK]
Hint: Remember Python arrays start at 0, last index is length-1 [OK]
Common Mistakes:
  • Setting right pointer to len(arr) causes index error
  • Starting left pointer at 1 misses first element
  • Using negative indices incorrectly
3. What will be the output of the following Python code?
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)
medium
A. [10, 14]
B. [10, 12]
C. [10, 12, 14]
D. [10, 10]

Solution

  1. 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)
  2. Step 2: Check loop condition and final result

    Loop stops when left == right (2), so only two sums added: [10, 10]
  3. Final Answer:

    [10, 10] -> Option D
  4. Quick Check:

    Sum pairs from ends until pointers meet [OK]
Hint: Add pairs from ends until pointers cross [OK]
Common Mistakes:
  • Including middle element sum when pointers meet
  • Not updating pointers correctly
  • Confusing indices causing wrong sums
4. Find the error in the following code that uses two pointers to check if an array is a palindrome:
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]))
medium
A. left should start at 1
B. right should be initialized as len(arr) - 1
C. Use 'while left <= right' instead of 'while left < right'
D. Return True should be inside the loop

Solution

  1. Step 1: Check pointer initialization

    In Python, last index is len(arr) - 1, but code sets right = len(arr), which is out of range.
  2. Step 2: Correct pointer initialization

    Change right to len(arr) - 1 to avoid index error and correctly compare elements.
  3. Final Answer:

    right should be initialized as len(arr) - 1 -> Option B
  4. Quick Check:

    Last index = length - 1 [OK]
Hint: Last index is length minus one, not length [OK]
Common Mistakes:
  • Setting right pointer to length causes index error
  • Changing loop condition incorrectly
  • Returning True too early inside loop
5. Given a sorted array 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.
hard
A. Initialize left at 0 and right at len(arr)-1; move pointers inward based on sum comparison
B. Initialize both pointers at 0 and move right pointer only
C. Sort the array again and use binary search for each element
D. Use two nested loops to check all pairs

Solution

  1. Step 1: Set pointers at array ends

    Start left pointer at 0 (start) and right pointer at last index (len(arr)-1).
  2. 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.
  3. Final Answer:

    Initialize left at 0 and right at len(arr)-1; move pointers inward based on sum comparison -> Option A
  4. Quick Check:

    Two pointers from ends adjust to find target sum [OK]
Hint: Move left/right pointers based on sum compared to target [OK]
Common Mistakes:
  • Moving only one pointer without condition
  • Using nested loops instead of two pointers
  • Not starting pointers at array ends
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