issue 117apr 27mmxxvi
est. 2017
Sun, 27 Apr 2026
vol. IX · no. 117
PapersAdda
placement intelligence, since 2017
640+ briefs · 24 campuses · by reservation
verified offers · sourced from r/developersIndia
razorpay₹65.00 LPA· iit-d · sde-1google₹54.00 LPA· iiit-h · swe-imicrosoft₹49.50 LPA· iit-b · sdeatlassian₹38.00 LPA· nit-w · sde-1amazon₹44.20 LPA· bits-p · sde-1uber₹42.00 LPA· iit-kgp · sde-1razorpay₹65.00 LPA· iit-d · sde-1google₹54.00 LPA· iiit-h · swe-imicrosoft₹49.50 LPA· iit-b · sdeatlassian₹38.00 LPA· nit-w · sde-1amazon₹44.20 LPA· bits-p · sde-1uber₹42.00 LPA· iit-kgp · sde-1

Two Pointers Pattern Questions 2026: 18+ Problems [Solved]

11 min read
Uncategorized
Updated: 8 Jun 2026
Aditya Sharma
Aditya's Edit

PapersAdda 2026 Placement Cycle

By Aditya Sharma·Founder & Editor, PapersAdda

What changed in 2026 drives

Mass-recruiter offer letters are flatter for 2026 batch - the 4-5 LPA ASE band has barely budged in three years while inflation eats real wages. Premium tracks (Digital, Pro, Elite, Specialist) are still where the differential lives, and they are entirely test-driven. If you are aiming higher than the default offer, the coding round is not optional pageantry - it is the entire interview.

What I'd actually study for this

  • 01Two solid coding-round answers (1 medium-hard DSA each, with edge-case discussion) > five half-baked ones
  • 02One real project you can defend end-to-end - file paths, design decisions, and what you would change
  • 03One DBMS schema you actually built (not a textbook ER diagram), with at least 3 join-heavy queries written from memory
  • 04Three behavioural STAR stories: failure recovered, conflict handled, ownership taken

Where most candidates trip up

The single biggest mistake is treating company-specific guides as primary prep and DSA as secondary. It is the opposite. Mass recruiters use the test as a filter, but premium tracks at every IT services company use coding to allocate offer band. Spend 70% of prep time on DSA + system fundamentals, 20% on company-specific patterns, 10% on HR rehearsal. Reverse that ratio and you collect the default offer.

Editorial commentary by Aditya Sharma · written for PapersAdda · not generated, not aggregated.

Last Updated: June 2026


Why Two Pointers Matters

Candidates report two pointers as one of the most consistently asked array patterns across FAANG and service company rounds. Based on public preparation resources and candidate-reported interview discussions, this technique eliminates nested loops on sorted arrays and palindrome-style problems. It is the foundation technique behind sliding window, fast-slow pointers, and Dutch national flag. Companies use it to test whether candidates think O(n) before writing O(n^2).

This guide covers the three main variants: opposite-direction, same-direction, and fast-slow (cycle detection).


Three Variants at a Glance

1. OPPOSITE DIRECTION (converging)
   left=0, right=n-1, move toward center
   Use for: pair sum, container water, palindrome check, 3Sum

2. SAME DIRECTION (sliding window base)
   left=0, right=0, both move right
   Use for: remove duplicates, move zeros, partition

