ποΈ Day 42 Bonus: Arrays β Advanced Operations and Two-Pointer Techniques
π§ Concept Deep Dive
Arrays are foundational in data structures. Today we explore more advanced techniques like slicing, splicing, searching, and especially the two-pointer pattern, which is often used in solving problems efficiently involving arrays.
π Core Concepts
Array Methods Refresher
const arr = [10, 20, 30, 40];
arr.push(50); // [10, 20, 30, 40, 50]
arr.pop(); // [10, 20, 30, 40]
arr.shift(); // [20, 30, 40]
arr.unshift(5); // [5, 20, 30, 40]
const sliced = arr.slice(1, 3); // [20, 30] (non-destructive)
arr.splice(2, 1); // removes 1 element at index 2Searching in Arrays
arr.includes(20); // true
arr.indexOf(30); // returns index or -1Two-Pointer Pattern
This is a common strategy used to reduce time complexity. Instead of nested loops, we move two pointers through the array.
When to use:
- Sorted arrays
- Searching pairs
- Partitioning
- Removing duplicates
Example 1: Find Pair with Sum
function hasPairWithSum(arr: number[], target: number): boolean {
let left = 0;
let right = arr.length - 1;
while (left < right) {
const sum = arr[left] + arr[right];
if (sum === target) return true;
if (sum < target) left++;
else right--;
}
return false;
}Input: [1, 2, 4, 4], target = 8 β Output: true
Example 2: Remove Duplicates from Sorted Array
function removeDuplicates(nums: number[]): number {
let i = 0;
for (let j = 1; j < nums.length; j++) {
if (nums[j] !== nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}Input: [1,1,2] β Output: 2 (array becomes [1,2,_])
π¨ ASCII Visualization
Two pointers:
arr = [1, 2, 3, 4, 5]
^ ^
left right
Loop continues:
If sum too small β left++
If sum too big β right--ποΈ Homework (LeetCode-style)
Problem 1: Move Zeroes
function moveZeroes(nums: number[]): void {
let insertPos = 0;
for (let num of nums) {
if (num !== 0) {
nums[insertPos++] = num;
}
}
while (insertPos < nums.length) {
nums[insertPos++] = 0;
}
}Input: [0,1,0,3,12] β Output: [1,3,12,0,0]
Problem 2: Two Sum II (Sorted Input)
function twoSum(numbers: number[], target: 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];
else if (sum < target) left++;
else right--;
}
return [];
}Input: [2,7,11,15], target = 9 β Output: [1,2]
Problem 3: Square of Sorted Array
function sortedSquares(nums: number[]): number[] {
let result = Array(nums.length);
let left = 0, right = nums.length - 1;
let pos = nums.length - 1;
while (left <= right) {
const leftSq = nums[left] * nums[left];
const rightSq = nums[right] * nums[right];
if (leftSq > rightSq) {
result[pos--] = leftSq;
left++;
} else {
result[pos--] = rightSq;
right--;
}
}
return result;
}Input: [-4,-1,0,3,10] β Output: [0,1,9,16,100]
π Summary
- Arrays offer many useful methods.
- Two-pointer technique simplifies many problems and improves performance.
- Know when to use
slice,splice, and pointer movement.