Sorting
sorting
Data Structures
Suffix Array / Suffix Tree
Genome alignment tools like BWA and Bowtie find a 100-character read inside a 3-billion-base human reference in milliseconds, not by scanning the genome but by querying an index built once over all of its suffixes. **Suffix Array / Suffix Tree** is the family of data structures behind that workflow, and the same machinery powers full-text search, plagiarism detection, and the BWT-based compression in bzip2. This lesson covers the suffix array (a sorted array of starting positions of every suffix), the binary-search pattern match in `O(m log n)` for a pattern of length `m`, the LCP (Longest Common Prefix) array that captures shared prefixes between adjacent sorted suffixes, and the suite of substring problems the pair solves: longest repeated substring, number of distinct substrings, and longest common substring. You will also meet the suffix tree, a compressed trie of all suffixes that pushes pattern matching down to `O(m)` independent of text length, and weigh the suffix array's smaller memory footprint against the suffix tree's faster query. In **Arrays & Strings**, sorting and binary search worked over numbers; here the same primitives extend to strings, with a comparator that compares characters position by position. **Trie (Prefix Tree)** introduced the prefix-matching tree shape, and a suffix tree is a compressed trie built from every suffix of the input. Next, the curriculum explores data structures organized around a different axis entirely: preserving every historical version of themselves through time.
Not Started
0%
Algorithms
Computational Geometry
The sign of a single 2D cross product tells you whether three points turn left, turn right, or are collinear, and that one signed scalar is the workhorse behind almost every algorithm in the plane. Convex hulls, polygon area, segment intersection, and point-in-polygon tests all reduce to a sequence of cross-product evaluations with a careful eye on edge cases. Get the geometric primitive right and the rest of the field follows. **Computational Geometry** introduces those primitives and the algorithms built on them. You will start with cross products and the orientation test, then implement convex-hull algorithms three ways: Graham scan in `O(n log n)` (sort by polar angle, maintain a stack with the orientation invariant), Jarvis march in `O(nh)` for hulls with few vertices, and Andrew's monotone chain. The lesson then covers line-segment intersection, the sweep-line algorithm for many segments, the closest-pair-of-points algorithm in 2D, polygon computations using the Shoelace formula, and the ray-casting point-in-polygon test. In **Sorting (Elementary)**, you learned the comparison-based sorting that drives polar-angle preprocessing. **Divide and Conquer (Advanced)** taught you the closest-pair `O(n log n)` template via the strip combine step, which reappears here. Next, **Advanced Tree Algorithms** moves from planar geometry back to hierarchical structures with Binary Lifting and centroid decomposition.
Not Started
0%
Greedy (Intro)
Given coin denominations of 1, 5, and 25, the greedy "take the largest coin that fits" strategy gives change optimally. Add a coin worth 10 to the system and greedy stays optimal. Replace 25 with 21 and greedy quietly breaks: making 63 cents now wants three 21s, but greedy says one 21 plus two 1s and ten more 1s. The same algorithm, the same input shape, and yet correctness depends entirely on a structural property of the problem. **Greedy (Intro)** explains exactly which property that is. You will learn to test for the greedy-choice property and optimal substructure, the twin ingredients that justify a greedy decision. The lesson covers the canonical problems where greedy provably works (activity selection by earliest end time, fractional knapsack by value-to-weight ratio, job scheduling with deadlines, the jump game, Huffman encoding) and walks through the exchange-argument style of correctness proof. It also shows where greedy fails (0/1 knapsack, coin change with arbitrary denominations) so you know when to reach for DP instead. In **Sorting (Elementary)**, you saw why sorting often costs `O(n log n)`; almost every greedy algorithm starts with a sort step. **Big-O Notation (Upper Bound)** gave you the language to express that cost. Next, **Dynamic Programming (Intro)** picks up where greedy fails, when the local optimum does not guarantee the global one.
Not Started
0%
Sorting (Advanced)
When you call `arr.sort()` in Python or JavaScript, you are running Timsort, an industrial-strength hybrid that switches between merge sort for long runs and insertion sort for short ones. Sorting a billion elements in seconds is possible only because someone, decades ago, broke the `O(n^2)` ceiling that bubble sort, selection sort, and insertion sort all sit beneath. This lesson is where you learn how. **Sorting (Advanced)** covers the comparison-based `O(n log n)` algorithms (merge sort, quick sort, heap sort) and the non-comparison sorts (counting sort, radix sort, bucket sort) that beat that bound under structural assumptions about the data. For each you will trace the divide, sort, combine pattern (or its non-recursive equivalent), analyze best, average, and worst case, examine pivot strategies and partitioning schemes for quick sort, and see why heap sort runs in place. The lesson closes with the `O(n log n)` lower bound for comparison sorting and a quick tour of how built-in sorts (Timsort, V8) blend these techniques. In **Sorting (Elementary)**, you mastered the vocabulary of passes, swaps, invariants, and stability on `O(n^2)` algorithms. **Recursion Fundamentals** gave you the call-stack model that explains the `O(log n)` factor in merge and quick sort. Next, **Binary Search Templates** capitalize on sorted output to solve an entire class of medium-difficulty interview problems.
Not Started
0%
Sorting (Elementary)
Insertion sort is `O(n^2)` and quick sort is `O(n log n)`, yet V8 actually runs insertion sort on arrays shorter than ten elements because the constant factors are smaller. The takeaway is that elementary sorts are not just historical curiosities; they are the algorithms that real engines drop down to once an array is small enough. **Sorting (Elementary)** walks through bubble sort, selection sort, and insertion sort in detail. For each, you will trace the pass-by-pass behavior on a small input, count comparisons and swaps, and analyze worst, best, and average time complexity. Along the way the lesson introduces the vocabulary that every later sorting topic relies on: passes, the growing sorted region, the loop invariant that proves correctness, in-place vs. extra-space sorts, and stability (whether equal keys keep their original relative order). In **Arrays & Strings**, you learned how arrays store and index data; sorting is the first time you will rearrange that storage in place. **Iteration Patterns on Arrays/Strings** trained you in nested loops and swaps, and these three sorts are essentially structured nested loops with a clear invariant. Up next, **Searching (Basics)** establishes the linear-search baseline whose `O(n)` cost is exactly what binary search will later cut down once your data is sorted.
Not Started
0%
Practice Problems
Meeting Rooms
Given an array of meeting time intervals, determine if a person could attend all meetings without any overlap.
Merge Sorted Array
Merge two sorted arrays into one sorted array in-place, using the extra space at the end of the first array.
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.
Minimum Interval to Include Each Query
Given a list of intervals and a list of queries, for each query find the size of the smallest interval that contains it, or -1 if no interval contains it.
Reconstruct Itinerary
Given a list of airline tickets, reconstruct the itinerary in lexical order starting from 'JFK', using all tickets exactly once.
Car Fleet
Given positions and speeds of cars heading toward a target, determine how many car fleets will arrive at the destination.
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.
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.
IPO
Maximize capital after completing at most k projects by greedily selecting the most profitable affordable projects using a max-heap.
K Closest Points to Origin
Find the k closest points to the origin using a max-heap to efficiently track the k smallest distances.
Find K Pairs with Smallest Sums
Given two sorted arrays, find the k pairs with the smallest sums using a min-heap to efficiently explore candidates.
Kth Largest Element in an Array
Find the kth largest element in an unsorted array using a min-heap or quickselect algorithm.
Meeting Rooms II
Given an array of meeting time intervals, determine the minimum number of conference rooms required to hold all meetings.
Merge Intervals
Given an array of intervals, merge all overlapping intervals and return an array of the non-overlapping intervals that cover all the intervals in the input.
Minimum Arrows to Burst Balloons
Given balloons represented as horizontal intervals, find the minimum number of vertical arrows needed to burst all balloons.
Non-overlapping Intervals
Given an array of intervals, return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Sort Colors
Sort an array containing only 0s, 1s, and 2s in-place using a single pass (Dutch National Flag problem).
Sort List
Given the head of a linked list, sort it in ascending order using O(n log n) time and O(1) or O(log n) space.
Subsets II
Given an integer array that may contain duplicates, return all possible subsets (the power set) without duplicate subsets.
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.
Code Snippets
Quick Sort One-Liner in Python
The functional Quicksort one-liner in Python is a classic teaching artifact: it is short enough to fit on one line and shows comprehensions plus recursion working together. This snippet covers the three-way functional one-liner, an in-place Lomuto-partition variant for performance, and a benchmark contrast against `sorted` to show why the one-liner is for teaching, not production.
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.
Question Banks
Sorting Algorithm Speed Round
Quick drills on quicksort, mergesort, heapsort, and counting sort: best / average / worst times, stability, and when each one wins.
External Sorting and Merge Pass
Disk-aware sorting when data exceeds memory. Drills cover run generation, k-way merge with a heap, and pass-count math.
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.
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 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.
Community
bisect Instead of sort() on Every Insert (Python)
I had a leaderboard insert loop running list.append + list.sort. Swapping to bisect.insort cut the loop from 4.2s to 0.14s on 50k inserts. The 5-line rewrite plus the keyed variant is here.
Boats to Save People
Given person weights, a boat capacity, and a 2-person-per-boat limit, find the minimum number of boats.
Top K Frequent Words
Return the k most frequent words, breaking frequency ties alphabetically and returning results in descending frequency.
Two City Scheduling
Send exactly half the candidates to city A and half to city B at minimum total cost.
Sorting Algorithms Compared
The complete comparison table, why your standard library is almost always faster than what you would write, and the two questions that decide which sort you actually want.
Quick Sort in Three Lines, and Why It's Wrong
Every interview blog shows the cute three-line quicksort. It's a teaching aid that looks elegant and ships bugs: O(n log n) extra memory, quadratic on sorted input, and unstable. Here is the cute version, the in-place version we should actually write, and the version with a randomized pivot.
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.
