Arrays are the most fundamental data structure, providing contiguous memory storage for elements of the same type. This page covers common array patterns and problems.
Arrays provide O(1) random access but O(n) insertion and deletion for arbitrary positions. TypeScript’s built-in array type is used with various algorithms and patterns.
/** * Time complexity: O(n) * Space complexity: O(1) */function merge( nums1: number[], m: number, nums2: number[], n: number) { // Go backwards comparing the bigger numbers let back = n + m - 1; n--; m--; // Since nums1 should always be returned, only care while n >= 0 while (n >= 0) { // If m exists, check if nums1 is bigger than nums2 if (m >= 0 && nums1[m] > nums2[n]) { nums1[back] = nums1[m]; m--; } else { nums1[back] = nums2[n]; n--; } back--; } return nums1;}// Example: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3// Output: [1,2,2,3,5,6]
/** * Time complexity: O(n log n) - due to sorting * Space complexity: O(1) */function arrayPairSum(arr: number[]): number { // Sort first to maximize the min value arr.sort((a, b) => a - b); // Sum all min items at even indexes return arr.reduce((sum, num, i) => { if (i % 2 === 0) { sum += num; } return sum; }, 0);}// Example: [1,5,3,2] → sorted: [1,2,3,5]// Pairs: (1,2), (3,5) → mins: 1, 3 → sum: 4