3. FAST-SLOW (Floyd's cycle)
   slow = head, fast = head.next
   Use for: cycle detection, middle of list, intersection

Opposite-Direction Template

def two_pointer_opposite(arr, target):
    left, right = 0, len(arr) - 1

    while left < right:
        current = arr[left] + arr[right]

        if current == target:
            return [left, right]
        elif current < target:
            left += 1
        else:
            right -= 1

    return []
# Requires sorted array. Time: O(n) after sort  Space: O(1)

Same-Direction Template

def two_pointer_same(arr):
    slow = 0  # write pointer

    for fast in range(len(arr)):
        if condition(arr[fast]):
            arr[slow] = arr[fast]
            slow += 1

    return slow  # length of valid section
# Time: O(n)  Space: O(1) in-place

Practice Questions with Solutions

Problem 1: Two Sum II - Input Array is Sorted (EASY)

Asked at: Amazon, Google, Microsoft, TCS

Problem: Given a 1-indexed sorted array, find two numbers that add to target.

def two_sum_sorted(numbers, target):
    """
    Converging two pointers on sorted array.
    Time: O(n)  Space: O(1)
    """
    left, right = 0, len(numbers) - 1

    while left < right:
        s = numbers[left] + numbers[right]
        if s == target:
            return [left + 1, right + 1]  # 1-indexed
        elif s < target:
            left += 1
        else:
            right -= 1

    return []

# Example
print(two_sum_sorted([2, 7, 11, 15], 9))  # [1, 2]

Complexity: Time O(n), Space O(1)


Problem 2: 3Sum (MEDIUM)

Asked at: Google, Amazon, Facebook, Microsoft - very frequently asked

Problem: Find all unique triplets in the array that sum to zero.

def three_sum(nums):
    """
    Sort + fix one element + two pointers on the rest.
    Time: O(n^2)  Space: O(1) (excluding output)
    """
    nums.sort()
    result = []

    for i in range(len(nums) - 2):
        # Skip duplicates for first element
        if i > 0 and nums[i] == nums[i - 1]:
            continue

        left, right = i + 1, len(nums) - 1

        while left < right:
            s = nums[i] + nums[left] + nums[right]

            if s == 0:
                result.append([nums[i], nums[left], nums[right]])
                # Skip duplicates
                while left < right and nums[left] == nums[left + 1]:
                    left += 1
                while left < right and nums[right] == nums[right - 1]:
                    right -= 1
                left += 1
                right -= 1
            elif s < 0:
                left += 1
            else:
                right -= 1

    return result

# Example
print(three_sum([-1, 0, 1, 2, -1, -4]))  # [[-1,-1,2],[-1,0,1]]

Complexity: Time O(n^2), Space O(1)


Problem 3: Container With Most Water (MEDIUM)

Asked at: Google, Amazon, Adobe, Paytm

Problem: Given n heights, find two lines that together with x-axis form a container that holds the most water.

def max_area(height):
    """
    Greedy insight: always move the shorter line inward.
    Moving the taller line can only decrease width with no height gain.
    Time: O(n)  Space: O(1)
    """
    left, right = 0, len(height) - 1
    max_water = 0

    while left < right:
        width = right - left
        water = width * min(height[left], height[right])
        max_water = max(max_water, water)

        if height[left] < height[right]:
            left += 1
        else:
            right -= 1

    return max_water

# Example
print(max_area([1, 8, 6, 2, 5, 4, 8, 3, 7]))  # 49

Complexity: Time O(n), Space O(1)


Problem 4: Remove Duplicates from Sorted Array (EASY)

Asked at: TCS NQT, Infosys, Amazon

Problem: Remove duplicates in-place from sorted array. Return new length.

def remove_duplicates(nums):
    """
    Slow pointer marks write position.
    Time: O(n)  Space: O(1)
    """
    if not nums:
        return 0

    slow = 0

    for fast in range(1, len(nums)):
        if nums[fast] != nums[slow]:
            slow += 1
            nums[slow] = nums[fast]

    return slow + 1

# Example
nums = [1, 1, 2]
k = remove_duplicates(nums)
print(nums[:k])  # [1, 2]

Complexity: Time O(n), Space O(1)


Problem 5: Move Zeros (EASY)

Asked at: Facebook, Amazon, Microsoft

Problem: Move all zeros to end while maintaining relative order of non-zero elements. In-place.

def move_zeroes(nums):
    """
    Write non-zeros at slow pointer, then fill rest with zeros.
    Time: O(n)  Space: O(1)
    """
    slow = 0

    for fast in range(len(nums)):
        if nums[fast] != 0:
            nums[slow] = nums[fast]
            slow += 1

    while slow < len(nums):
        nums[slow] = 0
        slow += 1

# Example
nums = [0, 1, 0, 3, 12]
move_zeroes(nums)
print(nums)  # [1, 3, 12, 0, 0]

Complexity: Time O(n), Space O(1)


Problem 6: Valid Palindrome (EASY)

Asked at: Amazon, Microsoft, Apple, Facebook

Problem: Given string, determine if it is a palindrome (ignoring non-alphanumeric, case-insensitive).

def is_palindrome(s):
    """
    Converging pointers skip non-alphanumeric.
    Time: O(n)  Space: O(1)
    """
    left, right = 0, len(s) - 1

    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1

        if s[left].lower() != s[right].lower():
            return False

        left += 1
        right -= 1

    return True

# Example
print(is_palindrome("A man, a plan, a canal: Panama"))  # True
print(is_palindrome("race a car"))                       # False

Complexity: Time O(n), Space O(1)


Problem 7: Trapping Rain Water (HARD)

Asked at: Amazon, Google, Microsoft, Goldman Sachs - classic hard problem

Problem: Given n non-negative integers representing elevation map, compute total water trapped.

def trap(height):
    """
    Two-pointer approach: water at position i = min(max_left, max_right) - height[i]
    Track max from each side as we go.
    Time: O(n)  Space: O(1)
    """
    if not height:
        return 0

    left, right = 0, len(height) - 1
    left_max = right_max = 0
    water = 0

    while left < right:
        if height[left] < height[right]:
            if height[left] >= left_max:
                left_max = height[left]
            else:
                water += left_max - height[left]
            left += 1
        else:
            if height[right] >= right_max:
                right_max = height[right]
            else:
                water += right_max - height[right]
            right -= 1

    return water

# Example
print(trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]))  # 6
print(trap([4, 2, 0, 3, 2, 5]))                       # 9

