Most array solutions are built from a few small, reusable pieces. You'll write them so often that they should become automatic — like knowing your times tables. Here are the ones that matter most.
One pass, one or two variables. The only subtle part is the starting value: start max at the first element (or at -Infinity), never at 0 — an array of negative numbers would otherwise report 0 as its maximum.
function stats(nums) { let sum = 0, min = nums[0], max = nums[0]; for (const x of nums) { sum += x; if (x < min) min = x; if (x > max) max = x; } return { sum, min, max };}In Java and C++ the sum is a long/long long: adding up many large ints can overflow 32 bits (about 2.1 billion) without any warning.
Step through a maximum search yourself — this is the simplest dry run in the course:
Change the input, press Run, then step through the code one move at a time.
"Where is target?" in an unsorted array: check every slot and stop at the first match. Return -1 to mean "not found" — a value that can never be a real index.
function indexOf(nums, target) { for (let i = 0; i < nums.length; i++) { if (nums[i] === target) return i; } return -1;}That's O(n). If the array is sorted, binary search does it in O(log n) — you'll use that idea in several problems later.
Swapping needs a temporary variable: if you write a = b first, the old value of a is gone before you can copy it.
[nums[i], nums[j]] = [nums[j], nums[i]]; // destructuring does it in one lineSwap the first and last elements, then the second and second-to-last, moving inward until the two indexes meet. About n / 2 swaps, no extra array.
function reverse(nums) { for (let l = 0, r = nums.length - 1; l < r; l++, r--) { [nums[l], nums[r]] = [nums[r], nums[l]]; }}When values fall in a small known range — say, marks from 0 to 100, or lowercase letters — an array can act as a counter: use the value as the index.
const counts = new Array(101).fill(0); // marks 0..100for (const mark of marks) counts[mark]++;// counts[90] is now how many students scored exactly 90That's the idea behind counting sort, and behind checking whether two words are anagrams in O(n). When the range of values is huge or unknown, a hash map plays the same role.
long) for sums in Java and C++.-1 (or null/None) for "not found".