Software Engineering
From arrays and Big-O to graphs, advanced trees and interview patterns, with practice platforms.
Learn how data is organised and how to reason about the cost of operating on it. The path starts with one language and complexity analysis, moves through sorting, searching, trees and graphs, and ends with specialised structures and the problem-solving patterns used in technical interviews.
The subjects follow the roadmap.sh Data Structures & Algorithms roadmap.
Algorithms are language-neutral, but you practise them in one concrete language, so choose one you can write without looking things up. Python and JavaScript keep the code short; Java, C++ and C# make memory and types more visible. Stick with one until the ideas click.
Arrays double as stacks (push/pop), Map and Set give hashing, but there is no built-in heap or deque, so you write your own. Array.prototype.sort compares as strings unless you pass a comparator.
The Collections Framework ships ArrayList, ArrayDeque, HashMap, TreeMap and PriorityQueue, which covers most interview needs. Verbose, but static types and predictable performance make complexity easy to reason about.
Slices and maps are built in, container/heap gives a heap through an interface you implement, and sort.Slice sorts with a closure. Little hidden magic, so the cost of each operation is visible.
Expressive enumerables (each_with_index, group_by, each_cons) make solutions compact. The standard library lacks a priority queue, so heap-based problems need a hand-rolled implementation.
.NET provides List<T>, Dictionary<K,V>, HashSet<T>, SortedSet<T> and, since .NET 6, PriorityQueue<TElement,TPriority>. LINQ is handy but hides allocations, so be careful inside tight loops.
The favourite of competitive programmers: the STL gives vector, deque, unordered_map, set, priority_queue and algorithms like sort and lower_bound, all fast with documented complexity guarantees.
Shortest path from idea to working code: lists, dict, set, collections.deque, heapq and bisect cover nearly everything. Watch out for slow pure-Python loops and the default recursion limit of about 1000.
Vec, VecDeque, HashMap, BTreeMap and BinaryHeap are in std::collections. Ownership makes linked structures like trees and graphs awkward; index-based arenas or Rc<RefCell<_>> are the usual workarounds.
Before data structures you need fluent basics: variables, loops, conditionals, functions and a little object orientation. If writing a loop still takes effort, the algorithm on top of it will be hard to see.
Know how your language declares variables, literals, operators and blocks, and its integer behaviour: Python ints never overflow, while Java and C++ int silently wrap at 2^31.
if/else, for, while, break and continue decide which code runs and how often. Loop bounds and off-by-one errors are where most algorithm bugs hide, so trace small inputs by hand.
An informal, language-free sketch of the steps. Writing it first separates "what is the algorithm" from "how does my language spell it", and is how textbooks and interviewers usually present ideas.
Parameters, return values and scope, plus whether arguments are passed by value or reference. Recursion, callbacks and comparators passed to sort all build on being comfortable with functions.
Classes bundle state with the methods that guard it, which is exactly how a Stack or LinkedList is written. Learn constructors, encapsulation and interfaces; deep inheritance trees rarely matter here.
A data structure is a way of laying out data in memory together with the operations it supports cheaply. An array gives instant access by index, a hash table gives fast lookup by key, a tree keeps data ordered. Each choice makes some operations fast and others slow.
The same task can take milliseconds or hours depending on the structure behind it: checking membership in a list is O(n), in a hash set O(1) on average. Picking the right structure is often the whole optimisation, and it is what interviews probe.
Five structures carry most real code: contiguous arrays, pointer-linked lists, LIFO stacks, FIFO queues and hash tables. For each one, learn its memory layout, what insert, delete and lookup cost, and which standard-library type implements it in your language.
Contiguous memory, so index access is O(1) and iteration is cache-friendly. Inserting or deleting in the middle shifts elements, O(n). Dynamic arrays double capacity when full, giving amortised O(1) appends.
Nodes hold a value and a pointer to the next (and in doubly linked lists, the previous) node. Insert and delete at a known node are O(1), but reaching the k-th element is O(n). A dummy head node simplifies edge cases.
First in, first out: enqueue at the back, dequeue from the front, both O(1) with a ring buffer or linked list. Popping from the front of a Python list is O(n), so use collections.deque. Queues drive breadth-first search.
Last in, first out with O(1) push and pop. Used for undo, matching brackets, evaluating expressions and simulating recursion iteratively. A monotonic stack solves "next greater element" problems in O(n).
A hash function maps keys to buckets, giving O(1) average insert and lookup, O(n) in the worst case when many keys collide. Collisions are resolved by chaining or open addressing; keys must be immutable and hashable.
Complexity describes how running time and memory grow as the input grows, ignoring constant factors and hardware. It lets you compare approaches before writing code and predict whether a solution survives n = 10^5.
Time counts basic operations; space counts extra memory beyond the input, including the recursion stack. They often trade off: caching results in a hash map buys speed with memory.
Count how often the innermost work runs: sequential blocks add, nested loops multiply, halving the input each step gives a log factor. For recursion, write a recurrence such as T(n) = 2T(n/2) + n and solve it, e.g. with the master theorem.
A family of notations that describe a function's growth for large n while dropping constants and lower-order terms. O gives an upper bound, Ω a lower bound and Θ a tight bound.
f(n) = O(g(n)) means f grows no faster than g beyond some point, up to a constant. In practice people use it for the worst case: "binary search is O(log n)".
A tight bound: the function is both O(g) and Ω(g), so it grows at exactly that rate. Merge sort is Θ(n log n) in every case, which is a stronger statement than O(n log n).
A lower bound: the function grows at least as fast as g. Any comparison sort needs Ω(n log n) comparisons in the worst case, so none can beat that bound.
A handful of growth classes cover almost every algorithm you will meet. Recognising them and knowing roughly which input sizes each can handle in a second is the fastest sanity check on an approach.
O(1): the cost does not depend on n. Array indexing, pushing to a stack and average hash-table lookup are constant time, though the constant itself can still be large.
O(log n): each step discards a constant fraction of the input, as in binary search or descending a balanced tree. A billion items need only about 30 steps.
O(n): touch each element a constant number of times, like summing a list or a linear search. Usually the best possible when every input must be read at least once.
O(n^k) for a fixed k, such as O(n²) for comparing every pair with nested loops. Quadratic is fine for a few thousand items and too slow around 10^5 or more.
O(2^n): work doubles with each extra item, typical of trying every subset. Workable up to n ≈ 25; beyond that you need pruning, memoisation or a smarter formulation.
O(n!): generating every ordering, as in brute-force travelling salesman. Already about 3.6 million at n = 10, so it only works for tiny inputs.
Sorting is the classic place to learn trade-offs: time, extra memory, stability and behaviour on nearly-sorted data. In real code you call the library sort; implementing the classics teaches divide and conquer, invariants and analysis.
Repeatedly swap adjacent out-of-order pairs until a full pass makes no swaps. O(n²), stable and in place; only useful as a teaching example.
Split in half, sort each half recursively, then merge the two sorted halves. Always O(n log n) and stable, but needs O(n) extra memory. Ideal for linked lists and external sorting of huge files.
Grow a sorted prefix by inserting each new element into place. O(n²) in general but O(n) on nearly-sorted input, so hybrid sorts like Timsort use it for small runs.
Pick a pivot, partition smaller elements left and larger right, recurse on both sides. O(n log n) on average and fast in practice, O(n²) with bad pivots; random pivots make that unlikely. Not stable.
Find the minimum of the unsorted part and swap it to the front, repeat. Always O(n²) comparisons but at most n swaps, which matters only when writes are expensive.
Build a max-heap in O(n), then repeatedly move the root to the end and sift down. O(n log n) worst case with O(1) extra space, but not stable and less cache-friendly than quicksort.
Finding an item is the most common operation of all. Unsorted data forces a scan; sorted data lets you halve the range every step. The same halving idea also searches over answers, not just arrays.
Check each element in turn until you find a match. O(n), works on any sequence, and for small arrays often beats cleverer methods thanks to its simplicity.
On sorted data, compare with the middle and discard the half that cannot contain the target: O(log n). Off-by-one errors are notorious, so fix one loop invariant (e.g. half-open [lo, hi)) and stick to it. Python has bisect.
Trees store hierarchical data: one root, each node with children, no cycles. Balanced search trees keep data ordered with O(log n) operations, heaps give fast access to the minimum, and file systems, DOMs and indexes are all trees.
Each node has at most a left and right child. Height ranges from log n when balanced to n when degenerate, and most tree problems are solved by recursing on the two subtrees.
Every left-subtree key is smaller and every right-subtree key larger than the node, so search, insert and delete follow one path from the root. Inserting sorted data unbalances it into a linked list.
A self-balancing BST that keeps the heights of sibling subtrees within one of each other, restoring balance with rotations after updates. Guarantees O(log n) operations; red-black trees relax balance for cheaper writes.
Each node holds many sorted keys and has many children, so the tree is very shallow. Designed so one node fits a disk page, which is why databases and file systems use B-tree variants.
A complete binary tree, stored in an array, where each parent is no larger (min-heap) than its children. Read the minimum in O(1), push and pop in O(log n). Python's heapq and Java's PriorityQueue are min-heaps.
Visiting every node once, either depth-first (pre-, in- or post-order) or level by level with a queue. Recursive versions are short; iterative ones use an explicit stack and avoid recursion limits on deep trees.
Left subtree, node, right subtree. On a binary search tree this yields keys in sorted order, which makes it the standard way to validate a BST or find its k-th smallest key.
Node first, then left and right subtrees. The natural order for copying or serialising a tree, since each parent is recorded before its children.
Both subtrees before the node, so children are finished first. Use it when a node needs results from below: computing heights or sizes, freeing memory, or evaluating an expression tree.
A graph is a set of vertices joined by edges, the model behind maps, networks, dependencies and social links. Store it as an adjacency list for sparse graphs or a matrix for dense ones, then reach for traversal, shortest path and spanning tree algorithms.
Edges have a direction, like "A depends on B" or a one-way street. Cycle detection and topological sorting of DAGs are the key algorithms for build systems and task scheduling.
Edges work both ways, as in a friendship or a two-way road; store each edge in both adjacency lists. Typical questions are connectivity, connected components and spanning trees.
Explore outward in layers using a queue, marking vertices as visited when enqueued. Finds shortest paths by edge count in unweighted graphs and prints trees level by level, in O(V + E).
Go as deep as possible before backtracking, with recursion or an explicit stack. The basis for cycle detection, topological sort, connected components and backtracking searches, in O(V + E).
Pick by edge weights: BFS when unweighted, Dijkstra for non-negative weights, Bellman-Ford when weights can be negative, Floyd-Warshall for every pair on small graphs, A* when a good distance estimate exists.
Repeatedly settle the unvisited vertex with the smallest known distance, using a min-heap, and relax its edges. O((V + E) log V); wrong as soon as any edge weight is negative.
Relax every edge V − 1 times; if a further pass still improves a distance, a negative cycle is reachable. O(V·E), slower than Dijkstra but handles negative weights.
Dijkstra guided by a heuristic: expand the vertex with the lowest cost-so-far plus estimated cost-to-goal. With an admissible heuristic such as straight-line distance it stays optimal while exploring far less; standard in games and maps.
The cheapest set of edges connecting every vertex of a weighted, undirected graph without cycles. Models laying cable or pipes at minimum cost; Prim and Kruskal both find it greedily.
Grow one tree from a start vertex, always adding the cheapest edge leaving it, found with a min-heap. O(E log V), a good fit for dense graphs.
Sort all edges by weight and add each one unless it would close a cycle, checked with a union-find structure. O(E log E), simple to write and well suited to sparse graphs.
Specialised structures that answer one kind of query far faster than the basics: prefix lookups, range sums, connectivity and substring search. They show up in competitive programming, search engines and harder interview rounds.
A prefix tree where each edge is a character and each path from the root spells a key. Lookup and insert cost O(key length) regardless of how many keys exist; behind autocomplete and spell checkers.
A binary tree over array ranges where each node stores an aggregate (sum, min, max) of its range. Range queries and point updates take O(log n); lazy propagation adds range updates.
A binary indexed tree: an array where index bits decide which partial sums each cell stores. Prefix sums and point updates in O(log n) with a few lines of code, lighter than a segment tree but less flexible.
Keeps a forest where each tree is one group: find returns a root representative and union links two roots. Add path compression plus union by rank and each call costs almost O(1) amortised. Powers Kruskal's MST and connectivity queries.
Index every suffix of a string so substring search, longest repeated substring and similar queries become fast. A suffix array is the sorted list of suffix positions; it uses far less memory than a suffix tree.
Balanced multi-way trees and probabilistic lists that keep large ordered datasets fast to search and update, often on disk. They underpin database storage engines and ordered in-memory stores.
Every internal node has two children and one key, or three children and two keys, and all leaves sit at the same depth. Inserts split full nodes upward, keeping perfect balance; red-black trees are an encoding of the same idea.
In a B+ tree only leaves hold records and the leaves are linked in order, so range scans walk sideways without revisiting the root. Most relational database indexes, including InnoDB and PostgreSQL btree, follow this design.
A sorted linked list with extra randomly-chosen "express lane" levels, giving expected O(log n) search and insert without any rebalancing. Redis sorted sets are built on one.
Indexed Sequential Access Method: records stored sequentially with a static index on top, from IBM mainframes. Fast reads, but inserts go to overflow areas and need periodic reorganisation, which is why B+ trees replaced it.
An index is an extra structure that maps keys to where records live, trading storage and slower writes for much faster reads. The choice of index structure decides which queries (exact match, range, prefix) are cheap.
A sorted list of key and position pairs, searched with binary search. Simple and compact for static data, but each insert shifts entries, so it suits read-mostly files rather than busy tables.
Balanced trees such as B+ trees keep the index sorted while absorbing inserts and deletes in O(log n), and support range queries. Hash indexes are faster for exact matches but cannot answer ranges.
General strategies for designing an algorithm when nothing obvious fits. Start with brute force to understand the problem, then look for structure: overlapping subproblems, a safe greedy choice, or a way to split the input.
Try every candidate and keep the ones that work. Easy to get right, often too slow, but a perfect baseline for testing faster solutions against and the first thing to state in an interview.
Build a solution step by step and undo the last choice as soon as it cannot lead anywhere. Solves permutations, subsets, N-Queens and Sudoku; good pruning is what makes it fast enough.
Take the locally best choice at each step and never revisit it. Correct only when you can prove the greedy choice is safe, as with interval scheduling, Huffman coding or Dijkstra; otherwise it silently gives wrong answers.
Use random choices to get good expected performance or simple code: random pivots in quicksort, quickselect, hashing, skip lists. Las Vegas algorithms are always correct, Monte Carlo ones may err with small probability.
Split the problem into independent smaller pieces, solve each recursively, combine the results. Merge sort, quicksort and binary search follow this shape, and the master theorem gives their running times.
A function that calls itself on a smaller input, with a base case that stops it. Natural for trees and divide and conquer; every call uses stack space, so very deep recursion can overflow.
When subproblems overlap, solve each once and reuse it, either top-down with memoisation (functools.cache) or bottom-up with a table. Define the state and the transition first; the code follows.
Recurring shapes behind many interview problems. Once you can name the pattern from the problem statement, the solution template follows. These sit beside the problem-solving techniques on the roadmap and were split out here to keep the lists short.
Move two indices through a sorted array or string, often from both ends inward, to replace a nested O(n²) loop with O(n). Classic uses: pair sums in sorted arrays, removing duplicates in place, palindrome checks.
Keep a contiguous window and update its state incrementally as one end grows and the other shrinks, instead of recomputing every subarray. Fits "longest or shortest substring or subarray with property X" problems.
Two pointers moving at different speeds through a linked list or sequence. If there is a cycle they meet (Floyd's algorithm); when the fast one hits the end, the slow one is at the middle.
Find the k-th largest or smallest item without fully sorting: keep a size-k heap in O(n log k), or use quickselect for O(n) on average. Also covers "top k frequent" style problems.
Split elements between a max-heap for the lower half and a min-heap for the upper half, rebalancing so their sizes differ by at most one. The tops then give a running median in O(log n) per insert.
Sort intervals by start, then sweep once, extending the current interval while the next overlaps it. The same sort-then-sweep idea handles meeting rooms, insertions and intersections of interval lists.
When an array holds numbers in a known range like 1..n, swap each value straight into its own index. One O(n) in-place pass then reveals missing or duplicate numbers.
Treat a grid as a graph whose cells connect to their neighbours, and flood-fill each unvisited land cell with BFS or DFS to count or measure regions. Mark cells visited to avoid revisiting them.
Problems about coordinating threads: ordering their output, producer-consumer queues, avoiding races and deadlocks. Solved with locks, condition variables, semaphores or blocking queues rather than clever algorithms.
Reading about algorithms is not enough; you get fast by solving many problems against automatic judges. Aim for steady daily practice grouped by pattern rather than random marathons.
The standard interview-prep site: thousands of problems tagged by topic and difficulty, an online judge for many languages, and weekly contests. Many problems and the company tags require Premium.
Short, beginner-friendly challenges with gentle difficulty steps. A good warm-up for building language fluency before moving on to harder algorithm problems.