Complexity: Time O(n), Space O(1)


Problem 8: Sort Colors (Dutch National Flag) (MEDIUM)

Asked at: Amazon, Microsoft, Flipkart

Problem: Sort array containing only 0, 1, 2 in-place. One pass.

def sort_colors(nums):
    """
    Three pointers: low, mid, high.
    [0..low-1] = 0s, [low..mid-1] = 1s, [high+1..n-1] = 2s
    Time: O(n)  Space: O(1)
    """
    low = mid = 0
    high = len(nums) - 1

    while mid <= high:
        if nums[mid] == 0:
            nums[low], nums[mid] = nums[mid], nums[low]
            low += 1
            mid += 1
        elif nums[mid] == 1:
            mid += 1
        else:  # nums[mid] == 2
            nums[mid], nums[high] = nums[high], nums[mid]
            high -= 1
            # Don't increment mid - newly swapped element unchecked

# Example
nums = [2, 0, 2, 1, 1, 0]
sort_colors(nums)
print(nums)  # [0, 0, 1, 1, 2, 2]

Complexity: Time O(n), Space O(1)


Problem 9: 4Sum (MEDIUM)

Asked at: Amazon, Microsoft

Problem: Find all unique quadruplets that sum to target.

def four_sum(nums, target):
    """
    Sort + two fixed pointers + two-pointer inner loop.
    Time: O(n^3)  Space: O(1)
    """
    nums.sort()
    result = []
    n = len(nums)

    for i in range(n - 3):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        for j in range(i + 1, n - 2):
            if j > i + 1 and nums[j] == nums[j - 1]:
                continue

            left, right = j + 1, n - 1

            while left < right:
                s = nums[i] + nums[j] + nums[left] + nums[right]
                if s == target:
                    result.append([nums[i], nums[j], nums[left], nums[right]])
                    while left < right and nums[left] == nums[left + 1]:
                        left += 1
                    while left < right and nums[right] == nums[right - 1]:
                        right -= 1
                    left += 1
                    right -= 1
                elif s < target:
                    left += 1
                else:
                    right -= 1

    return result

# Example
print(four_sum([1, 0, -1, 0, -2, 2], 0))  # [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

Complexity: Time O(n^3), Space O(1)


Problem 10: Squares of a Sorted Array (EASY)

Asked at: Amazon, Google, Bloomberg

Problem: Return array of squares of sorted input, in sorted order.

def sorted_squares(nums):
    """
    Converging pointers: compare abs values, fill result from right.
    Time: O(n)  Space: O(n)
    """
    n = len(nums)
    result = [0] * n
    left, right = 0, n - 1
    pos = n - 1

    while left <= right:
        if abs(nums[left]) > abs(nums[right]):
            result[pos] = nums[left] ** 2
            left += 1
        else:
            result[pos] = nums[right] ** 2
            right -= 1
        pos -= 1

    return result

# Example
print(sorted_squares([-4, -1, 0, 3, 10]))  # [0, 1, 9, 16, 100]

Complexity: Time O(n), Space O(n)


Problem 11: Middle of Linked List (Fast-Slow Variant, EASY)

Asked at: Amazon, Microsoft, Infosys

Problem: Find the middle node of a linked list. If even nodes, return the second middle.

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def middle_node(head):
    """
    Slow moves 1, fast moves 2. When fast reaches end, slow is at middle.
    Time: O(n)  Space: O(1)
    """
    slow = fast = head

    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next

    return slow

