QA
Beginner LevelData Structures & Algorithms

What is the Two-Pointer Technique?

ā“ Interview Prompt: Explain the Two-Pointer pattern, when to apply it, and solve the classic Two-Sum II (sorted array) and Palindrome problems.

The Two-Pointer Technique uses two indices that typically start at opposite ends (or same end) of an array and converge, reducing nested loop $O(N^2)$ problems to $O(N)$.

When to Apply:

•
Array/string is sorted or the problem involves comparing elements from both ends.
•
Finding pairs that sum to a target.
•
Checking palindromes, removing duplicates in-place.
•
Sliding window variants (fast + slow pointers).

Code Implementation Example

typescript
// Two-Sum II — sorted array, O(N) time, O(1) space
function twoSumSorted(numbers: number[], target: number): [number, number] {
  let left = 0, right = numbers.length - 1;
  while (left < right) {
    const sum = numbers[left] + numbers[right];
    if (sum === target) return [left + 1, right + 1]; // 1-indexed
    if (sum < target) left++;
    else right--;
  }
  return [-1, -1];
}

// Palindrome check — O(N) time
function isPalindrome(s: string): boolean {
  let l = 0, r = s.length - 1;
  while (l < r) {
    if (s[l] !== s[r]) return false;
    l++; r--;
  }
  return true;
}
šŸ’”Two-pointer solving Two-Sum II and palindrome check in O(N).
šŸŽÆ Interview Key Takeaway

Two-pointers reduce O(N²) pair-search problems to O(N) by exploiting sorted order or symmetry. Master this before interviews.

#DSA#Two Pointers#Patterns#Arrays#Beginner
Back to all Data Structures & Algorithms Questions→

More Data Structures & Algorithms Interview Questions

Beginner LevelData Structures & Algorithms

What is the difference between an Array and a Linked List?

Beginner LevelData Structures & Algorithms

What is Big-O Notation and why is it important?

Beginner LevelData Structures & Algorithms

What are Stack and Queue data structures and where are they used?