Arrays
arrays
Data Structures
Arrays & Strings
Reading `arr[1000000]` takes the same amount of time as reading `arr[0]`, because an array's contiguous memory layout lets the runtime compute the address of any element with a single multiplication. That single property is what makes **Arrays & Strings** the workhorse data structure of nearly every program you will ever write. This lesson walks through array declaration and indexing in JavaScript and Python, the cost of inserts and deletes that force shifting, slicing and subarray patterns, and the basic string operations every interview problem assumes you know. You will also see why strings behave as immutable character arrays in both languages and what that means for performance when you build strings inside a loop. In **How to Read Code (JS & Python)**, you practiced tracing programs line by line; that habit is exactly how you will reason about loop indices and slice boundaries here. **Big-O Notation (Upper Bound)** gave you the language to express scaling behavior, and arrays are where you will first see `O(1)` access sit next to `O(n)` insertion in the same data structure. Once array fundamentals are second nature, **Matrix/Grid Fundamentals** extends the same indexing intuition into two dimensions, where row and column traversal patterns power BFS, DFS, and dynamic programming on grids.
Not Started
0%
Fenwick Tree (BIT)
A complete Fenwick Tree implementation fits in fifteen lines of code, half the memory of a segment tree, and a smaller constant factor on every operation. The price of admission is that you only get prefix-style aggregates, but for the enormous class of problems that need exactly that, a **Fenwick Tree** (also called a Binary Indexed Tree, or BIT) is the right answer. This lesson covers the dynamic prefix-sum problem (static prefix sums are `O(1)` query and `O(n)` update; you want both in `O(log n)`), the `i & -i` lowbit trick that isolates the lowest set bit and implicitly defines which range each index covers, point update and prefix query in `O(log n)`, and the `prefix(R) - prefix(L-1)` identity that turns those into general range queries. You will also meet the difference-array technique that swaps the roles, supporting `O(log n)` range updates with `O(log n)` point queries. In **Arrays & Strings**, you saw how a flat array can encode rich structure when the indexing scheme is clever; the Fenwick tree pushes that idea further by letting binary representation itself carry the partition information. **Segment Tree** solved a more general version of this problem with explicit nodes; the BIT trades flexibility for simplicity and memory and wins on both metrics whenever prefix queries suffice. Next, **Sparse Table** addresses a different point in the trade space: arbitrary range minimum (and similar idempotent) queries, with `O(1)` queries when no updates are involved.
Not Started
0%
Matrix/Grid Fundamentals
Picture an image as a grid of pixels, a chessboard as an 8 by 8 array of squares, or a maze as a rectangle of walls and corridors. Each of these is a **Matrix/Grid**: a two-dimensional array indexed by `(row, column)` where the right traversal order can turn a hard problem into a single nested loop. This lesson covers how to allocate and initialize 2D arrays in JavaScript and Python, how row-major storage maps a `[i][j]` access to a contiguous memory offset, and the standard traversal patterns: row by row, column by column, and along the two diagonals. You will also practice boundary checks, the most common source of off-by-one bugs in grid problems, and implement a transpose to see how index swaps reshape data in place. In **Arrays & Strings**, you saw that a one-dimensional array gives `O(1)` indexed access through a single offset calculation. A grid is just nested arrays sharing that same property along two axes, so every shifting and bounds idea you used there carries over directly. Once you can move confidently through a grid, **Linked Lists (Singly)** shifts the focus to a very different memory layout: pointer-based nodes with no contiguous block at all.
Not Started
0%
Sparse Table
Range minimum queries on a fixed array do not need updates, so the segment tree's `O(log n)` query is leaving performance on the table. A **Sparse Table** flattens the query down to genuine `O(1)`: precompute the minimum of every power-of-2 length window, and any range `[L, R]` can be answered by combining two such windows that together cover it, exploiting the fact that `min(min(A), min(B)) = min(A union B)` when the windows overlap. This lesson covers the `O(n log n)` preprocessing that fills a 2D table indexed by `(start, log2_length)`, the `O(1)` query trick for idempotent operations such as min, max, GCD, and bitwise OR, the `log2_floor` precomputation that makes every query branch-free, and the slower `O(log n)` query needed when the operation is not idempotent (like sum). You will see why this structure is the right tool for the Range Minimum Query (RMQ) problem and an essential building block in algorithms like Lowest Common Ancestor in `O(1)` per query. In **Arrays & Strings**, a flat array stored values; here the same shape stores precomputed answers indexed by a length exponent. **Logarithms & Exponentiation** is what makes the geometry work: power-of-two windows tile the index space the way binary representations tile integers, and the `O(1)` query depends on `floor(log2(length))`. With Sparse Tables in your toolkit, the curriculum next pivots to specialized structures for strings, immutability, and bounded integer universes.
Not Started
0%
Algorithms
Binary Search (Intro)
Searching a sorted array of one billion elements with linear search takes up to a billion comparisons. Binary search needs about thirty. The same input, the same hardware, two algorithms with completely different scaling behavior, separated only by the assumption that the array is sorted. **Binary Search (Intro)** explains how to get that speedup and how to write the algorithm without the off-by-one errors and infinite loops that trip up almost everyone the first time. You will implement the canonical two-pointer template with `left` and `right` indices, learn why `mid = left + (right - left) / 2` matters for avoiding integer overflow, and trace the algorithm step by step on small inputs to see the search space halve each iteration. The lesson also surveys built-in support across languages (`Array.indexOf` is _not_ a binary search; Python's `bisect` is) and the most common pitfalls. In **Arrays & Strings**, you saw why indexed access on an array is `O(1)`; binary search is the first algorithm that uses that property to skip past whole regions instead of walking through them. **Big-O Notation (Upper Bound)** gave you the language `O(log n)` and the reasoning that explains why halving leads to logarithmic growth. From here you will move into **Two Pointers (Intro)**, which generalizes the same coordinated-index idea beyond exact-match searching.
Not Started
0%
Iteration Patterns on Arrays/Strings
Look at almost any solved interview problem and you will see the same six or seven shapes of `for` loop reappearing: a single sweep that finds a max, a nested pair that compares every element to every other, a single sweep that fills a frequency table. Before you can recognize when two pointers or sliding window will help, you have to recognize these primitive shapes on sight. **Iteration Patterns on Arrays/Strings** catalogs those shapes. You will work through single-pass templates (running sum, find max/min, counting), nested-loop templates that consider all pairs in `O(n^2)` time, frequency counting with a hash map, early termination with `break`, sentinel values, and the choice between in-place modification and building a new array. Classic transformations like reverse, rotate, and partition appear as named patterns rather than puzzles solved from scratch each time. In **Arrays & Strings**, you saw that arrays give you constant-time indexed access and contiguous memory. This lesson turns that storage model into actual movement: how an index walks across an array, what it costs, and when one walk is enough. Next you will use these patterns directly in **Prefix Sum & Difference Array**, where a single preprocessing pass replaces many later range-sum loops.
Not Started
0%
Prefix Sum & Difference Array
Imagine an array of a million numbers and a thousand questions of the form "what is the sum of elements between index `l` and `r`?". The naive answer loops through each query, doing roughly a billion additions in total. Prefix sums turn the same workload into a million additions plus a thousand subtractions, with answers in constant time per query. **Prefix Sum & Difference Array** covers the technique in three layers. You will build 1D prefix sums where `prefix[i] = prefix[i-1] + arr[i]` and answer any range sum in `O(1)`. You will then learn the inverse, the difference array, which turns repeated `O(n)` range updates into `O(1)` updates that you reconstruct in a single final pass. The lesson finishes with 2D prefix sums and the inclusion-exclusion trick for answering submatrix sum queries, plus quick variants like prefix XOR and prefix product. In **Arrays & Strings**, you saw why arrays support `O(1)` random access; that property is exactly what makes prefix lookup possible. **Iteration Patterns on Arrays/Strings** trained you to think in terms of single passes, and the prefix sum is the first pattern where one preprocessing pass replaces an entire family of later loops. From here you will move into **Sorting (Elementary)**, where rearranging the array unlocks an entirely different class of techniques.
Not Started
0%
Searching (Basics)
If your phone's contact list is unsorted and you are looking for Sam, the only option is to read names top to bottom until you find a match or hit the end. That brute-force scan is linear search, and it is the right algorithm in a surprising number of situations: small arrays, unsorted data, linked lists, and any case where sorting first would cost more than the search itself. **Searching (Basics)** covers linear search and its small family of variations. You will implement the standard `O(n)` scan in JavaScript and Python, learn the sentinel trick that removes a per-iteration boundary check, and adapt the same template to find the first occurrence, the last occurrence, or the first element matching a condition. The lesson also walks through linear search on linked lists, where you cannot skip ahead by index. In **Arrays & Strings**, you saw why arrays support `O(1)` random access. Searching turns that primitive into a question: how many of those accesses do you need to find a value, and can you do better than reading every one? That question motivates **Binary Search (Intro)** next, which exploits sorted order to bring the cost down to `O(log n)`.
Not Started
0%
Sliding Window (Intro)
To find the longest substring of `s` with no repeated characters, the brute-force approach checks every substring in `O(n^3)` time. The sliding-window solution touches each character at most twice and runs in `O(n)`: extend a right pointer until a duplicate appears, then advance a left pointer until the duplicate is gone, repeating until the right pointer falls off the end. **Sliding Window (Intro)** turns that idea into two reusable templates. The fixed-size window slides a range of length `k` across the array and updates the running sum or count by adding the new right element and removing the old left element, never recomputing from scratch. The variable-size window expands the right edge while a condition holds and shrinks the left edge to restore that condition, tracking the window's contents with a hash map or counter. You will apply both to maximum-sum subarray of size `k`, longest substring without repeating characters, minimum window substring, and longest substring with at most `k` distinct characters. In **Two Pointers (Intro)**, you used coordinated indices to walk an array linearly. **Hash Map (Dictionary) Basics** gave you the `O(1)` lookup and update that lets a window track its own contents efficiently. Sliding window combines both: two indices and one hash map. From here you turn to **Recursion Fundamentals**, which trades sequential index movement for self-similar subproblems.
Not Started
0%
Two Pointers (Intro)
Given a sorted array and a target sum, the brute-force "check every pair" approach is `O(n^2)`. With two indices walking inward from opposite ends, the same problem drops to `O(n)`: if the current pair sums too low, move the left pointer right; if it sums too high, move the right pointer left. **Two Pointers (Intro)** turns that insight into a reusable pattern with two main shapes. The opposite-direction variant has pointers converge from both ends and powers problems like pair sum, palindrome check, reverse in place, and container with most water. The same-direction (fast and slow) variant has both pointers walk forward at different speeds and powers in-place filtering problems like remove duplicates from a sorted array, move zeros to the end, and the linked-list cycle detection you will revisit later. In **Arrays & Strings**, you learned how a single index walks across an array. This lesson coordinates two indices in a way that exploits sorted order or a structural invariant to skip work an inner loop would otherwise repeat. Next, **Sliding Window (Intro)** generalizes the same-direction pointer pair into an expanding and shrinking range that solves contiguous-subarray problems.
Not Started
0%
Practice Problems
Best Time to Buy and Sell Stock
Find the maximum profit from buying and selling a stock once, given daily prices.
Binary Search
Given a sorted array of integers and a target value, return the index of the target using binary search, or -1 if not found.
Contains Duplicate II
Check if an array contains two distinct indices with the same value whose absolute difference is at most k.
Contains Duplicate
Given an integer array, determine if any value appears at least twice in the array.
Isomorphic Strings
Determine if two strings are isomorphic, where each character in one string can be mapped to exactly one character in the other.
Length of Last Word
Given a string of words separated by spaces, return the length of the last word.
Longest Common Prefix
Find the longest common prefix string among an array of strings.
Majority Element
Given an array, find the element that appears more than half the time using Boyer-Moore Voting.
Maximum Average Subarray I
Find the contiguous subarray of a given length k that has the maximum average value.
Merge Sorted Array
Merge two sorted arrays into one sorted array in-place, using the extra space at the end of the first array.
Plus One
Given a large integer represented as an array of digits, increment it by one and return the resulting array of digits.
Ransom Note
Determine if a ransom note can be constructed from the characters available in a magazine string.
Remove Duplicates from Sorted Array
Remove duplicates from a sorted array in-place so each element appears only once, and return the new length.
Remove Element
Remove all occurrences of a given value from an array in-place and return the new length.
Search Insert Position
Given a sorted array and a target value, return the index where the target is found or where it would be inserted to keep the array sorted.
Single Number
Given a non-empty array of integers where every element appears twice except for one, find that single element using constant extra space.
Two Sum
Given an array of integers and a target, return the indices of the two numbers that add up to the target.
Valid Anagram
Given two strings, determine if one is an anagram of the other by comparing character frequencies.
Word Pattern
Check if a string of words follows the same pattern as a given pattern string, using a bijective character-to-word mapping.
Candy
Given an array of children's ratings, distribute the minimum number of candies such that each child gets at least one and children with higher ratings get more candies than their neighbors.
Maximum Profit in Job Scheduling
Given jobs with start times, end times, and profits, find the maximum profit you can earn by scheduling non-overlapping jobs.
Median of Two Sorted Arrays
Find the median of two sorted arrays in O(log(min(m, n))) time by binary searching for the correct partition.
N-Queens II
Given an integer n, return the number of distinct solutions to the n-queens puzzle, where n queens are placed on an n x n chessboard so that no two queens attack each other.
N-Queens
Place n queens on an n x n chessboard so that no two queens attack each other. Return all distinct board configurations as lists of strings, where 'Q' represents a queen and '.' represents an empty space.
Sliding Window Maximum
Find the maximum value in each sliding window of size k as it moves across the array.
Best Time to Buy and Sell Stock III
Find the maximum profit from at most two stock transactions, where you must sell before buying again.
Best Time to Buy and Sell Stock IV
Find the maximum profit from at most k stock transactions, generalizing the Stock III problem to arbitrary k.
Trapping Rain Water
Given an elevation map, compute how much water it can trap after raining.
Word Search II
Given a 2D board of characters and a list of words, find all words that can be formed by sequentially adjacent cells on the board, using each cell at most once per word.
Combination Sum II
Given a collection of candidate numbers (which may contain duplicates) and a target, find all unique combinations where the chosen numbers sum to the target. Each number may only be used once.
Combination Sum
Given an array of distinct integers and a target, return all unique combinations where the chosen numbers sum to the target. Each number may be used an unlimited number of times.
Combinations
Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. Return the answer in any order.
Container With Most Water
Find two lines that together with the x-axis form a container holding the most water.
Encode and Decode Strings
Design an algorithm to encode a list of strings into a single string and decode it back, handling any character content.
Find First and Last Position of Element in Sorted Array
Given a sorted array and a target, find the starting and ending position of the target value in O(log n) time.
Find Minimum in Rotated Sorted Array
Find the minimum element in a sorted array that has been rotated between 1 and n times, using O(log n) time.
Find Peak Element
Find a peak element in an array where the element is strictly greater than its neighbors. Return any peak's index in O(log n) time.
Game of Life
Implement Conway's Game of Life: compute the next state of a board in-place using state-encoding to avoid extra space.
Gas Station
Given arrays of gas available and cost to travel to the next station arranged in a circle, find the starting station index that lets you complete the circuit, or return -1 if impossible.
Group Anagrams
Group an array of strings so that anagrams appear together, using a hash map with sorted-character keys.
H-Index
Compute a researcher's h-index from their citation counts using sorting or counting sort for optimal performance.
Hand of Straights
Given an array of integers and a group size, determine if the array can be rearranged into groups where each group consists of consecutive integers of the given size.
House Robber II
Houses are arranged in a circle. Adjacent houses cannot be robbed on the same night, and the first and last houses are also adjacent. Determine the maximum amount of money you can rob.
Insert Delete GetRandom O(1)
Design a data structure that supports insert, remove, and getRandom in average O(1) time using a hash map paired with a dynamic array.
Jump Game II
Given an integer array where each element represents the maximum jump length at that position, find the minimum number of jumps needed to reach the last index.
Jump Game
Given an integer array where each element represents the maximum jump length from that position, determine if you can reach the last index starting from the first index.
Longest Consecutive Sequence
Find the length of the longest consecutive element sequence in an unsorted array in O(n) time using a hash set.
Maximum Product Subarray
Given an integer array, find the contiguous subarray within the array that has the largest product, and return that product.
Maximum Sum Circular Subarray
Given a circular integer array, find the maximum possible sum of a non-empty subarray that may wrap around the ends of the array.
Maximum Subarray
Given an integer array, find the subarray with the largest sum and return its sum.
Merge Triplets to Form Target
Given a 2D array of triplets and a target triplet, determine if the target can be formed by choosing any subset of triplets and taking the element-wise maximum.
Minimum Size Subarray Sum
Find the minimal length subarray whose sum is greater than or equal to the target.
Partition Equal Subset Sum
Given an integer array, determine if it can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Permutations
Given an array of distinct integers, return all possible permutations in any order.
Product of Array Except Self
Build an output array where each element is the product of all elements except itself, without using division.
Remove Duplicates from Sorted Array II
Remove duplicates from a sorted array in-place so each element appears at most twice, using a two-pointer technique.
Rotate Array
Rotate an array to the right by k steps in-place using the reverse technique for O(1) extra space.
Rotate Image
Rotate an n x n 2D matrix by 90 degrees clockwise in-place, without allocating another matrix.
Search a 2D Matrix II
Search for a target value in an m x n matrix where each row and each column is sorted in ascending order, using an efficient staircase approach.
Search a 2D Matrix
Write an efficient algorithm to search for a target value in an m x n matrix where each row is sorted and the first integer of each row is greater than the last integer of the previous row.
Search in Rotated Sorted Array
Search for a target value in a rotated sorted array of unique integers, returning its index or -1 if not found, in O(log n) time.
Set Matrix Zeroes
Given an m x n integer matrix, if an element is 0, set its entire row and column to 0 using constant extra space.
Sort Colors
Sort an array containing only 0s, 1s, and 2s in-place using a single pass (Dutch National Flag problem).
Spiral Matrix
Return all elements of an m x n matrix in spiral order, traversing from the outer boundary inward.
Best Time to Buy and Sell Stock II
Given an array of daily stock prices, find the maximum profit you can achieve with unlimited buy-sell transactions (one share at a time).
Subarray Sum Equals K
Count the total number of contiguous subarrays whose sum equals k using a prefix sum hash map technique.
Subsets II
Given an integer array that may contain duplicates, return all possible subsets (the power set) without duplicate subsets.
Subsets
Given an integer array of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets.
Target Sum
Given an integer array and a target, assign '+' or '-' to each element and count the number of ways to achieve the target sum.
3Sum
Find all unique triplets in an array that sum to zero, avoiding duplicate triplets in the result.
Top K Frequent Elements
Find the k most frequent elements in an array using a hash map for counting and bucket sort for efficient selection.
Two Sum II - Input Array Is Sorted
Given a 1-indexed sorted array, find two numbers that add up to a target and return their indices.
Valid Sudoku
Determine if a 9x9 Sudoku board is valid by checking rows, columns, and 3x3 sub-boxes for duplicate digits using hash sets.
Word Search
Given an m x n grid of characters and a string word, determine if the word exists in the grid by following a path of adjacent cells (horizontally or vertically) without reusing any cell.
01 Matrix
Given a binary matrix, find the distance of each cell to the nearest 0 using multi-source BFS.
Code Snippets
Chunk an Array into Fixed Sizes
Splitting an array into fixed-size groups is a recurring need for pagination, batch API calls, and grid layouts. This snippet covers a one-line slice loop, a generator variant for streaming large inputs, and the edge cases (size <= 0, non-integer size, non-multiple lengths) that bite production code. Drop it in as a tiny utility and stop reaching for lodash for one helper.
Get Unique Items from an Array
Deduping an array sounds trivial until objects, NaN, and case-insensitive strings show up. This snippet walks from the one-liner everyone reaches for first, to a key-projecting variant that handles object identity, to the gotcha around NaN that catches even seasoned engineers. Pick the version that matches your data shape and keep the rest as reference.
Flatten a Nested Array
Flattening a nested array is a one-line job most of the time, but pre-built `Array#flat` is shallow by default and the depth parameter has surprises. This snippet starts with the modern built-in, adds a recursive deep-flatten that works in any environment, and ends with the iterative stack version that avoids stack-overflow on pathological inputs. Three flavours, one mental model.
Generate a Numeric Range
JavaScript still has no built-in `range()` like Python, so every codebase eventually grows its own. This snippet shows the canonical `Array.from` trick for `[0, n)`, a `start, end, step` variant that handles negative steps, and a lazy generator for huge ranges where allocating the full array is wasteful. Use it for pagination, retries, table rows, and any test fixture that needs N of something.
Safely Read the Last Element
Reading `array[array.length - 1]` is the line every JavaScript developer writes a thousand times, and a chunk of those calls hide bugs on empty arrays or computed expressions. Modern `Array.prototype.at(-1)` makes the intent obvious and supports negative indexes natively. This snippet shows the modern form, the safe-default helper for empty inputs, and the typed-array story so you pick the right tool.
Shuffle an Array (Fisher-Yates)
The naive `array.sort(() => Math.random() - 0.5)` looks fine until you measure it: the distribution is heavily biased and some pairs swap with much higher probability than others. The Fisher-Yates shuffle is the standard correct answer in O(n) time with uniform output. This snippet shows the in-place version, a non-mutating wrapper, and an empirical demo of why the popular `sort`-based trick is biased.
Group an Array by a Key
Grouping records by a derived key is one of the most common data-shaping tasks in JavaScript: bucketing users by role, orders by status, logs by date. This snippet shows a portable `Map`-based helper, a plain-object variant, and the modern `Object.groupBy` API that landed in Node 22 and recent browsers. It also covers the multi-key composite-key trick for grouping by tuples like `[city, role]`.
Partition an Array by a Predicate
Calling `array.filter(p)` and `array.filter((x) => !p(x))` works but walks the input twice and runs the predicate twice per element, which is wasteful and (for non-pure predicates) plain wrong. A single-pass `partition` returns the matched and unmatched buckets in one go. This snippet covers a clean fold-based implementation, an N-way `partitionBy` for multi-class splits, and a streaming variant that lazily partitions an iterable without materialising the full input.
Zip Multiple Arrays
Python users miss `zip(a, b)` and the Lodash crowd reaches for `_.zip`, but JavaScript can do this cleanly with one helper. This snippet covers the basic two-array zip, an N-array variadic version, the unzip inverse, and a `zipWith` that lets you fold pairs into custom shapes (records, objects, weighted sums). It also clarifies the truncate-to-shortest vs. fill-with-undefined trade-off.
Set Intersection and Difference
Computing the items shared between two arrays, the items in the first but not the second, or the symmetric difference is a routine task: comparing API responses, diffing user selections, finding new vs. removed records. This snippet shows the classic `Set`-backed implementations, an object-aware `byKey` variant, and the new native `Set.prototype.intersection` / `difference` methods that landed in Node 22 and 2024 browsers.
Two-Pointer Template
The two-pointer technique is the linear-time answer to many sorted-array problems: pair sums, palindrome checks, in-place reversal, partition. This snippet covers the opposite-ends sweep for sorted-pair targets, the reverse-in-place pattern, and the slow-fast pointer used for in-place mutation. Each fits in 10 lines and runs in O(n) time, O(1) extra space.
Stack via Array
JavaScript does not ship a dedicated `Stack` class because `Array` already supports O(1) `push` and `pop`. This snippet covers the array-as-stack idiom, a tiny class wrapper for self-documenting code, and a balanced-parentheses checker that demonstrates the canonical stack-driven algorithm. Use this template anywhere the LIFO order matters: undo, expression evaluation, DFS bookkeeping.
Insert, Update, Remove Items by Index
Index-based mutations are where most array bugs come from: `splice` mutates in place and is easy to misuse, while `slice` plus spread gives you a copy without mutating the input. This snippet contrasts the mutable and immutable forms for the four common index operations (remove by index, update by index, insert at index, remove all matching a predicate). Keep mutation explicit at the call site so reviewers know whether the original array survives.
Merge and Sort Two Arrays
Merging two arrays of numbers is the kind of task whose right answer depends entirely on whether the inputs are already sorted. This snippet shows three patterns: a simple concat-then-sort for small or unsorted inputs, the classic two-pointer linear merge for already-sorted inputs, and an in-place variant that fills a preallocated buffer for hot paths. Pick by input shape and size, not by habit.
Cloning an Array (Shallow and Deep)
Most array clones in product code are shallow, which is exactly what `[...arr]`, `Array.from`, and `slice()` give you. The trap is nested data: shallow copies share inner references, so mutating a nested object inside the copy mutates the original. This snippet walks the modern shallow forms, the older idioms still in the wild, the `structuredClone` deep-copy answer for nested data, and an object-shaped sibling for contrast.
Reversing an Array (Iterative, Recursive, Copy)
Reversing an array is a one-liner if you do not mind mutating the input, and a slightly different one-liner if you do. This snippet covers the built-in `reverse()` mutating call alongside the immutable `toReversed()` and spread alternatives, the two-pointer in-place swap that interviewers ask about, and a recursive form for the recursion lesson. Production code should pick one of the first-accordion forms; the others are for understanding.
every, some, and Includes Patterns
When you need to ask "do all of these match?" or "is there at least one match?", `Array.prototype.every` and `Array.prototype.some` give you boolean answers in one pass. This snippet covers those two plus the count-via-filter pattern for "how many match?" and a small predicate factory pattern that lets you compose these checks for form validation, feature flags, or permission rules.
Numeric Aggregations: Sum, Filter, Closest Pair
Three numeric questions you will hit again and again on real arrays: sum (with safety against non-number inputs), summary statistics (sum, average, min, max in one pass), and the smallest absolute difference between any two numbers. Each one is short, but the right answer changes with the input shape: mixed-type arrays, large arrays, and "closest pair" all reward different idioms.
Longest String and String-Length Maps
Two small but common questions on arrays of strings: which string is the longest, and how long is each one. The longest-string answer is a single `reduce`, with the tie-breaking rule explicit. The length-map answer is a single `map`, plus a tiny extension that sorts by length so the longest comes first. Both are short, but the patterns generalize to any "pick an extremum" or "shape the data for display" task.
Generate Arrays from Args, Random, and Higher-Order Inputs
Three array-generation idioms that come up constantly: building a fixed-length array of computed values (random fillers, ranges, defaults), turning function arguments into an array, and writing higher-order functions that return array transformers parameterized by a constant. Each is one line of code, but the patterns generalize to test fixtures, configuration, and small DSLs.
Value-In-Array and Value-In-Object Checks
"Is X in this array?" and "is X anywhere in this object?" sound like the same question but call for different tools. Arrays have `includes` (which handles `NaN`), `indexOf` (which does not), and `Set.has` for hot paths. Objects need `Object.values` for a flat scan and a recursive walk for nested structures. This snippet covers both, with the gotchas that bite: `NaN`, hot-path scans, and shared object identity.
Array Equality and Duplicate Detection
Three related questions on arrays: are these two arrays equal in content, does this array have any duplicates at all, and how do I dedupe a list of objects by some key. Each one has a clean linear-time answer once you know which JS collection to lean on (`Set` for primitives, `Map` for keyed objects). The naive `O(n^2)` versions are fine for tiny arrays but show up in code reviews on anything bigger.
Generate Unique Random Integers Without Bias
Picking N unique random integers from a range sounds simple, but the right algorithm depends on how N compares to the range size. Retry-into-a-Set is fine when N is small relative to the population, but as N approaches the range size retries dominate and a partial Fisher-Yates shuffle becomes the right answer. For streams of unknown size, reservoir sampling is the only option that gives uniform probability in a single pass.
Question Banks
Array Fundamentals Quiz
Quick prompts on indexing, in-place mutation, and the cost of common array operations. Good for warming up before sliding-window or two-pointer drills.
JavaScript Array Method Output Traces
Six traces drilling on in-place vs returning array methods: `reverse`, sparse arrays, `indexOf`, `filter(Boolean)`, default lexicographic `sort`, and `copyWithin`.
JavaScript Array and Object Fundamentals Quiz
Test the day-one moves for working with arrays and objects: type-checking, copying, deduping, and the gotchas hiding under shallow vs deep clones.
Array Cross-Reference and Lookup Challenges
Six lookup-and-filter drills: id-to-id matching with Sets, random sampling without duplicates, valid-only filtering, numeric-only extraction, value-by-row matching, and rest-parameter multipliers.
Array Sorting and Grouping Challenges
Six sorting/grouping problems: dynamic key sort, multi-key sort, top-N average, date sort, top-N max preserving identity, group-by, and id-driven custom ordering.
Array Higher-Order Methods Quiz (map / filter / reduce / find)
Four drills on the core array higher-order methods: reduce for aggregation, filter plus reduce (or Math.max) for selection, find for first-match lookup, and flatMap for one-step map-and-flatten.
JavaScript Take-Out-and-Rest Array: Two Approaches Quiz
Two seeded approaches to build a map of each-element-to-the-rest (reduce + filter and forEach + filter), plus two companions on slice + concat and a complexity discussion.
JavaScript Count Backward by Evens: Two Approaches Quiz
Two seeded approaches to enumerate even numbers descending from n (filter-on-step-1 vs step-2 loop), plus two companions on Array.from and an odd-start edge case.
JavaScript Object Values to Array: Two Approaches Quiz
Two seeded approaches to convert an object's values to an array (Object.values spread vs Object.keys.map) plus two companions on Object.entries and ordering pitfalls.
JavaScript Group Students by ID: Two Approaches Quiz
Two seeded approaches to group an array of student records by id (reduce + dict and the `in` operator), plus two companions on Map and Object.groupBy.
JavaScript Largest Difference Without Sort: Two Approaches Quiz
Two seeded approaches to compute the largest pairwise difference in an array without sorting (single-pass min/max and the brute-force nested loop), plus two companions on prefix tracking and a negative-numbers twist.
JavaScript Top-N Numbers (Preserving Order): Two Approaches Quiz
Return the N largest numbers from an array while keeping their original order, two ways (sort-and-filter-back and threshold partition), plus two companions on ties and a heap-style streaming variant.
JavaScript Min/Max Leave-One-Out Sum: Three Approaches Quiz
Compute the smallest and largest "drop one and sum the rest" totals three ways (sort + slice, total-sum minus extremum, single-pass min/max tracker), plus two companions on streaming inputs and a top-K leave-out generalisation.
JavaScript Top-N Numbers: Two Approaches Quiz
Return the N largest numbers from an array (order-not-required), two ways (sort + slice and one-pass min-tracking buffer), plus two companions on heap-style updates and tie-aware quickselect.
JavaScript Array Occurrences Count: Two Approaches Quiz
Tally how many times each value appears in an array, two ways (reduce + dict and Map-based counter), plus two companions on Object.create(null) safety and case-insensitive string tallies.
JavaScript Grouped Scores Filter: Two Approaches Quiz
Filter a grouped scores object so each row keeps only requested keys, solved two ways (Object.entries + map and a for-in loop), plus companions on Map output and key-rename mapping.
JavaScript Binary Array Plant Pots: Two Approaches Quiz
Decide whether N new plants can be potted into a binary array of pots with no two plants adjacent. Two approaches (greedy single pass, lookahead with neighbour check), plus capacity counting and input validation.
JavaScript Missing Numbers Finder: Two Approaches Quiz
Find missing integers between the min and max of an array, two ways (sort + gap-walk and Set diff over min..max), plus companions on the consecutive-1..n case and detecting duplicates.
JavaScript Array Pair Extraction: Two Approaches Quiz
Split an array into consecutive pairs (with a trailing single when the length is odd), two ways (reduce with odd-index push and a stepped slice loop), plus companions on a generic chunk size and a lazy generator variant.
JavaScript Spread Operator Refactor: Two Explanations Quiz
Refactor a manual `sum(nums[0], nums[1], nums[2])` call with the spread operator, two equivalent shapes (spread shortcut and the older `apply(null, nums)` form), plus companions on rest parameters and array-spread vs concat.
JavaScript Largest Difference in Array: Three Approaches Quiz
Three seeded ways to compute the maximum pairwise gap in an integer array (sort and subtract ends, reduce with Math.max and Math.min, single-pass tracker), plus two companions on edge cases and complexity.
JavaScript Pair-Sum Finder: Two Approaches Quiz
Two seeded ways to test whether two numbers in an array add up to a target (nested loop and Set complement), plus two companions on time complexity and on returning the actual pair instead of a boolean.
JavaScript find vs filter for Student Lookup Quiz
Two seeded approaches to look up students by name: `find` returns the first match, `filter` returns every match. Two companions cover return-type pitfalls and short-circuit semantics.
JavaScript String Lengths Array: Four Approaches Quiz
Four seeded ways to turn an array of strings into an array of their lengths (map, for-loop with push, reduce, for-of), plus one companion on a recursive variant.
JavaScript Recipe Batches: Two Approaches Quiz
Two seeded ways to compute how many full batches can be produced from available materials (imperative loop with Math.min and a reduce-based variant), plus two companions on missing-key handling and zero-quantity edge cases.
JavaScript Group By ID with Average Score: Two Approaches Quiz
Two seeded ways to group records by id and compute each group's average (bucket-then-divide vs running sum + count), plus two companions on min/max per group and on memory trade-offs at scale.
JavaScript Set and Map Values Output: Two Explanations Quiz
Two seeded explanations of how `Set` and `Map` expose their values via iterators and what `console.log` prints when you call `.values()` on each, plus two companions on insertion-order guarantees and on de-duplication semantics.
Community
Stone Game
Decide whether the first player wins a take-from-either-end stone game on an even-length pile, with both players playing optimally.
Subdomain Visit Count
Aggregate visit counts across every subdomain prefix from a list of count-paired domain strings.
Paint House III
Find the minimum cost to paint exactly target neighborhoods of n houses with k colors, using 3D DP over (index, last color, neighborhoods so far).
Excel Sheet Column Number
Convert a spreadsheet column title (`A`, `Z`, `AA`, `AB`, ...) into its 1-based column number using bijective base-26.
Core Data Structures Warmup
Two quick whiteboard questions on array vs linked list complexity and hash-map two-sum. Five minutes each.
Two City Scheduling
Send exactly half the candidates to city A and half to city B at minimum total cost.
Split Array Largest Sum
Split a non-negative integer array into k contiguous parts that minimize the maximum part sum, via binary search on the answer plus a greedy feasibility check.
Find Smallest Letter Greater Than Target
Classic upper_bound on a sorted character array, with a wrap-around twist that makes the binary-search invariants worth thinking through carefully.
Combination Sum III
Find all unique k-digit combinations from 1-9 that sum to a target n, using cardinality-bounded backtracking.
Subarrays with K Different Integers
Count subarrays containing exactly K distinct integers using the at-most-K window trick.
Find Pivot Index
Find the leftmost index where the sum of elements to its left equals the sum to its right.
Maximum XOR of Two Numbers in an Array
Find the maximum bitwise XOR of any two elements in an integer array using a bit-trie that's queried greedily from the most significant bit down.
Subarray Product Less Than K
Count contiguous subarrays whose product is strictly less than k, in linear time using a sliding window.
Snapshot Array
Implement an array-like structure with constant-time set / snap and binary-search get-at-snapshot, using per-index version lists.
Move Zeroes
Move every zero to the end of the array in place while keeping the relative order of the non-zero elements.
Find All Duplicates in an Array
Identify every value that appears twice in an array of integers in [1, n], using O(1) extra space via index-negation.
Squares of a Sorted Array
Return the squares of a sorted integer array, also sorted, in O(n) time using a two-pointer merge from the ends.
Capacity to Ship Packages Within D Days
Binary-search-on-answer for the smallest belt capacity that ships all packages in order within D days, with a linear feasibility check per candidate.
Find K Closest Elements
Find a length-k window in a sorted array whose elements are closest to x, using a binary search on the LEFT edge of the window.
Design Hit Counter
Build a counter that returns the number of hits in the past 5 minutes (300 seconds), with monotonically non-decreasing timestamps.
Max Consecutive Ones III
Find the longest contiguous subarray of 1s achievable when you can flip at most K zeros.
Running Sum of 1d Array
Build the prefix-sum array in place: each output index holds the cumulative sum of nums up to that index.
Sort Array By Parity
Rearrange the array so that every even integer appears before every odd integer; any valid arrangement is accepted.
Delete and Earn
Maximize total points earned by picking values, where picking value v deletes v-1 and v+1, by reducing to House Robber on a frequency line.
Fruit Into Baskets
Find the longest contiguous subarray that contains at most two distinct values.
Asteroid Collision
Simulate collisions between right- and left-moving asteroids using a stack of survivors, popping while the top loses head-on encounters.