Complexity: Time O(n), Space O(1)


Problem 12: Linked List Cycle Detection (Fast-Slow Variant, EASY)

Asked at: Amazon, Google, Microsoft, TCS

Problem: Detect if a linked list has a cycle.

def has_cycle(head):
    """
    Floyd's cycle detection. If cycle exists, fast and slow will meet.
    Time: O(n)  Space: O(1)
    """
    slow = fast = head

    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow == fast:
            return True

    return False

Complexity: Time O(n), Space O(1)


Problem 13: Remove Nth Node From End of List (MEDIUM)

Asked at: Amazon, Microsoft, Facebook

Problem: Remove the nth node from the end of the list and return its head.

def remove_nth_from_end(head, n):
    """
    Two pointers: advance fast n steps, then move both until fast.next is None.
    Slow.next is the node to remove.
    Time: O(n)  Space: O(1)
    """
    dummy = ListNode(0)
    dummy.next = head
    fast = slow = dummy

    for _ in range(n + 1):
        fast = fast.next

    while fast:
        slow = slow.next
        fast = fast.next

    slow.next = slow.next.next
    return dummy.next

Complexity: Time O(n), Space O(1)


Problem 14: Palindrome Linked List (MEDIUM)

Asked at: Amazon, Facebook, Microsoft

Problem: Check if a linked list is a palindrome.

def is_palindrome_list(head):
    """
    1. Find middle with fast-slow.
    2. Reverse second half.
    3. Compare both halves.
    Time: O(n)  Space: O(1)
    """
    # Find middle
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next

    # Reverse second half
    prev = None
    curr = slow
    while curr:
        next_node = curr.next
        curr.next = prev
        prev = curr
        curr = next_node

    # Compare
    left, right = head, prev
    while right:
        if left.val != right.val:
            return False
        left = left.next
        right = right.next

    return True

Complexity: Time O(n), Space O(1)


When to Use Which Variant

SituationVariantDirection
Sorted array pair sumOppositeConverging
3Sum/4SumOpposite (after fix)Converging
Container waterOppositeConverging
Palindrome stringOppositeConverging
Remove duplicatesSameLeft=write, Right=read
Move zerosSameLeft=write, Right=read
Cycle in listFast-SlowFast = 2x slow
Middle of listFast-SlowFast = 2x slow
Trapping rain waterOppositeConverging

Complexity Summary

ProblemTimeSpace
Two Sum SortedO(n)O(1)
3SumO(n^2)O(1)
Container With Most WaterO(n)O(1)
Trapping Rain WaterO(n)O(1)
Sort ColorsO(n)O(1)
Remove DuplicatesO(n)O(1)
Palindrome CheckO(n)O(1)

Common Mistakes

  1. Not sorting before using opposite-direction: The converging pointer logic only works on sorted input for sum problems.
  2. Incrementing mid in Dutch flag when swapping with high: The swapped-in element from high is unchecked; do not advance mid.
  3. Off-by-one in fast-slow for even-length lists: Behavior depends on whether fast = head or fast = head.next at start.
  4. Missing duplicate skip in 3Sum: Always skip duplicate values for all three positions.

Methodology applied to this articlelast verified 8 Jun 2026
Sources used
Public exam-pattern documents, official recruiter pages, and verified candidate reports on r/developersIndia and LinkedIn.
Verification window
Page last edited 8 Jun 2026 by Aditya Sharma. Numbers and patterns sanity-checked against the most recent 2026 cycle drives we tracked.
What we did NOT do
  • No fabricated salary numbers or success rates. If we quote a range, it's sourced.
  • No noun-substituted templates. This article was not generated by swapping company names in a stock prompt.
  • No paid placements, sponsored coaching links, or affiliate-shilled course pushes.
Verification policy: /editorial-standards/. Found something incorrect? Submit a correction - we respond within 48 hours.

Explore this topic cluster

More resources in Uncategorized

Use the category hub to browse similar questions, exam patterns, salary guides, and preparation resources related to this topic.

Paid contributor programme

Sat this this year? Share your story, earn ₹500.

First-person experience reports help future candidates prep smarter. We pay verified contributors ₹500 via UPI per accepted story - with byline.

Submit your story →

Ready to practice?

Take a free timed mock test

Put what you learned into practice. Our mock tests match the 2026 pattern with timer, navigator, reveal, and score breakdown. No signup.

Start Free Mock Test →

Related Articles

More from PapersAdda

Share this guide: