What if you could find pairs in a list without checking every single combination?
Why Two Pointer Technique on Arrays in DSA Typescript?
Imagine you have a long list of numbers, and you want to find two numbers that add up to a specific target. Doing this by checking every possible pair one by one feels like searching for a needle in a haystack.
Checking every pair means a lot of repeated work and takes a long time, especially if the list is very long. It's easy to make mistakes or miss pairs because you have to remember which pairs you already checked.
The Two Pointer Technique uses two markers that move through the list from different ends. By moving these pointers smartly, you can find pairs or solve problems much faster without checking every pair.
for (let i = 0; i < arr.length; i++) { for (let j = i + 1; j < arr.length; j++) { if (arr[i] + arr[j] === target) { return [i, j]; } } }
let left = 0; let right = arr.length - 1; while (left < right) { const sum = arr[left] + arr[right]; if (sum === target) return [left, right]; else if (sum < target) left++; else right--; }
This technique lets you solve problems involving pairs or ranges in arrays quickly and efficiently, saving time and effort.
Think of two people starting at opposite ends of a line trying to find a pair of gifts that together cost exactly a certain amount. Instead of checking every pair, they move closer or farther based on the total cost, quickly finding the right pair.
Manual pair checking is slow and error-prone.
Two pointers move from both ends to find solutions faster.
Great for sorted arrays and problems involving pairs or sums.
Practice
Two Pointer Technique when used on arrays?Solution
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.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.Final Answer:
Use two indices to scan the array from different ends or positions simultaneously -> Option BQuick Check:
Two pointers = two indices scanning array [OK]
- Thinking it uses only one pointer
- Confusing with sorting or recursion
- Assuming pointers move only forward
arr?Solution
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).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.Final Answer:
let left = 0, right = arr.length - 1; -> Option CQuick Check:
Start = 0, End = length-1 [OK]
- Using arr.length as an index (out of bounds)
- Assigning pointer to array values instead of indices
- Swapping left and right initialization
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);Solution
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)Step 2: Final output array
The sumPairs array contains [10, 10] after the loop finishes.Final Answer:
[10, 10] -> Option DQuick Check:
Pairs sums = [10, 10] [OK]
- Including middle element sum when left equals right
- Incorrect pointer updates causing infinite loop
- Wrong sum calculations or indices
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;
}Solution
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.Step 2: Validate other parts
Left pointer at 0 is correct. Loop condition left < right is standard. Sum calculation uses addition correctly.Final Answer:
Right pointer initialized to arr.length instead of arr.length - 1 -> Option AQuick Check:
Right pointer must be last index (length-1) [OK]
- Using arr.length as index causing runtime error
- Changing loop condition incorrectly
- Mistaking sum operation for subtraction
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.Solution
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.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.Step 3: Collect unique pairs efficiently
This approach avoids nested loops and handles duplicates by skipping repeated values, ensuring unique pairs.Final Answer:
Initialize two pointers at start and end; move inward adjusting pointers based on sum; skip duplicates to collect unique pairs -> Option AQuick Check:
Two pointers + skip duplicates = unique pairs [OK]
- Using nested loops causing higher time complexity
- Not skipping duplicates leading to repeated pairs
- Incorrect pointer movement causing missed pairs
Ready to prove it?
Pass the test and this pattern moves unknown
