Bird
Raised Fist0
DSA Typescriptprogramming~15 mins

Two Pointer Technique on Arrays in DSA Typescript - Deep Dive

Choose your learning style10 modes available
Overview - Two Pointer Technique on Arrays
What is it?
The Two Pointer Technique on Arrays is a way to solve problems by using two markers that move through the array to find answers efficiently. Instead of checking every pair or element repeatedly, these two pointers help scan the array from different directions or speeds. This method is useful for tasks like finding pairs, reversing parts, or merging sorted arrays. It simplifies complex problems by breaking them down into smaller, manageable steps.
Why it matters
Without the Two Pointer Technique, many array problems would require checking all possible pairs or combinations, which can be very slow and inefficient. This technique speeds up the process, saving time and computing power, which is important in real-world applications like searching data, processing signals, or handling large datasets. It helps programmers write faster and cleaner code, making software more responsive and scalable.
Where it fits
Before learning this, you should understand basic arrays and simple loops. After mastering Two Pointer Technique, you can explore sliding window methods, binary search on arrays, and advanced sorting or searching algorithms. It is a foundational skill that connects basic array handling to more complex algorithmic strategies.
Mental Model
Core Idea
Use two markers moving through the array to efficiently find or compare elements without repeating work.
Think of it like...
Imagine two friends walking towards each other from opposite ends of a hallway, checking for something interesting as they go, instead of one friend walking back and forth repeatedly.
Array: [a0, a1, a2, ..., an-2, an-1]
Pointers:  ↑                             ↑
          left                         right

Process:
- Move left pointer forward to find needed elements
- Move right pointer backward to find needed elements
- Stop when pointers meet or cross
Build-Up - 7 Steps
1
FoundationUnderstanding Basic Array Pointers
šŸ¤”
Concept: Introduce the idea of using two separate positions (pointers) to track elements in an array.
An array is a list of items. Normally, we use one pointer (index) to go through it. Here, we use two pointers, each starting at different positions, usually at the start and end of the array. We can move these pointers independently to check or compare elements.
Result
You can track two elements at once without extra loops.
Understanding that two pointers can move independently allows you to scan arrays more flexibly than a single loop.
2
FoundationMoving Pointers Towards Each Other
šŸ¤”
Concept: Learn how to move two pointers from opposite ends towards the center to compare or find pairs.
Start with one pointer at the beginning (left) and one at the end (right). Compare the elements they point to. Depending on the problem, move one pointer inward (left moves right, right moves left) to find the desired condition. Repeat until pointers meet or cross.
Result
You can efficiently find pairs or conditions involving two elements without checking all pairs.
Knowing when and how to move each pointer reduces unnecessary checks and speeds up the solution.
3
IntermediateTwo Pointer for Sorted Arrays
šŸ¤”Before reading on: Do you think the two pointer technique works only on sorted arrays or also on unsorted arrays? Commit to your answer.
Concept: Using two pointers is especially powerful on sorted arrays because the order helps decide pointer movement.
In a sorted array, if the sum of elements at two pointers is too small, move the left pointer right to increase sum. If too large, move the right pointer left to decrease sum. This logic quickly finds pairs matching a target sum.
Result
You can find pairs with a specific sum in linear time instead of quadratic.
Understanding the sorted order lets you decide pointer moves logically, avoiding brute force checks.
4
IntermediateTwo Pointer for Partitioning Arrays
šŸ¤”Before reading on: Do you think two pointers can help rearrange arrays in place or only for searching? Commit to your answer.
Concept: Two pointers can rearrange arrays by swapping elements to group them based on a condition.
Use one pointer from the start and one from the end. Move the left pointer forward until it finds an element that should be on the other side. Move the right pointer backward until it finds an element that belongs to the left side. Swap these two elements. Repeat until pointers meet.
Result
The array is partitioned into two groups without extra space.
Knowing that two pointers can rearrange arrays in place helps solve problems like separating even and odd numbers efficiently.
5
IntermediateTwo Pointer for Merging Sorted Arrays
šŸ¤”
Concept: Two pointers can merge two sorted arrays by comparing elements and building a combined sorted array.
Have one pointer for each array starting at the beginning. Compare elements at both pointers. Append the smaller element to the result and move that pointer forward. Repeat until all elements are merged.
Result
You get a fully sorted merged array in linear time.
Using two pointers to merge leverages sorted order and avoids sorting the combined array from scratch.
6
AdvancedTwo Pointer with Variable Window Size
šŸ¤”Before reading on: Can two pointers be used to handle problems where the size of the segment changes dynamically? Commit to your answer.
Concept: Two pointers can define a window that grows or shrinks to solve problems like finding subarrays with certain properties.
Use one pointer as the start of the window and the other as the end. Move the end pointer to expand the window and include more elements. Move the start pointer to shrink the window when conditions are met or violated. This dynamic adjustment finds the desired subarray efficiently.
Result
You can find subarrays matching conditions in linear time.
Understanding that pointers can control a flexible window size unlocks solutions to many complex array problems.
7
ExpertOptimizing Two Pointer for Edge Cases
šŸ¤”Before reading on: Do you think two pointer solutions always run in linear time regardless of input? Commit to your answer.
Concept: Two pointer algorithms can be optimized to handle duplicates, empty arrays, or special conditions without extra overhead.
For example, when skipping duplicates in sorted arrays, move pointers past repeated elements to avoid redundant work. Handle empty or single-element arrays by adding checks before loops. Carefully design pointer movement to prevent infinite loops or missed cases.
Result
Robust two pointer solutions that handle all inputs efficiently.
Knowing how to handle edge cases prevents bugs and ensures your two pointer solutions work reliably in production.
Under the Hood
Two pointers are simply two indices that track positions in the array. The algorithm moves these indices based on comparisons or conditions, avoiding nested loops. This reduces time complexity from quadratic to linear in many cases. Internally, the array is accessed sequentially, and pointer updates are constant time operations. The technique leverages the array's order or problem constraints to decide pointer movement.
Why designed this way?
The two pointer technique was designed to optimize problems that involve pairs or segments in arrays. Before, brute force methods checked all pairs, which was slow. Using two pointers reduces repeated work by using problem structure, like sorted order, to guide pointer movement. This design balances simplicity and efficiency, making it widely applicable.
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│        Array Elements        │
│  a0  a1  a2  ...  an-2  an-1│
ā””ā”€ā”¬ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”˜
  │   │   │         │       │
  L   ->   ->         ←       R

