Autocoder

Two pointers interview questions with worked solutions

Last updated 2026-11-19

The two pointers pattern uses two indexes that move through a sequence in a coordinated way, so a problem that looks like it needs all pairs is solved in a single pass. It comes in two shapes: pointers that start at both ends and move inwards, and pointers that both move forward at different speeds, one reading and one writing.

Reach for it when the input is sorted, when the question is about pairs, triplets or palindromes, or when you must compact or compare an array in place. The ten problems below move from a plain sorted-pair search to 4Sum. For forward-moving pointer pairs on linked lists, see fast and slow pointers questions.

Problems10, easy to hard
LanguagesPython and Java
ShapesEnds-inwards and same-direction pointers

Why moving a pointer is safe

In a sorted array with pointers at both ends, if the sum is too small, the left value paired with any smaller right value would be even smaller, so the left pointer can never be part of an answer with the current right end. That argument, "discarding this index loses nothing", is what you should state aloud.

When it does not apply

If the array is unsorted and you must return original indices, sorting loses them; use a hash map instead (see hashing questions). If the question is about contiguous subarrays with a window condition, sliding window is the sharper label.

Two pointers interview questions with worked solutions: questions with worked answers

  1. 1

    Two Sum II: find two numbers in a sorted array that add up to a target.

    easy

    Put pointers at both ends. If the sum is below the target, move the left pointer right; if above, move the right pointer left. Return the indices when the sum matches. Each step discards one index that cannot be part of the answer. Time O(n), space O(1).. Edge cases: no pair (return an empty result), negative values, two equal numbers.

    python
    def two_sum_sorted(a, target):
        l, r = 0, len(a) - 1
        while l < r:
            s = a[l] + a[r]
            if s == target:
                return [l, r]
            if s < target:
                l += 1
            else:
                r -= 1
        return []
    java
    import java.util.*;
    
    class Solution {
        static int[] twoSumSorted(int[] a, int target) {
            int l = 0, r = a.length - 1;
            while (l < r) {
                int s = a[l] + a[r];
                if (s == target) return new int[]{l, r};
                if (s < target) l++;
                else r--;
            }
            return new int[0];
        }
    }
  2. 2

    Intersection of two sorted arrays, without duplicates in the result.

    easy

    Advance the pointer at the smaller value. When the values are equal, add the value if it is not the same as the last one added, then advance both. No hash set is needed because both arrays are sorted. Time O(n + m), space O(1) beyond the output.. Edge cases: one array empty, no overlap, runs of equal values.

    python
    def intersect_sorted(a, b):
        i = j = 0
        out = []
        while i < len(a) and j < len(b):
            if a[i] < b[j]:
                i += 1
            elif a[i] > b[j]:
                j += 1
            else:
                if not out or out[-1] != a[i]:
                    out.append(a[i])
                i += 1
                j += 1
        return out
    java
    import java.util.*;
    
    class Solution {
        static List<Integer> intersectSorted(int[] a, int[] b) {
            int i = 0, j = 0;
            List<Integer> out = new ArrayList<>();
            while (i < a.length && j < b.length) {
                if (a[i] < b[j]) i++;
                else if (a[i] > b[j]) j++;
                else {
                    if (out.isEmpty() || out.get(out.size() - 1) != a[i]) out.add(a[i]);
                    i++;
                    j++;
                }
            }
            return out;
        }
    }
  3. 3

    Squares of a sorted array, returned in sorted order.

    easy

    The largest square is at one of the two ends, because negatives with large magnitude square to large values. Fill the result from the back: compare the absolute values at both pointers, place the larger square and move that pointer inwards. Time O(n), space O(n) for the output.. Edge cases: all negative, all non-negative, a single element.

    python
    def sorted_squares(a):
        n = len(a)
        res = [0] * n
        l, r = 0, n - 1
        for k in range(n - 1, -1, -1):
            if abs(a[l]) > abs(a[r]):
                res[k] = a[l] * a[l]
                l += 1
            else:
                res[k] = a[r] * a[r]
                r -= 1
        return res
    java
    import java.util.*;
    
    class Solution {
        static int[] sortedSquares(int[] a) {
            int n = a.length, l = 0, r = n - 1;
            int[] res = new int[n];
            for (int k = n - 1; k >= 0; k--) {
                if (Math.abs(a[l]) > Math.abs(a[r])) { res[k] = a[l] * a[l]; l++; }
                else { res[k] = a[r] * a[r]; r--; }
            }
            return res;
        }
    }
  4. 4

    Valid palindrome II: can a string become a palindrome by deleting at most one character?

    medium

    Run the usual inward scan. At the first mismatch, you have one deletion: try skipping the left character or the right one, and check whether the rest is a palindrome. If either works, the answer is true. You never need more than one such branch because only one deletion is allowed. Time O(n), space O(1).. Edge cases: already a palindrome, mismatch at the very ends, length 1 or 2.

    python
    def valid_palindrome2(s):
        def ok(l, r):
            while l < r:
                if s[l] != s[r]:
                    return False
                l += 1
                r -= 1
            return True
        l, r = 0, len(s) - 1
        while l < r:
            if s[l] != s[r]:
                return ok(l + 1, r) or ok(l, r - 1)
            l += 1
            r -= 1
        return True
    java
    import java.util.*;
    
    class Solution {
        static boolean validPalindrome2(String s) {
            int l = 0, r = s.length() - 1;
            while (l < r) {
                if (s.charAt(l) != s.charAt(r)) return isPal(s, l + 1, r) || isPal(s, l, r - 1);
                l++;
                r--;
            }
            return true;
        }
        static boolean isPal(String s, int l, int r) {
            while (l < r) if (s.charAt(l++) != s.charAt(r--)) return false;
            return true;
        }
    }
  5. 5

    Container with most water: choose two lines that hold the most water.

    medium

    Area is width times the shorter height. Start with the widest container and move the pointer at the shorter line inwards: keeping the shorter line cannot improve the area as the width only shrinks, whereas moving it might find a taller line. Time O(n), space O(1).. Edge cases: two lines only, heights containing zero, all equal heights.

    python
    def max_area(h):
        l, r, best = 0, len(h) - 1, 0
        while l < r:
            best = max(best, (r - l) * min(h[l], h[r]))
            if h[l] < h[r]:
                l += 1
            else:
                r -= 1
        return best
    java
    import java.util.*;
    
    class Solution {
        static int maxArea(int[] h) {
            int l = 0, r = h.length - 1, best = 0;
            while (l < r) {
                best = Math.max(best, (r - l) * Math.min(h[l], h[r]));
                if (h[l] < h[r]) l++;
                else r--;
            }
            return best;
        }
    }
  6. 6

    Boats to save people: each boat carries at most two people and a weight limit.

    medium

    Sort the weights. The heaviest person must take a boat; pair them with the lightest if the two fit under the limit, otherwise they go alone. So advance the light pointer only when the pair fits, and always retire the heavy pointer. Time O(n log n) for the sort, space O(1) beyond it.. Edge cases: everyone alone because each weight is near the limit, all light people, a single person.

    python
    def num_boats(people, limit):
        people.sort()
        i, j, boats = 0, len(people) - 1, 0
        while i <= j:
            if people[i] + people[j] <= limit:
                i += 1
            j -= 1
            boats += 1
        return boats
    java
    import java.util.*;
    
    class Solution {
        static int numBoats(int[] people, int limit) {
            Arrays.sort(people);
            int i = 0, j = people.length - 1, boats = 0;
            while (i <= j) {
                if (people[i] + people[j] <= limit) i++;
                j--;
                boats++;
            }
            return boats;
        }
    }
  7. 7

    3Sum: list all unique triplets that sum to zero.

    medium

    Sort the array. For each index i, run the two-pointer search for pairs summing to -a[i] on the part to its right. Skip repeated values for i, and after a hit skip repeated values on both pointers. Exit early when a[i] > 0 since sorted positives cannot sum to zero. Time O(n^2), space O(1) beyond the output and sort.. Edge cases: fewer than three numbers, all zeroes (one triplet), many duplicates.

    python
    def three_sum(a):
        a.sort()
        res = []
        for i in range(len(a) - 2):
            if a[i] > 0:
                break
            if i > 0 and a[i] == a[i - 1]:
                continue
            l, r = i + 1, len(a) - 1
            while l < r:
                s = a[i] + a[l] + a[r]
                if s < 0:
                    l += 1
                elif s > 0:
                    r -= 1
                else:
                    res.append([a[i], a[l], a[r]])
                    l += 1
                    r -= 1
                    while l < r and a[l] == a[l - 1]:
                        l += 1
        return res
    java
    import java.util.*;
    
    class Solution {
        static List<List<Integer>> threeSum(int[] a) {
            Arrays.sort(a);
            List<List<Integer>> res = new ArrayList<>();
            for (int i = 0; i < a.length - 2 && a[i] <= 0; i++) {
                if (i > 0 && a[i] == a[i - 1]) continue;
                int l = i + 1, r = a.length - 1;
                while (l < r) {
                    int s = a[i] + a[l] + a[r];
                    if (s < 0) l++;
                    else if (s > 0) r--;
                    else {
                        res.add(Arrays.asList(a[i], a[l], a[r]));
                        l++;
                        r--;
                        while (l < r && a[l] == a[l - 1]) l++;
                    }
                }
            }
            return res;
        }
    }
  8. 8

    3Sum closest: find the triplet sum nearest to a target.

    medium

    Sort, then for each i run two pointers. At each step compare the distance of the current sum to the best so far, and move the left pointer if the sum is below the target or the right pointer if above. An exact match ends the search. Time O(n^2), space O(1).. Edge cases: exactly three elements, an exact hit, negative numbers.

    python
    def three_sum_closest(a, target):
        a.sort()
        best = a[0] + a[1] + a[2]
        for i in range(len(a) - 2):
            l, r = i + 1, len(a) - 1
            while l < r:
                s = a[i] + a[l] + a[r]
                if abs(s - target) < abs(best - target):
                    best = s
                if s < target:
                    l += 1
                elif s > target:
                    r -= 1
                else:
                    return s
        return best
    java
    import java.util.*;
    
    class Solution {
        static int threeSumClosest(int[] a, int target) {
            Arrays.sort(a);
            int best = a[0] + a[1] + a[2];
            for (int i = 0; i < a.length - 2; i++) {
                int l = i + 1, r = a.length - 1;
                while (l < r) {
                    int s = a[i] + a[l] + a[r];
                    if (Math.abs(s - target) < Math.abs(best - target)) best = s;
                    if (s < target) l++;
                    else if (s > target) r--;
                    else return s;
                }
            }
            return best;
        }
    }
  9. 9

    Backspace string compare in O(1) space: are two typed strings equal once "#" deletes the previous character?

    hard

    Scan both strings from the right, since a backspace only affects characters to its left. A helper skips over characters that are deleted by counting pending backspaces, and returns the index of the next surviving character. Compare survivors pair by pair. Time O(n + m), space O(1).. Edge cases: more backspaces than characters, both strings reduce to empty (true), backspaces at the start.

    python
    def backspace_compare(s, t):
        def nxt(x, i):
            skip = 0
            while i >= 0:
                if x[i] == '#':
                    skip += 1
                elif skip > 0:
                    skip -= 1
                else:
                    break
                i -= 1
            return i
        i, j = len(s) - 1, len(t) - 1
        while True:
            i, j = nxt(s, i), nxt(t, j)
            if i < 0 and j < 0:
                return True
            if i < 0 or j < 0 or s[i] != t[j]:
                return False
            i -= 1
            j -= 1
    java
    import java.util.*;
    
    class Solution {
        static boolean backspaceCompare(String s, String t) {
            int i = s.length() - 1, j = t.length() - 1;
            while (true) {
                i = next(s, i);
                j = next(t, j);
                if (i < 0 && j < 0) return true;
                if (i < 0 || j < 0 || s.charAt(i) != t.charAt(j)) return false;
                i--;
                j--;
            }
        }
        static int next(String x, int i) {
            int skip = 0;
            while (i >= 0) {
                if (x.charAt(i) == '#') skip++;
                else if (skip > 0) skip--;
                else break;
                i--;
            }
            return i;
        }
    }
  10. 10

    4Sum: list unique quadruplets that sum to a target.

    hard

    Extend 3Sum by one more loop. Sort, fix i and j with duplicate skipping on both, then run two pointers on the remainder. Use long arithmetic in Java, since four int values can overflow. Time O(n^3), space O(1) beyond the output.. Edge cases: fewer than four numbers, large values that overflow int, many duplicates.

    python
    def four_sum(a, target):
        a.sort()
        n, res = len(a), []
        for i in range(n - 3):
            if i and a[i] == a[i - 1]:
                continue
            for j in range(i + 1, n - 2):
                if j > i + 1 and a[j] == a[j - 1]:
                    continue
                l, r = j + 1, n - 1
                while l < r:
                    s = a[i] + a[j] + a[l] + a[r]
                    if s < target:
                        l += 1
                    elif s > target:
                        r -= 1
                    else:
                        res.append([a[i], a[j], a[l], a[r]])
                        l += 1
                        r -= 1
                        while l < r and a[l] == a[l - 1]:
                            l += 1
        return res
    java
    import java.util.*;
    
    class Solution {
        static List<List<Integer>> fourSum(int[] a, int target) {
            Arrays.sort(a);
            int n = a.length;
            List<List<Integer>> res = new ArrayList<>();
            for (int i = 0; i < n - 3; i++) {
                if (i > 0 && a[i] == a[i - 1]) continue;
                for (int j = i + 1; j < n - 2; j++) {
                    if (j > i + 1 && a[j] == a[j - 1]) continue;
                    int l = j + 1, r = n - 1;
                    while (l < r) {
                        long s = (long) a[i] + a[j] + a[l] + a[r];
                        if (s < target) l++;
                        else if (s > target) r--;
                        else {
                            res.add(Arrays.asList(a[i], a[j], a[l], a[r]));
                            l++;
                            r--;
                            while (l < r && a[l] == a[l - 1]) l++;
                        }
                    }
                }
            }
            return res;
        }
    }

Frequently asked questions

How do I know when to use two pointers?

Sorted input, a pair or triplet condition, or an in-place rewrite are the three cues. If you find yourself writing two nested loops over the same array, ask whether one pointer can be discarded at each step.

Do I need to sort first?

Often yes, for pair-sum problems on unsorted data when original indices are not needed. Sorting costs O(n log n), which is usually dominated by nothing smaller, so state it.

What is the difference between two pointers and sliding window?

Sliding window keeps a contiguous range and moves both ends forward only. Two pointers is broader and includes ends-inwards scans. Windows are a special case. See sliding window questions.

How do I avoid duplicate triplets?

After sorting, skip a value if it equals the previous one at the same loop level, and after finding a match advance the pointers past repeated values.

Which problems should I do after these?

Try arrays questions for in-place work and greedy questions for boat-style pairing arguments.

Related guides

More in DSA Interview Questions

See all in this section