Process:
- L and R start at ends
- Move L right or R left based on conditions
- Stop when L >= R
Myth Busters - 4 Common Misconceptions
Quick: Does the two pointer technique always require the array to be sorted? Commit to yes or no.
Common Belief:Two pointer technique only works on sorted arrays.
Tap to reveal reality
Reality:While it is most effective on sorted arrays, two pointers can be used on unsorted arrays for tasks like partitioning or reversing segments.
Why it matters:Believing it only works on sorted arrays limits your ability to use two pointers for many useful problems like rearranging or scanning arrays.
Quick: Do two pointers always move towards each other? Commit to yes or no.
Common Belief:Two pointers always start at opposite ends and move towards each other.
Tap to reveal reality
Reality:Two pointers can start anywhere and move in any direction, including both moving forward or one staying fixed while the other moves.
Why it matters:Misunderstanding pointer movement restricts problem-solving approaches and misses flexible uses like sliding windows.
Quick: Is the two pointer technique always faster than other methods? Commit to yes or no.
Common Belief:Two pointer technique always gives the fastest solution.
Tap to reveal reality
Reality:Two pointer is efficient for many problems but not always the fastest; some problems require other algorithms like hashing or binary search.
Why it matters:Overusing two pointers can lead to suboptimal solutions when better algorithms exist.
Quick: Can two pointers cause infinite loops if not handled carefully? Commit to yes or no.
Common Belief:Two pointer algorithms are always safe and cannot get stuck.
Tap to reveal reality
Reality:If pointer movement conditions are not carefully designed, pointers can get stuck or loop infinitely.
Why it matters:Ignoring pointer update logic can cause bugs and crashes in real applications.
Expert Zone
1
Two pointer technique can be combined with binary search to solve complex problems like finding pairs with constraints efficiently.
2
Handling duplicates by skipping repeated elements during pointer moves can drastically reduce runtime in sorted arrays.
3
In some problems, pointers can move non-linearly or jump multiple steps based on precomputed information, improving performance.
When NOT to use
Avoid two pointer technique when the problem requires random access or complex conditions that cannot be checked by simple pointer moves. Alternatives include hash maps for quick lookups, divide and conquer for recursive splitting, or dynamic programming for overlapping subproblems.
Production Patterns
Two pointer technique is widely used in production for tasks like merging sorted data streams, removing duplicates, partitioning data for parallel processing, and real-time sliding window analytics in streaming systems.
Connections
Sliding Window Technique
Builds on
Sliding window is a specialized form of two pointers where the pointers define a dynamic segment, helping solve subarray problems efficiently.
Merge Sort Algorithm
Shares pattern
Merge sort uses two pointers to merge sorted halves, showing how two pointer technique underpins classic sorting methods.
Human Visual Attention
Analogous process
Like two eyes focusing on different parts of a scene to gather information efficiently, two pointers scan arrays to gather data without redundant effort.
Common Pitfalls
#1Pointers not moving correctly causing infinite loops
Wrong approach:while (left < right) { if (arr[left] + arr[right] == target) { return [left, right]; } // Forgot to move pointers when sum != target }
Correct approach:while (left < right) { if (arr[left] + arr[right] == target) { return [left, right]; } else if (arr[left] + arr[right] < target) { left++; } else { right--; } }
Root cause:Not updating pointers in all cases causes the loop to never progress.
#2Using two pointers on unsorted array without sorting or proper logic
Wrong approach:let left = 0, right = arr.length - 1; while (left < right) { if (arr[left] + arr[right] == target) return [left, right]; else if (arr[left] + arr[right] < target) left++; else right--; }
Correct approach:arr.sort((a,b) => a - b); let left = 0, right = arr.length - 1; while (left < right) { if (arr[left] + arr[right] == target) return [left, right]; else if (arr[left] + arr[right] < target) left++; else right--; }
Root cause:Two pointer logic for sum depends on sorted array; skipping sorting breaks correctness.
#3Assuming two pointers must start at array ends
Wrong approach:let left = 0, right = arr.length - 1; // Trying to find subarray sum but only moving right pointer while (right < arr.length) { // logic right++; }
Correct approach:let start = 0, end = 0; while (end < arr.length) { // move end to expand window // move start to shrink window }
Root cause:Misunderstanding pointer roles limits flexibility and correctness.
Key Takeaways
Two pointer technique uses two indices moving through an array to solve problems efficiently without nested loops.
It works best on sorted arrays but can also rearrange or scan unsorted arrays with proper logic.
Pointer movement decisions based on problem conditions reduce unnecessary checks and speed up solutions.
Handling edge cases and pointer updates carefully prevents bugs like infinite loops.
Two pointer technique is foundational for many advanced algorithms like sliding windows and merging.

Practice

(1/5)
1. What is the main idea behind the Two Pointer Technique when used on arrays?
easy
A. Use a single pointer to iterate through the array once
B. Use two indices to scan the array from different ends or positions simultaneously
C. Sort the array before processing it with one pointer
D. Use recursion to divide the array into two parts

Solution

  1. Step 1: Understand the technique

    The Two Pointer Technique involves using two indices or pointers to traverse the array, often from opposite ends or different positions.
  2. Step 2: Compare with other options

    Options A, C, and D describe different methods like single pointer iteration, sorting, or recursion, which are not the core idea of two pointers.
  3. Final Answer:

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

    Two pointers = two indices scanning array [OK]
Hint: Two pointers move independently to cover array efficiently [OK]
Common Mistakes:
  • Thinking it uses only one pointer
  • Confusing with sorting or recursion
  • Assuming pointers move only forward
2. Which of the following is the correct TypeScript syntax to initialize two pointers at the start and end of an array named arr?
easy
A. let left = arr[0], right = arr[arr.length];
B. let left = 1, right = arr.length;
C. let left = 0, right = arr.length - 1;
D. let left = arr.length, right = 0;

Solution

  1. Step 1: Identify correct pointer initialization

    For two pointers at array ends, left starts at 0 (first index), right at arr.length - 1 (last index).
  2. Step 2: Check other options for errors

    let left = 1, right = arr.length; uses invalid indices (arr.length is out of bounds). let left = arr[0], right = arr[arr.length]; assigns values from array elements, not indices. let left = arr.length, right = 0; reverses pointers incorrectly.
  3. Final Answer:

    let left = 0, right = arr.length - 1; -> Option C
  4. Quick Check:

    Start = 0, End = length-1 [OK]
Hint: Array indices start at 0, last index is length minus one [OK]
Common Mistakes:
  • Using arr.length as an index (out of bounds)
  • Assigning pointer to array values instead of indices
  • Swapping left and right initialization
3. What will be the output of the following TypeScript code?
const arr = [1, 3, 5, 7, 9];
let left = 0;
let right = arr.length - 1;
let sumPairs = [];
while (left < right) {
  sumPairs.push(arr[left] + arr[right]);
  left++;
  right--;
}
console.log(sumPairs);
medium
A. [10, 16]
B. [10, 12]
C. [10, 8]
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, sumPairs=[10]
    left=1, right=3
    Iteration 2: arr[1]+arr[3] = 3+7=10, sumPairs=[10,10]
    left=2, right=2 (loop ends as left is not less than right)
  2. Step 2: Final output array

    The sumPairs array contains [10, 10] after the loop finishes.
  3. Final Answer:

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

    Pairs sums = [10, 10] [OK]
Hint: Add elements at left and right, move pointers inward [OK]
Common Mistakes:
  • Including middle element sum when left equals right
  • Incorrect pointer updates causing infinite loop
  • Wrong sum calculations or indices
4. Identify the bug in the following TypeScript code that uses two pointers to find if a sorted array contains two numbers summing to target.
function hasPairSum(arr: number[], target: number): boolean {
  let left = 0;
  let right = arr.length;
  while (left < right) {
    const sum = arr[left] + arr[right];
    if (sum === target) return true;
    else if (sum < target) left++;
    else right--;
  }
  return false;
}
medium
A. Right pointer initialized to arr.length instead of arr.length - 1
B. Left pointer should start at 1, not 0
C. The loop condition should be left <= right
D. The sum calculation should use arr[left] - arr[right]

Solution

  1. Step 1: Check pointer initialization

    The right pointer is set to arr.length, which is out of array bounds. It should be arr.length - 1 to point to the last element.
  2. Step 2: Validate other parts

    Left pointer at 0 is correct. Loop condition left < right is standard. Sum calculation uses addition correctly.
  3. Final Answer:

    Right pointer initialized to arr.length instead of arr.length - 1 -> Option A
  4. Quick Check:

    Right pointer must be last index (length-1) [OK]
Hint: Array last index is length minus one, not length [OK]
Common Mistakes:
  • Using arr.length as index causing runtime error
  • Changing loop condition incorrectly
  • Mistaking sum operation for subtraction
5. Given a sorted array arr of integers, how can you use the Two Pointer Technique to find all unique pairs that sum up to a target value target? Choose the best approach.
hard
A. Initialize two pointers at start and end; move inward adjusting pointers based on sum; skip duplicates to collect unique pairs
B. Use nested loops to check all pairs and add those matching target
C. Sort the array first, then use a hash map to find complements
D. Initialize pointers both at start and move forward checking sums

Solution

  1. Step 1: Use two pointers at array ends

    Start with left at 0 and right at arr.length - 1. Calculate sum of elements at these pointers.
  2. Step 2: Move pointers and skip duplicates

    If sum equals target, record pair and move both pointers skipping duplicates. If sum less than target, move left pointer right. If sum greater, move right pointer left.
  3. Step 3: Collect unique pairs efficiently

    This approach avoids nested loops and handles duplicates by skipping repeated values, ensuring unique pairs.
  4. Final Answer:

    Initialize two pointers at start and end; move inward adjusting pointers based on sum; skip duplicates to collect unique pairs -> Option A
  5. Quick Check:

    Two pointers + skip duplicates = unique pairs [OK]
Hint: Move pointers inward and skip duplicates for unique pairs [OK]
Common Mistakes:
  • Using nested loops causing higher time complexity
  • Not skipping duplicates leading to repeated pairs
  • Incorrect pointer movement causing missed pairs
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