Dev guide :: Data Structures and Algorithms

Data Structures and Algorithms

A data structure organizes information; an algorithm describes the steps that operate on it. Good choices make a solution easier to explain, verify and scale. This developer guide builds intuition through complete programs, invariants, execution traces and explicit trade-offs.

Start with complexity, binary representation and arrays, continue through linked structures and trees, then study searching, sorting, graphs and problem-solving techniques. Each of the 22 worked examples is available in every programming language supported by Dev Handbooks. Changing the selector updates every implementation while keeping the problem, inputs and expected results consistent.

The examples favor readable algorithms over production container implementations. Standard libraries are used where appropriate; manual implementations expose the mechanism where useful. Copy a complete program or use its sandbox action to experiment. Runtime availability depends on the sandbox configuration; the snippets specify any special requirements in comments.

Ada programs can be compiled locally with GNAT; the current online sandbox does not provide Ada execution.

The selection applies to all 22 worked examples.

Complexity & correctness

First define the input size. For a sequence, n usually means its element count; for a graph, V and E mean vertices and edges; for a string, L means its length in the representation being processed. Complexity describes how resource use grows with those sizes, rather than predicting milliseconds on one machine.

Big O, tight bounds and practical cost

Big O is an asymptotic upper bound. Big Ω is a lower bound and Big Θ is a tight bound. Saying an algorithm is O(n²) does not prove that bound is tight: a linear scan also satisfies that loose upper bound. State the input case and use a tight bound when it helps comparison.

GrowthExampleWhen n doubles
O(1)Array index lookupBounded work independent of n
O(log n)Binary searchAbout one more halving step
O(n)Sum an arrayAbout twice the work
O(n log n)Merge sortA little more than twice the work
O(n²)Compare every pairAbout four times the work
O(2ⁿ)Enumerate all subsetsThe number of subsets is squared

A loop that visits n elements performs linear work. Two independent full loops are still linear: n + n = 2n. Two nested full loops can perform n × n operations and be quadratic. A nested loop is not automatically quadratic: if one pointer only advances across the input once, total pointer movements may still be linear.

Worst-case, expected and amortized analysis

Worst-case analysis bounds the most expensive input of a given size. Expected analysis averages over a stated probability model, such as randomized hashing. Amortized analysis spreads cost across a sequence of operations without requiring randomness. With geometric capacity growth, n dynamic-array appends require O(n) total copying and insertion work, even though a single resizing append can cost O(n).

Count auxiliary space separately from input and output. A recursive traversal uses call-stack memory even if it allocates no explicit container. Returning all subsets requires exponential output storage; printing one subset at a time only needs the current path. Constants, allocations, locality and data representation still matter: benchmark realistic inputs after proving correctness.

How to argue that an algorithm is correct

  1. State preconditions: sorted input, valid indices, positive coins or nonnegative edge weights.
  2. Define an invariant that is true before an iteration or recursive call.
  3. Show that each step preserves it and makes progress toward termination.
  4. Explain why the invariant plus the stopping condition gives the required answer.

For an array sum, the invariant is that total equals the sum of the visited prefix. Initially that prefix is empty and total is zero. Each step includes exactly one new value. Once all values have been visited, total is the required answer. Tests can catch mistakes in that reasoning, but a few successful examples do not establish the general claim.

Choosing a structure or technique

Start from the required operations and constraints, then choose the simplest structure that supports them. The same problem can admit several good solutions; sorted input, update frequency, output size and memory limits often decide between them.

NeedStarting pointMain condition or cost
Indexed access and sequential scansArray or dynamic arrayMiddle insertions move elements
Fast membership and countsHash set or mapExpected performance; no sorted-order guarantee
Ordered keys and range queriesBalanced search treeMaintain balance for logarithmic height
Repeatedly remove the minimumMin-heapRemoval is logarithmic; arbitrary lookup is not fast
Word prefixesTrieCharacter policy and node overhead matter
Incremental connectivityUnion-findOrdinary form does not support arbitrary deletions
Fewest edges from a sourceBFSUnweighted or equal-cost edges
Minimum nonnegative path costDijkstraNegative edges invalidate the proof
Many static interval sumsPrefix sumsUpdates can invalidate a whole suffix
Overlapping optimization subproblemsDynamic programmingDefine state, recurrence and dependency order

Binary representation & bit manipulation

Bits, bytes & number formats

A bit has two possible values, 0 and 1. A byte in these examples contains eight bits, so it has 2⁸ = 256 possible patterns. Binary is base two: position i, counted from zero at the right, contributes 2ⁱ when its bit is set. The least significant bit is on the right; the most significant displayed bit is on the left.

Bit position76543210
Place value1286432168421
Bits of decimal 1300001101

Hexadecimal is base sixteen. Its digits 0 through 9 and A through F represent values zero through fifteen. One hexadecimal digit corresponds to four bits, called a nibble: binary 1101 is hexadecimal D. Thus binary 00001101, hexadecimal 0D and decimal 13 are equivalent. Prefixes and literal syntax vary by language; a displayed base does not change the stored value.

Unsigned values and two’s complement

An unsigned w-bit integer represents 0 through 2ʷ − 1. A signed w-bit two’s-complement integer represents −2ʷ⁻¹ through 2ʷ⁻¹ − 1. In the signed interpretation, the top bit has weight −2ʷ⁻¹; other positions keep positive weights. For eight bits, 11111011 is −128 + 64 + 32 + 16 + 8 + 2 + 1 = −5. The same pattern interpreted as unsigned is 251.

To encode a negative value in two’s complement, invert the positive magnitude within the chosen width and add one. Discard any carry beyond that width. This is modular arithmetic, not permission to overflow a signed language type: use unsigned or explicitly wrapping operations where required. Width is part of the interpretation; 11111011 alone does not identify a signed value without that agreement.

Endianness: ordering bytes

A multibyte format must specify which byte is stored first. For the 16-bit value hexadecimal 1234, big-endian order stores bytes 12 then 34; little-endian order stores 34 then 12. This does not reverse the bits within each byte or alter the numeric value. Use explicit byte-order APIs for files and network messages instead of assuming that host memory order matches the format.

Bitwise operations are not logical conditions

AND, OR and XOR operate on corresponding bits. Logical conjunction and disjunction instead combine conditions and may short-circuit. Operator symbols differ across languages, and precedence can be surprising: parenthesize mask expressions before comparing them with zero. NOT flips bits within a defined width; it does not simply turn a nonzero integer into zero.

ABANDORXORNOT A
000001
010111
100110
111100

Floating-point representation is different

Integers and floating-point numbers interpret bits differently. IEEE 754 binary32 uses one sign bit, eight exponent bits and 23 fraction bits; binary64 uses one, eleven and 52 respectively. Normal finite values also have an implicit leading significant bit. Fractions such as decimal 0.1 have no finite binary expansion, so rounding is expected. Changing an integer’s bit pattern is not the same as numerically converting a floating-point value.

JavaScript and TypeScript normally use binary64 Number values, but Number bitwise operations coerce them to 32-bit integers. Python integers grow as needed; a fixed-width complement requires a mask. Java and C# distinguish arithmetic and logical right shifts through operators or operand types. Rust, Go and Ada provide explicit fixed-width or modular types. Always establish the language’s width, signedness and shift rules before generalizing a bit trick.

Encoding and decoding binary integers

A numeral is a representation of a value, not a different value: decimal 13, binary 00001101 and hexadecimal 0D all denote the same integer. Leading zeroes make the chosen width visible. These examples model an eight-bit byte explicitly, independently of the language’s default integer size.

How it works & invariant

To print eight bits, inspect positions 7 down to 0. Shift the desired position into the lowest bit and mask with 1. To decode a binary string, repeatedly multiply the accumulated value by two and add the next digit; parsing APIs perform the same positional conversion. Encode −5 modulo 256 as 251, then interpret values at least 128 by subtracting 256.

Step-by-step trace

The set bits of 00001101 contribute 8 + 4 + 1 = 13. For −5, start from positive 5 = 00000101, invert the eight bits to 11111010 and add one to obtain 11111011. Read as unsigned, that pattern is 251; read as signed two’s complement, it is 251 − 256 = −5. The program prints both interpretations without shifting a negative operand.

Complete worked example

python
def binary8(value):
    return ''.join(str((value >> i) & 1) for i in range(7, -1, -1))

bits = binary8(13)
print(bits)          # 00001101
print(int(bits, 2))  # 13
encoded = (256 - 5) & 255
print(binary8(encoded)) # 11111011
print(encoded - 256 if encoded >= 128 else encoded) # -5

Expected output

plaintext
00001101
13
11111011
-5

Time & space complexity

Printing or parsing w binary digits takes O(w) time and O(w) output storage. These fixtures fix w = 8. Formatting a byte does not allocate or change the underlying integer’s native storage width.

When to use it

Useful for understanding file formats, protocol fields, debugger displays and numeric conversions. Always distinguish the numeric value, the displayed base and the signed interpretation of a fixed-width bit pattern.

Trade-offs & edge cases

The fixtures accept unsigned byte values from 0 through 255. Two’s-complement signed interpretation covers −128 through 127. Do not infer byte order from the displayed numeral: endianness determines the order of bytes in a multibyte encoding, not the left-to-right significance of this string.

AND, OR, XOR, NOT & shifts

Bitwise operators act independently at corresponding bit positions. AND keeps a bit only when both inputs contain it; OR keeps it when either does; XOR keeps it when exactly one does; NOT flips it. Shifts move positions left or right and require an explicit width and signedness policy.

How it works & invariant

Use a = 12 = 00001100 and b = 10 = 00001010. Apply each operator, restricting complement and left-shift results to eight bits where the language uses wider integers. A logical right shift introduces zeroes; an arithmetic right shift propagates the sign bit. The example deliberately uses unsigned or nonnegative operands so the result is consistent in every language.

Step-by-step trace

AND gives 00001000 = 8; OR gives 00001110 = 14; XOR gives 00000110 = 6. The eight-bit complement of a is 11110011 = 243. Shifting a left once yields 00011000 = 24; shifting it logically right once yields 00000110 = 6. Bits shifted beyond the byte are discarded when the result is masked.

Complete worked example

python
a, b, mask = 12, 10, 255
print(a & b)         # 8
print(a | b)         # 14
print(a ^ b)         # 6
print((~a) & mask)   # 243; Python alone would give ~12 == -13.
print((a << 1) & mask) # 24
print(a >> 1)        # 6; nonnegative input, so zero bits enter from the left.

Expected output

plaintext
8
14
6
243
24
6

Time & space complexity

Fixed-width machine-word operations are modeled as O(1) time and space. Arbitrary-precision integers can require work proportional to their stored words; a single bitwise expression is not automatically O(1) for an unbounded integer.

When to use it

Useful for extracting packed fields, combining masks and manipulating compact state. Left shift by k corresponds to multiplication by 2ᵏ only when discarded bits and overflow do not alter the result; logical right shift of an unsigned value corresponds to floor division by 2ᵏ.

Trade-offs & edge cases

Python integers are unbounded and ~12 equals −13, so mask with 255 for an eight-bit complement. JavaScript and TypeScript Number bitwise operators coerce to 32 bits; >>> is zero-filling, and BigInt has no >>> operator. C/C++ examples use unsigned operands to avoid signed overflow and negative-shift pitfalls. Keep shift counts within the operand’s valid bit-width range.

Bit masks, flags & packed fields

A mask identifies bit positions with ones. Assign independent flags distinct powers of two so each occupies one position. In the example, READ = 1, WRITE = 2 and EXECUTE = 4. A single integer can then store any combination of the three flags.

How it works & invariant

Set selected bits with OR, clear them with AND against the complemented mask, and toggle them with XOR. Test any required bit using a nonzero AND result. To require all bits in a combined mask, compare the AND result with that mask itself. Parentheses make the intended grouping explicit across languages with different operator precedence.

Step-by-step trace

READ | WRITE starts at 3 = 011. Testing READ succeeds. Setting EXECUTE gives 7 = 111; clearing WRITE gives 5 = 101; toggling READ gives 4 = 100. Requiring both READ and EXECUTE now fails: 100 AND 101 is 100, not the required 101. The program prints 3, 1, 7, 5, 4 and 0.

Complete worked example

python
READ, WRITE, EXECUTE = 1 << 0, 1 << 1, 1 << 2
flags = READ | WRITE
print(flags) # 3
print(int((flags & READ) != 0)) # 1
flags |= EXECUTE
print(flags) # 7
flags &= ~WRITE
print(flags) # 5
flags ^= READ
print(flags) # 4
required = READ | EXECUTE
print(int((flags & required) == required)) # 0: require all bits

Expected output

plaintext
3
1
7
5
4
0

Time & space complexity

A fixed-width mask update or membership test takes O(1) time and space. Storing n independent flags needs n bits; once they span multiple machine words, operations over the full set scale with the number of words.

When to use it

Use for permission-like flags, feature sets, compact visited-state sets and protocol fields. To extract a field of width k starting at bit p, logically shift right by p, then AND with a k-bit mask. Validate field widths and reserved bits before accepting external data.

Trade-offs & edge cases

ANY and ALL are different predicates. Testing ALL bits of an empty mask succeeds mathematically, while testing ANY bit of it fails. Reusing a bit for two independent flags makes them indistinguishable. Masks represent state; actual authorization still requires the application’s authoritative checks.

Counting bits & recognizing powers of two

Several useful algorithms follow from the shape of binary subtraction. For a nonzero integer x, x − 1 clears its lowest one and fills all lower positions with ones. Therefore x AND (x − 1) removes exactly the lowest set bit. Repeating that step counts the number of ones, also called population count.

How it works & invariant

Kernighan’s counting loop increments once per removed bit. A positive power of two has exactly one set bit, so x > 0 and x AND (x − 1) = 0 recognize it. In two’s-complement or modular arithmetic, x AND (−x) isolates the lowest set bit. C/C++ use defined unsigned subtraction and Rust uses wrapping_neg rather than an overflowing signed negation.

Step-by-step trace

Start with 44 = 00101100. Removing the lowest set bit gives 40 = 00101000, then 32 = 00100000, then 0: three iterations. The isolated lowest bit is 4 = 00000100. Zero is not a power of two; 16 is; 18 is not. The program prints 3, 4, 0, 1 and 0.

Complete worked example

python
def popcount(value):
    # Require nonnegative integers. Negative Python integers would not terminate.
    count = 0
    while value:
        value &= value - 1
        count += 1
    return count

def is_power_of_two(value):
    return value > 0 and (value & (value - 1)) == 0

value = 44
print(popcount(value)) # 3
print(value & -value)  # 4
for n in [0, 16, 18]:
    print(int(is_power_of_two(n))) # 0, 1, 0

Expected output

plaintext
3
4
0
1
0

Time & space complexity

The counting loop takes O(k) fixed-width operations for k set bits, at most O(w) for a w-bit word, and O(1) auxiliary space. The power-of-two and lowest-bit expressions use O(1) word operations. Arbitrary-precision arithmetic adds a cost per operation based on integer size.

When to use it

Useful for compact subset states, occupancy maps, alignment checks and iterating selected positions. Standard libraries often provide population-count operations; understanding the invariant helps verify fallback implementations and boundary behavior.

Trade-offs & edge cases

These examples use nonnegative values in 0..255. A negative Python integer makes the clearing loop fail to terminate because of its unbounded signed interpretation. Always reject or mask such input. Check zero before subtracting in unsigned types that trap on underflow; logical short-circuiting protects the power-of-two test.

Data structures

Arrays & dynamic arrays

An array stores elements in an indexed sequence. Its address arithmetic makes indexed access constant time. A dynamic array adds capacity management: when full, it allocates a larger buffer and copies existing elements. Python lists, JavaScript arrays, C++ vectors and Rust Vec serve this role, although their element representation differs.

How it works & invariant

The example scans [4, 2, 7, 1], maintaining a running total. Before each iteration, total equals the sum of the elements already visited. Adding the next element preserves that invariant. Reading index 2 jumps directly to the third element instead of repeating the scan. Separate logical length from allocated capacity when implementing a dynamic array.

Array / dynamic array

Indices run left to right. Middle insertion shifts a suffix right; deletion shifts it left. Dynamic-array growth may also copy all elements.

Insert40Current focusIncoming node
Incoming10Index 020Index 130Index 240
Step 1 of 5
Step 1 of 5

Insert 40 at index 1. Elements to its right must move first.

Step-by-step trace

Initially total = 0. After visiting 4, 2, 7 and 1, the totals are 4, 6, 13 and 14. Index 2 contains 7 because these examples use zero-based numeric indices. Ada explicitly declares zero-based ranges here; native Ada arrays can use other bounds.

Complete worked example

python
values = [4, 2, 7, 1]
total = 0
for value in values:
    total += value
print(total)      # 14
print(values[2])  # 7: direct indexed access

Expected output

plaintext
14
7

Time & space complexity

Index lookup: O(1). Full scan: O(n) time and O(1) auxiliary space. Middle insertion or deletion: O(n). Dynamic-array append: amortized O(1), but a resizing append can take O(n).

When to use it

Prefer arrays for sequential processing, indexed access and cache-friendly storage. Measure before replacing them with linked structures: fewer theoretical pointer changes do not guarantee faster real execution.

Trade-offs & edge cases

Check bounds, empty input and numeric overflow. These small integer fixtures fit every demonstrated numeric type. JavaScript Number represents integers exactly only through its safe-integer range; use BigInt or appropriate wider types when the domain requires them.

Linked lists & ownership

A singly linked list stores a value and a link to the next node. Nodes need not occupy adjacent memory. The head identifies the first node; a null link or sentinel marks the end. Prepending changes the head without moving existing values.

How it works & invariant

Start with 3 → 5. Create a node containing 1 whose next link points to the old head, then make it the new head. Traversal follows one link at a time and accumulates 1 + 3 + 5. In C the list owns allocated nodes and frees them after use; C++ and Rust use owning smart pointers. Ada demonstrates links as indices into a bounded arena.

Singly linked list

Arrows are next pointers. Appending updates the old tail; deletion reconnects the predecessor to the successor.

Insert40Current focusIncoming node
Incoming➤➤10203040
Step 1 of 5
Step 1 of 5

Append 40. Start at head 10 and find the tail.

Current focus: 10

Step-by-step trace

Before prepend: head → 3 → 5 → end. After prepend: head → 1 → 3 → 5 → end. The original two nodes keep their positions. The traversal cursor visits three nodes and prints 9. A cursor borrows access; it does not become a second owner of the chain.

Complete worked example

python
class Node:
    def __init__(self, value, next_node=None):
        self.value = value
        self.next = next_node

head = Node(3, Node(5))
head = Node(1, head)  # O(1) prepend
total = 0
node = head
while node is not None:
    total += node.value
    node = node.next
print(total)  # 9: 1 -> 3 -> 5

Expected output

plaintext
9

Time & space complexity

Prepend: O(1). Search or access by position: O(n). Insertion after a known node: O(1); finding that node may take O(n). Storage: O(n), including links. Traversal uses O(1) auxiliary space.

When to use it

Useful when nodes must be relinked frequently and a position is already known. A doubly linked list adds a previous link for reverse traversal and removal of a known node.

Trade-offs & edge cases

Extra allocations, links and poor locality often outweigh constant-time relinking. Cycles cause an unguarded traversal to loop forever. Very deep smart-pointer chains can also overflow the call stack during recursive destruction; production ownership and cleanup need to match expected depth.

Stacks, queues & deques

A stack is last in, first out (LIFO): the newest value leaves first. A queue is first in, first out (FIFO): the oldest value leaves first. A deque supports both ends. These are behavioral contracts, not a requirement to use any particular storage layout.

How it works & invariant

Push 10 then 20 onto the stack and pop to obtain 20. Enqueue the same values and dequeue to obtain 10. Python uses deque, Rust uses VecDeque, and the managed languages use standard queues. The array-based JavaScript and Go examples advance a head index; C and Ada illustrate a fixed-capacity ring buffer.

Stack

The stack grows from bottom to top. Push adds at the top; pop removes from the top. The last element added is the first removed.

Insert40Current focusIncoming node
Bottom← TopIncoming10203040
Step 1 of 3
Step 1 of 3

The new element 40 is waiting outside the structure.

Queue

Enqueue on the left, dequeue on the right. The first element added is the first removed. This shows logical order, independently of storage layout.

Insert40Current focusIncoming node
Enqueue →Dequeue →RearFrontIncoming10203040
Step 1 of 3
Step 1 of 3

The new element 40 is waiting outside the structure.

Deque

Both ends support insertion and removal. The animations demonstrate adding and removing at each end.

Insert40, 5Current focusIncoming node
Incoming102030405
Step 1 of 5
Step 1 of 5

A deque supports both ends. First append 40 on the right.

Step-by-step trace

Stack bottom [10, 20] top becomes [10] after pop. Queue front [10, 20] back becomes [20] after dequeue. In a ring buffer, the next insertion slot is (head + count) modulo capacity; advancing head reuses slots without shifting all remaining values.

Complete worked example

python
from collections import deque

stack = []
stack.append(10)
stack.append(20)
print(stack.pop())  # 20: LIFO

queue = deque([10, 20])
print(queue.popleft())  # 10: FIFO; no shifting an entire list

Expected output

plaintext
20
10

Time & space complexity

Typical push/pop and enqueue/dequeue: O(1) amortized with suitable containers. A fixed-capacity ring buffer has O(1) operations without resizing. Storage: O(n). Removing index zero from a contiguous dynamic array usually costs O(n).

When to use it

Use stacks for undo, parsing and explicit DFS. Use queues for BFS and work scheduling. Use a deque when both ends matter, such as monotonic-window algorithms.

Trade-offs & edge cases

Handle empty removal and full bounded buffers explicitly. A growing head-index queue retains consumed storage until compacted or discarded; it is a teaching implementation rather than an indefinitely reusable queue. The ring-buffer fixtures never exceed their declared capacity.

Hash maps & sets

A hash map associates keys with values; a set records membership without a separate value. A hash function routes a key to a bucket. Different keys can collide, so a correct implementation must compare keys and resolve collisions rather than treating the hash as a unique identity.

How it works & invariant

Count each integer in [2, 3, 2, 4, 3, 2], treating a missing count as zero. The final mapping is 2 → 3, 3 → 2, 4 → 1; its key set has size 3. C and Ada show linear probing: advance to the next slot until finding the key or an empty slot. Their fixed tables deliberately remain below capacity.

Hash map / set

For this illustration, hash(key) = key modulo 3. Arrows show a collision chain; maps also associate a value with each key. Traversal order is not a sorted-order guarantee.

Insert4, 7Current focusIncoming node
Incomingbucket 0bucket 1bucket 247
Step 1 of 6
Step 1 of 6

Insert key 4 first. Compute 4 modulo 3 = 1.

Step-by-step trace

Processing the first 2 creates count 1; the second 2 changes it to 2; the final 2 changes it to 3. Duplicate insertions do not increase the number of distinct keys. The program prints the count for key 2, followed by the set cardinality: 3 and 3.

Complete worked example

python
counts = {}
values = [2, 3, 2, 4, 3, 2]
for value in values:
    counts[value] = counts.get(value, 0) + 1
print(counts[2])         # 3 occurrences
print(len(set(values))) # 3 distinct values

Expected output

plaintext
3
3

Time & space complexity

Typical expected lookup/insertion: O(1) with a well-distributed hash and controlled load factor. Worst-case lookup can be O(n), depending on collision strategy and implementation. Building counts: expected O(n) time and O(k) space for k distinct keys.

When to use it

Use maps for frequency counts, caches and key-based joins. Use sets for deduplication and visited-state tracking. Choose ordered trees instead when sorted traversal or range queries are essential.

Trade-offs & edge cases

Hash keys must have compatible equality and hash behavior and should not mutate while stored. Table iteration order is not generally sorted. A production probing table needs resizing, full-table detection and deletion markers; those operations are outside this insert-only bounded fixture.

Binary search trees

A binary search tree (BST) maintains smaller keys in each node’s left subtree and larger keys in its right subtree. That ordering applies recursively to entire subtrees, not just immediate children. This example represents a set and ignores duplicate insertions.

How it works & invariant

Insert 4 as the root, 2 on its left, 6 on its right, then 1 and 3 below 2. Inorder traversal recursively visits the left subtree, the node and the right subtree. Because the ordering invariant holds, that traversal emits keys in ascending order. The program implements an ordinary unbalanced BST, not a balanced library tree.

Binary search tree

Smaller keys are left, larger keys are right. Inorder traversal visits sorted keys. Deletion demonstrates two children, one child and a leaf.

Insert2Current focusIncoming node
Incoming➤➤41623
Step 1 of 9
Step 1 of 9

Start with 1, 4 and 6: root 4 has left child 1 and right child 6. Insert 2 first.

flowchart TD
    R[4] -->|smaller| L[2]
    R -->|larger| S[6]
    L -->|smaller| A[1]
    L -->|larger| B[3]

Step-by-step trace

Inserting 3 compares with 4, goes left to 2, then right to an empty link. Inorder traversal visits 1, 2, 3, 4, 6. A search for 5 would compare with 4, move right to 6, then left to an empty link and report absence.

Complete worked example

python
class Node:
    def __init__(self, value):
        self.value = value
        self.left = self.right = None

def insert(root, value):
    if root is None:
        return Node(value)
    if value < root.value:
        root.left = insert(root.left, value)
    elif value > root.value:
        root.right = insert(root.right, value)
    return root  # Ignore duplicates.

def inorder(root, result):
    if root is not None:
        inorder(root.left, result)
        result.append(root.value)
        inorder(root.right, result)

root = None
for value in [4, 2, 6, 1, 3]:
    root = insert(root, value)
result = []
inorder(root, result)
print(*result)  # 1 2 3 4 6

Expected output

plaintext
1 2 3 4 6

Time & space complexity

Lookup/insertion: O(h) for height h. Balanced trees keep h = O(log n); an unbalanced tree can have h = n. Inorder traversal: O(n) time and O(h) recursion space. Building this unbalanced tree can take O(n²) for sorted insertions.

When to use it

Use ordered trees for predecessor/successor operations, sorted iteration and range queries. Prefer a standard balanced tree when adversarial or sorted inputs are possible.

Trade-offs & edge cases

A plain BST does not guarantee logarithmic operations. Duplicates need an explicit policy: reject them, store a count or define a secondary ordering. Deep recursion can exhaust the call stack; test increasing and decreasing insertion orders.

Binary heaps & priority queues

A min-heap guarantees that a parent is no greater than its children, so the root is the minimum. It does not fully sort the array. A priority queue exposes the behavior of inserting work and removing the highest-priority item; a binary heap is a common implementation.

How it works & invariant

Insert 5, 1, 4 and 2. A newly inserted element moves upward while smaller than its parent. To remove the minimum, move the last element to the root and move it downward toward the smaller child until the invariant is restored. Zero-based children are 2i + 1 and 2i + 2; the parent is floor((i − 1) / 2).

Min-heap / priority queue

Parents are no larger than children. Insertion sifts up; removing the minimum replaces the root with the last leaf and sifts down. Level-order traversal is not sorted.

Insert1Current focusIncoming node
Incoming➤➤2581
Step 1 of 7
Step 1 of 7

Initial min-heap

Step-by-step trace

One valid sequence of heap arrays is [5], [1, 5], [1, 5, 4], [1, 2, 4, 5]. Removing 1 replaces it with 5 and sifts down to [2, 5, 4]. The next removal returns 2. Both values are printed on separate lines.

Complete worked example

python
# heapq implements a binary min-heap in a Python list.
import heapq

heap = []
for value in [5, 1, 4, 2]:
    heapq.heappush(heap, value)
print(heapq.heappop(heap))  # 1
print(heapq.heappop(heap))  # 2
# Check that the heap is nonempty before popping in caller-facing code.

Expected output

plaintext
1
2

Time & space complexity

Peek minimum: O(1). Insert/remove minimum: O(log n) worst-case heap work, plus possible container resizing. Bottom-up heap construction: O(n); inserting n items individually: O(n log n). Storage: O(n).

When to use it

Use heaps for scheduling, top-k selection and priority-driven graph algorithms. C++ priority_queue and Rust BinaryHeap default to maximum-first ordering, so these examples explicitly reverse that order.

Trade-offs & edge cases

Equal-priority items are not necessarily removed in insertion order; include a sequence number when stable ordering matters. Check empty removal. C# implements a heap manually for compatibility with the sandbox’s older Mono runtime; Go implements the container/heap adapter methods.

Tries & prefix lookup

A trie stores keys along paths of characters. Shared prefixes share nodes: cat and car follow the same c → a path before branching. A terminal marker distinguishes a complete stored word from a path that exists only as a prefix.

How it works & invariant

Insert cat and car, creating missing children and marking each final node as terminal. Exact lookup follows the characters and checks the terminal marker at the end. Prefix lookup would instead succeed as soon as the complete prefix path is found, regardless of that marker. Each language implements the same ASCII-word fixture.

Trie

Each edge advances one character. The star marks a complete word. Deleting a word preserves nodes needed by other words.

Insertt*Current focusIncoming node
Incoming➤➤➤rootcar*t*
Step 1 of 5
Step 1 of 5

Insert cat into a trie that already contains car. Start at root.

Current focus: root
flowchart LR
    R[root] --> C[c]
    C --> A[a: prefix only]
    A --> T[t: terminal]
    A --> S[r: terminal]

Step-by-step trace

After both inserts, the a node has t and r children. Looking up cat reaches a terminal t node and prints 1. Looking up ca reaches an existing but nonterminal a node and prints 0. An empty word would be represented by marking the root terminal.

Complete worked example

python
class Node:
    def __init__(self):
        self.children = {}
        self.terminal = False

root = Node()

def insert(word):
    node = root
    for letter in word:
        if letter not in node.children:
            node.children[letter] = Node()
        node = node.children[letter]
    node.terminal = True

def contains(word):
    node = root
    for letter in word:
        if letter not in node.children:
            return False
        node = node.children[letter]
    return node.terminal

insert('cat')
insert('car')
print(int(contains('cat'))) # 1
print(int(contains('ca')))  # 0: prefix only

Expected output

plaintext
1
0

Time & space complexity

Lookup/insertion: O(L) for word length L with fixed-alphabet arrays or expected O(1) child maps. Ordered child maps add a log(alphabet size) factor. Space is proportional to distinct prefix nodes, plus child-container overhead.

When to use it

Useful for autocomplete, dictionary prefixes and routing by structured keys. To list completions, first locate the prefix node, then traverse its descendants, collecting terminal words.

Trade-offs & edge cases

Sparse maps save empty slots; fixed child arrays offer predictable indexing but can waste memory. C, C#, Java and Ada deliberately restrict the example to lowercase ASCII; C and Ada also bound node capacity. Unicode code units, code points, normalization and case folding require a deliberate key policy.

Disjoint sets: union-find

Union-find maintains a partition of elements into disjoint groups. Each element points toward a representative root. Find returns that root; union merges two groups. It answers connectivity questions without storing the full path or adjacency structure that connected the elements.

How it works & invariant

Initially every element from 0 through 4 is its own root. Merge 0 with 1, then 1 with 2. Union by size attaches the smaller root beneath the larger. Find uses path halving: redirect a visited node to its grandparent, progressively shortening future searches. Only root sizes are authoritative.

Disjoint sets / union-find

Arrows point to parents. Union merges sets; find follows parents to a representative. Ordinary union-find does not support arbitrary deletion.

UnionCurrent focus
Focus—123
Step 1 of 7
Step 1 of 7

Start with three singleton sets. Each node is its own representative.

Step-by-step trace

After the two unions, 0, 1 and 2 share a representative, while 3 and 4 remain separate. Comparing find(0) with find(2) prints 1; comparing find(0) with find(4) prints 0. Repeating a union within the same group must leave its size unchanged.

Complete worked example

python
parent = list(range(5))
size = [1] * 5

def find(x):
    while x != parent[x]:
        parent[x] = parent[parent[x]]  # Path halving
        x = parent[x]
    return x

def unite(a, b):
    a, b = find(a), find(b)
    if a == b:
        return
    if size[a] < size[b]:
        a, b = b, a
    parent[b] = a
    size[a] += size[b]

unite(0, 1)
unite(1, 2)
print(int(find(0) == find(2))) # 1
print(int(find(0) == find(4))) # 0

Expected output

plaintext
1
0

Time & space complexity

Initialization: O(n) time and space. Union by size with path compression gives O(α(n)) amortized time per operation, where α is the inverse Ackermann function. It grows extremely slowly but is not literally a constant.

When to use it

Use for incremental undirected connectivity, component grouping and Kruskal’s minimum spanning tree algorithm. To detect an undirected cycle, an edge whose endpoints already share a root closes a cycle.

Trade-offs & edge cases

Ordinary union-find cannot undo arbitrary deletions or recover a connecting path. Path compression mutates state even during find; account for that in concurrent or persistent designs. Vertex IDs must be valid array indices.

Searching, sorting & graphs

Binary search repeatedly discards half of an ordered search space. This lower-bound variant returns the first position whose value is at least the target. If no such value exists it returns the array length, which is a valid insertion position but not a readable element index.

How it works & invariant

Maintain a half-open interval [lo, hi). Everything before lo is smaller than the target; everything at or after hi is at least the target. If values[mid] is too small, set lo = mid + 1. Otherwise set hi = mid. The interval strictly shrinks until lo equals hi. Use lo + (hi − lo) / 2 to avoid adding two potentially large bounds.

Binary search: lower bound

Watch lo, hi and mid narrow a half-open interval. Equal values move hi left so the first duplicate is found.

Find first duplicateCurrent focus
Focus—1Index 0lo3Index 13Index 27Index 39Index 4
Target3
Search interval [lo, hi)[0, 5)
Step 1 of 8
Step 1 of 8

Search for the first value at least 3. Start with the full half-open interval.

Step-by-step trace

For [1, 3, 3, 7, 9] and target 3: [0,5) checks index 2, narrows to [0,2), checks 1, narrows to [0,1), then checks 0 and returns 1. Target 10 returns 5. An empty array immediately returns 0.

Complete worked example

python
def lower_bound(values, target):
    lo, hi = 0, len(values)  # Half-open interval [lo, hi)
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if values[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo

values = [1, 3, 3, 7, 9]
print(lower_bound(values, 3))  # 1: first duplicate
print(lower_bound(values, 10)) # 5: insertion after the end

Expected output

plaintext
1
5

Time & space complexity

O(log n) comparisons and O(1) auxiliary space on an indexed sequence. Sorting unsorted input first costs extra, typically O(n log n). Linked-list midpoint access does not have the same constant-time indexing advantage.

When to use it

Use for sorted lookup, insertion positions and monotone feasibility predicates such as the smallest capacity that meets a deadline. To test exact membership after lower bound, first check that the returned position is within bounds.

Trade-offs & edge cases

The data or predicate must be monotone. Returning immediately on equality does not guarantee the first duplicate. Test empty, singleton, repeated, below-minimum and above-maximum targets; off-by-one errors often appear at those boundaries.

Sorting & divide-and-conquer

Merge sort divides a sequence into two smaller sequences, sorts each recursively, then merges them. The base case is a sequence of length zero or one. Divide-and-conquer works because each subproblem can be solved independently before their results are combined.

How it works & invariant

During merge, compare the next unused item from each sorted half and take the smaller. Taking the left item on equality preserves the original relative order of equal keys: stability. Some examples return fresh arrays; others use one reusable buffer and half-open index ranges. They implement the same stable merge operation.

Stable merge sort

Rows separate the two sorted inputs from the merge result. Identity labels distinguish equal elements.

Split and mergeCurrent focus
Focus—5#11#24#31#43#5
Merged values∅
Step 1 of 34
Step 1 of 34

Split the array into smaller runs until each run has one element.

Step-by-step trace

Split [5,1,4,1,3] into [5,1] and [4,1,3]. Recursive results are [1,5] and [1,3,4]. Merge chooses left 1, right 1, then 3, 4 and 5, printing 1 1 3 4 5. Every merge step consumes exactly one element from a half.

Complete worked example

python
def merge_sort(values):
    if len(values) < 2:
        return values[:]
    middle = len(values) // 2
    left = merge_sort(values[:middle])
    right = merge_sort(values[middle:])
    result = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]: # Left first on a tie: stable.
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    return result + left[i:] + right[j:]

print(*merge_sort([5, 1, 4, 1, 3])) # 1 1 3 4 5

Expected output

plaintext
1 1 3 4 5

Time & space complexity

Merge sort: O(n log n) time in best and worst cases, O(n) peak auxiliary storage plus O(log n) recursion. Allocation-heavy variants create O(n log n) total copied elements across levels, even though peak live storage is O(n).

When to use it

Use stable sorting when secondary ordering must survive, such as sorting previously name-ordered records by department. Insertion sort is simple and adaptive for tiny or nearly sorted sequences; quicksort is often fast in place but its pivot strategy matters.

Trade-offs & edge cases

Insertion sort has O(n²) worst-case time; conventional quicksort has expected O(n log n) but O(n²) worst-case time and is usually unstable; heapsort guarantees O(n log n) with O(1) array auxiliary space but is unstable. Library sort guarantees differ by language: consult the chosen API before relying on stability.

Graphs, BFS & DFS

A graph models vertices connected by edges. Adjacency lists store each vertex’s outgoing neighbors. Breadth-first search (BFS) explores by distance in number of edges; depth-first search (DFS) follows a branch before returning to alternatives. A visited set prevents repeated processing and infinite loops on cycles.

How it works & invariant

The directed graph has edges 0 → 1, 0 → 2, 1 → 3 and 2 → 3. BFS marks a vertex when enqueuing it, so 3 enters the queue only once. Recursive DFS marks on entry and processes neighbors in their listed order. These programs start from 0; they do not automatically traverse disconnected components.

Compare recursive and iterative DFS traversals and iterative BFS on the same binary tree. Index 0 represents an empty child; every other index is the node value. Each animation shows its corresponding complete program in the selected language.

Directed graph

Arrows represent directed edges. BFS marks vertices when enqueued. Removing a vertex also removes all incident edges.

InsertCCurrent focusIncoming node
Incoming➤ABC
Step 1 of 5
Step 1 of 5

Add vertex C to a graph with edge A to B.

Corresponding algorithm (pseudocode)
plaintext
Adjacency list: graph[vertex] contains its outgoing neighbors.

ADD_VERTEX(v): graph[v] = empty list
ADD_EDGE(from, destination): append destination to graph[from]
TRAVERSE(source): BFS(source) using a visited set
REMOVE_VERTEX(v):
    remove v from every neighbor list
    delete graph[v]
Depth-first search

DFS follows a branch before backtracking. The call stack and visited output make returns and skipped neighbors visible.

Explore depth firstCurrent focus
Focus—➤➤➤➤0123
Visited output∅
Call stack: top on the right∅
Discovered vertices∅
Step 1 of 15
Step 1 of 15

Start DFS from 0 with an empty visited set and call stack.

Corresponding algorithm (pseudocode)
plaintext
DFS(vertex):
    if vertex in seen: return
    add vertex to seen
    visit(vertex)
    for next in graph[vertex]:
        DFS(next)

seen = empty set
DFS(0)
Graph breadth-first search

A FIFO queue explores by distance from the source. Mark on enqueue so shared neighbors and cycles cannot duplicate work.

Explore breadth firstCurrent focus
Focus—➤➤➤➤0123
Visited output∅
Work queue: next on the left0
Discovered vertices0
Step 1 of 14
Step 1 of 14

Mark source 0 discovered and enqueue it before beginning BFS.

Corresponding algorithm (pseudocode)
plaintext
BFS(source):
    seen = {source}
    queue = FIFO([source])
    while queue is not empty:
        vertex = queue.dequeue()
        visit(vertex)
        for next in graph[vertex]:
            if next not in seen:
                add next to seen
                queue.enqueue(next)

BFS(0)
Binary tree: pre-order DFS

Visit root, then left subtree, then right subtree. The explicit stack schedules tasks in reverse order.

RecursiveCurrent focus
Focus—➤➤➤➤➤➤4261357
Visited output∅
Call stack: top on the right∅
Step 1 of 23
Step 1 of 23

Use the same binary tree: root 4, children 2 and 6, and leaves 1, 3, 5 and 7.

python
left = [0, 0, 1, 0, 2, 0, 5, 0]
right = [0, 0, 3, 0, 6, 0, 7, 0]
output = []

def traverse(node):
    if node == 0:
        return
    output.append(node)
    traverse(left[node])
    traverse(right[node])

traverse(4)
print(*output)

Expected output: 4 2 1 3 6 5 7

Tree traversals take O(n) time. DFS uses O(h) call or explicit stack space. Iterative BFS uses O(w) live queue space; array queues with a head index retain O(n) storage. Here h is tree height and w is maximum width. Output storage is counted separately.

These examples assume a proper tree: no cycles and no shared children. In-order is sorted only for a binary search tree. Deep trees may exceed the recursion limit; prefer an iterative traversal when depth is unbounded. Bounded C, C++ and Ada buffers fit this fixture and must be resized for larger trees.

Binary tree: in-order DFS

Visit left subtree, then root, then right subtree. Sorted output requires the binary-search-tree ordering invariant.

RecursiveCurrent focus
Focus—➤➤➤➤➤➤4261357
Visited output∅
Call stack: top on the right∅
Step 1 of 23
Step 1 of 23

Use the same binary tree: root 4, children 2 and 6, and leaves 1, 3, 5 and 7.

python
left = [0, 0, 1, 0, 2, 0, 5, 0]
right = [0, 0, 3, 0, 6, 0, 7, 0]
output = []

def traverse(node):
    if node == 0:
        return
    traverse(left[node])
    output.append(node)
    traverse(right[node])

traverse(4)
print(*output)

Expected output: 1 2 3 4 5 6 7

Tree traversals take O(n) time. DFS uses O(h) call or explicit stack space. Iterative BFS uses O(w) live queue space; array queues with a head index retain O(n) storage. Here h is tree height and w is maximum width. Output storage is counted separately.

These examples assume a proper tree: no cycles and no shared children. In-order is sorted only for a binary search tree. Deep trees may exceed the recursion limit; prefer an iterative traversal when depth is unbounded. Bounded C, C++ and Ada buffers fit this fixture and must be resized for larger trees.

Binary tree: post-order DFS

Visit left subtree, then right subtree, then root. Deferred visit tasks keep the parent after both children.

RecursiveCurrent focus
Focus—➤➤➤➤➤➤4261357
Visited output∅
Call stack: top on the right∅
Step 1 of 23
Step 1 of 23

Use the same binary tree: root 4, children 2 and 6, and leaves 1, 3, 5 and 7.

python
left = [0, 0, 1, 0, 2, 0, 5, 0]
right = [0, 0, 3, 0, 6, 0, 7, 0]
output = []

def traverse(node):
    if node == 0:
        return
    traverse(left[node])
    traverse(right[node])
    output.append(node)

traverse(4)
print(*output)

Expected output: 1 3 2 5 7 6 4

Tree traversals take O(n) time. DFS uses O(h) call or explicit stack space. Iterative BFS uses O(w) live queue space; array queues with a head index retain O(n) storage. Here h is tree height and w is maximum width. Output storage is counted separately.

These examples assume a proper tree: no cycles and no shared children. In-order is sorted only for a binary search tree. Deep trees may exceed the recursion limit; prefer an iterative traversal when depth is unbounded. Bounded C, C++ and Ada buffers fit this fixture and must be resized for larger trees.

Binary tree: breadth-first search

Visit one level at a time, left to right, using an iterative FIFO queue.

IterativeCurrent focus
Focus—➤➤➤➤➤➤4261357
Visited output∅
Work queue: next on the left∅
Step 1 of 24
Step 1 of 24

Use the same binary tree: root 4, children 2 and 6, and leaves 1, 3, 5 and 7.

python
left = [0, 0, 1, 0, 2, 0, 5, 0]
right = [0, 0, 3, 0, 6, 0, 7, 0]
output = []

from collections import deque

def traverse(root):
    queue = deque([root] if root else [])
    while queue:
        node = queue.popleft()
        output.append(node)
        for child in (left[node], right[node]):
            if child:
                queue.append(child)

traverse(4)
print(*output)

Expected output: 4 2 6 1 3 5 7

Tree traversals take O(n) time. DFS uses O(h) call or explicit stack space. Iterative BFS uses O(w) live queue space; array queues with a head index retain O(n) storage. Here h is tree height and w is maximum width. Output storage is counted separately.

These examples assume a proper tree: no cycles and no shared children. In-order is sorted only for a binary search tree. Deep trees may exceed the recursion limit; prefer an iterative traversal when depth is unbounded. Bounded C, C++ and Ada buffers fit this fixture and must be resized for larger trees.

flowchart LR
    A[0] --> B[1]
    A --> C[2]
    B --> D[3]
    C --> D

Step-by-step trace

BFS queue starts [0], becomes [1,2], then [2,3], then [3], then empty: output 0 1 2 3. DFS enters 0, 1 and 3, returns to 0 and enters 2; it skips the already visited 3: output 0 1 3 2. Neighbor order determines the exact visitation order.

Complete worked example

python
from collections import deque

graph = [[1, 2], [3], [3], []]
seen = {0}
queue = deque([0])
breadth = []
while queue:
    vertex = queue.popleft()
    breadth.append(vertex)
    for neighbor in graph[vertex]:
        if neighbor not in seen:
            seen.add(neighbor) # Mark before enqueue.
            queue.append(neighbor)
print(*breadth) # 0 1 2 3

seen.clear()
depth = []
def dfs(vertex):
    if vertex in seen:
        return
    seen.add(vertex)
    depth.append(vertex)
    for neighbor in graph[vertex]:
        dfs(neighbor)

dfs(0)
print(*depth) # 0 1 3 2

Expected output

plaintext
0 1 2 3
0 1 3 2

Time & space complexity

Adjacency-list traversal: O(V + E) time across visited vertices and edges, O(V) auxiliary space. Recursive DFS can use O(V) stack depth. An adjacency matrix takes O(V²) space and requires scanning rows for neighbors.

When to use it

Use BFS for unweighted shortest paths and level-order exploration; record a parent when first discovering each vertex to reconstruct a path. Use DFS for dependency exploration, components and cycle analysis.

Trade-offs & edge cases

Directed and undirected edges have different meanings; an undirected edge normally appears in both neighbor lists. For a full disconnected traversal, start another search at each unvisited vertex. Directed cycle detection and topological ordering require more than one visited flag, such as unseen/active/finished states.

Weighted shortest paths: Dijkstra

Dijkstra finds minimum total path weights from one source when every edge weight is nonnegative. It repeatedly settles the unsettled vertex with the smallest tentative distance. Relaxing an edge means replacing a destination’s distance when the route through the current vertex is cheaper.

How it works & invariant

Set the source distance to zero and others to infinity. Select a minimum unsettled vertex by scanning all vertices, stop if none is reachable, and relax its outgoing edges. This intentionally uses linear minimum selection rather than a heap. Some languages use adjacency lists, others a matrix with −1 for an absent edge; zero-weight edges remain valid.

Dijkstra: relaxation and settling

Edge labels are weights. Each node shows its tentative distance. Only the smallest unsettled distance is finalized next.

Find shortest pathsCurrent focus
Focus—➤4➤1➤1➤2➤50d=01d=∞2d=∞3d=∞
Settled vertices∅
Tentative distances: vertices 0, 1, 2, 30, ∞, ∞, ∞
Step 1 of 16
Step 1 of 16

Set distance 0 to zero and all other distances to infinity. Edge weights are nonnegative.

flowchart LR
    A[0] -->|4| B[1]
    A -->|1| C[2]
    C -->|2| B
    B -->|1| D[3]
    C -->|5| D

Step-by-step trace

From 0, tentative distances become [0,4,1,∞]. Settle 2 next: 0 → 2 → 1 costs 3 and 0 → 2 → 3 costs 6. Settle 1 next and improve 3 to 4. Final distances are 0 3 1 4. The best route to 3 is 0 → 2 → 1 → 3.

Complete worked example

python
# Dijkstra, O(V^2 + E); nonnegative weights only.
graph = [[(1, 4), (2, 1)], [(3, 1)], [(1, 2), (3, 5)], []]
distance = [float('inf')] * len(graph)
settled = [False] * len(graph)
distance[0] = 0
for _ in graph:
    vertex = -1
    for i in range(len(graph)):
        if not settled[i] and (vertex == -1 or distance[i] < distance[vertex]):
            vertex = i
    if vertex == -1 or distance[vertex] == float('inf'):
        break
    settled[vertex] = True
    for neighbor, weight in graph[vertex]:
        distance[neighbor] = min(distance[neighbor], distance[vertex] + weight)
print(*distance) # 0 3 1 4

Expected output

plaintext
0 3 1 4

Time & space complexity

Linear selection with adjacency lists: O(V² + E) time; the matrix versions take O(V²). Auxiliary distances and settled flags use O(V) space. A binary-heap implementation with adjacency lists can achieve O((V + E) log V), with implementation-dependent queue storage.

When to use it

Use for nonnegative travel costs, latency or weighted routing. Use BFS when every edge has equal cost. Negative edges require another algorithm, such as Bellman–Ford, including handling of reachable negative cycles.

Trade-offs & edge cases

Negative weights break the settling proof. Unreachable vertices retain infinity; never add a weight to an infinity sentinel. Fixed-width implementations guard distance addition against overflow. Distances alone do not reconstruct paths; maintain predecessors when a relaxation improves a distance.

Problem-solving techniques

Two pointers on sorted data

Two pointers can eliminate many candidate pairs without testing them individually. For a sorted ascending sequence, start one pointer at each end. Comparing their sum with the target tells us which endpoint can be safely discarded.

How it works & invariant

If the sum is too small, moving the right pointer left cannot increase it, so discard the current left endpoint. If the sum is too large, moving the left pointer right cannot decrease it, so discard the current right endpoint. Stop on a match or when the pointers meet. A valid pair must use two distinct positions.

Two pointers: pair sum

Sorted values let each comparison discard one endpoint. L and R must remain at distinct indices.

Find a pairCurrent focus
Focus0, 41Index 0L2Index 14Index 27Index 311Index 4R
Target9
Endpoint sum12
Step 1 of 7
Step 1 of 7

Start with one pointer at each end of the sorted array.

Current focus: 0 → 4

Step-by-step trace

For [1,2,4,7,11] and target 9: 1 + 11 = 12, so move right leftward. Then 1 + 7 = 8, so move left rightward. Now 2 + 7 = 9: output zero-based indices 1 3. Negative numbers also work when the ordering precondition holds.

Complete worked example

python
def pair_sum(values, target):
    left, right = 0, len(values) - 1
    while left < right:
        total = values[left] + values[right]
        if total == target:
            return left, right
        if total < target:
            left += 1
        else:
            right -= 1
    return -1, -1

print(*pair_sum([1, 2, 4, 7, 11], 9)) # 1 3; sorted input required

Expected output

plaintext
1 3

Time & space complexity

O(n) time and O(1) auxiliary space on already sorted input. Sorting first adds O(n log n) time and may require extra storage. Preserving original indices requires carrying them through the sort.

When to use it

Use for sorted pair sums, merging sorted sequences, deduplication and partitioning. A hash-based complement lookup is another option for unsorted pair sums, trading expected O(n) extra storage for avoiding a sort.

Trade-offs & edge cases

These programs return the first encountered pair, not all pairs. Most versions use −1 indices to indicate no match; Rust uses Option. Empty and singleton input cannot form a pair. Check sum overflow for large fixed-width values.

Sliding windows

A sliding window reuses work between overlapping contiguous ranges. This example finds the maximum sum of exactly three consecutive values. Rather than recomputing each window from scratch, subtract the leaving value and add the entering value.

How it works & invariant

Compute the first width-element sum and initialize best to that sum. For each later endpoint, update sum by values[i] − values[i − width], then compare against best. The invariant is that sum equals the current window total and best equals the greatest total seen so far. Initializing best to zero would be wrong for all-negative input.

Sliding window: maximum sum

Keep exactly three values in the window. Subtract the leaving value, add the entering value, and retain the best sum.

Slide the windowCurrent focus
Focus0, 1, 22Index 0L1Index 15Index 2R1Index 33Index 42Index 5
Window sum8
Best sum8
Step 1 of 8
Step 1 of 8

Sum the first three values: 2 + 1 + 5 = 8. Initialize best from this real window.

Current focus: 0 → 1 → 2

Step-by-step trace

For [2,1,5,1,3,2], the width-three windows sum to 8, 7, 9 and 6. Moving from [1,5,1] to [5,1,3] subtracts 1 and adds 3: 7 − 1 + 3 = 9. The maximum is 9, from values at indices 2 through 4.

Complete worked example

python
def max_window(values, width):
    if width < 1 or width > len(values):
        raise ValueError('Invalid width')
    total = sum(values[:width])
    best = total
    for i in range(width, len(values)):
        total += values[i] - values[i - width]
        best = max(best, total)
    return best

print(max_window([2, 1, 5, 1, 3, 2], 3)) # 9

Expected output

plaintext
9

Time & space complexity

O(n) time and O(1) auxiliary space for a fixed-width sum. Recomputing every window independently would take O(n × width). The width must satisfy 1 ≤ width ≤ n.

When to use it

Use for rolling totals and fixed-length substring or subarray statistics. Variable-width windows can solve longest or shortest feasible-range problems when expanding and shrinking change validity in a predictable way.

Trade-offs & edge cases

Fixed-width sums work with negative values. A variable-width sum algorithm that shrinks only when the total exceeds a target generally requires nonnegative values; do not transfer that assumption to arbitrary signed input. Test width one, width n and all-negative values.

Prefix sums & range queries

A prefix-sum array stores cumulative totals so any static interval total can be answered with one subtraction. Define prefix[0] = 0 and prefix[i + 1] = prefix[i] + values[i]. The extra leading zero removes special handling for intervals starting at zero.

How it works & invariant

Use half-open intervals [left, right), including left and excluding right. The range total is prefix[right] − prefix[left], because the common prefix cancels. An empty range has equal endpoints and total zero. All examples validate 0 ≤ left ≤ right ≤ n before reading the prefix array.

Prefix sums: build and query

A leading zero makes half-open range sums a single subtraction, including empty intervals.

Build and queryCurrent focus
Focus—2Index 04Index 11Index 23Index 30Index 0P
Prefix totals0
Step 1 of 9
Step 1 of 9

Initialize prefix[0] = 0. The top row is input; the bottom row stores prefix totals.

Step-by-step trace

For [2,4,1,3], prefix becomes [0,2,6,7,10]. Query [1,3) returns 7 − 2 = 5, covering 4 + 1. Query [2,2) returns 6 − 6 = 0. Query [0,4) would return the full total, 10.

Complete worked example

python
values = [2, 4, 1, 3]
prefix = [0]
for value in values:
    prefix.append(prefix[-1] + value)

def range_sum(left, right):
    if not 0 <= left <= right <= len(values):
        raise ValueError('Invalid range')
    return prefix[right] - prefix[left]

print(range_sum(1, 3)) # 5: [1, 3)
print(range_sum(2, 2)) # 0: empty range

Expected output

plaintext
5
0

Time & space complexity

Preprocessing: O(n) time and O(n) extra space. Each range query: O(1). Changing one original value requires updating all subsequent prefix totals, which is O(n) in the worst case.

When to use it

Useful for many queries over mostly static data, cumulative counts and interval statistics. For frequent point updates, consider a Fenwick tree or segment tree instead of rebuilding every suffix.

Trade-offs & edge cases

Agree on inclusive versus exclusive endpoints before coding. Prefix totals can overflow even when individual elements fit the chosen type. These examples use small exact integers; floating-point prefix subtraction can amplify cancellation error.

Recursion & backtracking

Recursion solves a problem by calling a smaller version of itself and stopping at a base case. Backtracking explores a decision tree, maintaining a partial solution and undoing choices before trying alternatives. This example enumerates every subset of {1,2}.

How it works & invariant

At each value, first explore excluding it, then append it and explore including it. Undo the append before returning. The path contains exactly the included values from earlier decisions. Languages passing an explicit logical length by value can overwrite an inactive slot instead of removing an element from a shared container.

Backtracking: enumerate subsets

Each branch excludes or includes a value. The path must be restored after exploring an inclusion branch.

Choose, explore, undoCurrent focus
Focusroot➤➤➤➤➤➤∅∅{1}∅{2}{1}{1,2}
Call stack: top on the right1
Current subset{}
Emitted subsets∅
Step 1 of 14
Step 1 of 14

Exclude 1 and explore the next decision.

Current focus: root
flowchart TD
    R[Start] -->|exclude 1| A[Empty path]
    R -->|include 1| B[Path: 1]
    A -->|exclude 2| C[Empty subset]
    A -->|include 2| D[Subset: 2]
    B -->|exclude 2| E[Subset: 1]
    B -->|include 2| F[Subset: 1 2]

Step-by-step trace

Exclude 1 and exclude 2: print − for the empty subset. Exclude 1 and include 2: print 2. Include 1 and exclude 2: print 1. Include both: print 1 2. The actual empty marker in the output is an ASCII hyphen, and each subset occupies its own line.

Complete worked example

python
path = []
def subsets(next_value, limit):
    if next_value > limit:
        print(' '.join(map(str, path)) if path else '-')
        return
    subsets(next_value + 1, limit) # Exclude
    path.append(next_value)       # Choose
    subsets(next_value + 1, limit) # Explore
    path.pop()                    # Undo

subsets(1, 2) # -, 2, 1, 1 2 (one per line)

Expected output

plaintext
-
2
1
1 2

Time & space complexity

There are 2ⁿ subsets. Printing their members costs O(n × 2ⁿ) total time in the worst case. The current path and recursion depth require O(n) auxiliary space when results are streamed rather than all retained.

When to use it

Use for combinations, permutations, constraint search and puzzle solving. Prune a branch only when a proven condition shows that no extension can be valid; pruning changes performance without discarding valid solutions.

Trade-offs & edge cases

Forgetting to undo shared mutable state contaminates sibling branches. Saving a reference to the same path repeatedly also loses earlier results; copy it when collecting answers. Large inputs are expensive because output size itself is exponential, and deep recursion can exceed stack limits.

Dynamic programming

Dynamic programming reuses solutions to overlapping subproblems. Here dp[s] means the minimum number of coins needed to form sum s using unlimited positive-denomination coins. A precise state definition is more useful than memorizing a table-filling pattern.

How it works & invariant

Set dp[0] = 0 and initialize other states to amount + 1 as an unreachable sentinel. For each increasing sum s and each coin c ≤ s, consider dp[s − c] + 1. The recurrence is valid because the last coin leaves a smaller solved sum. Positive denominations make the dependency direction acyclic.

Dynamic programming: minimum coins

Each cell stores the best count for its amount. Try every usable final coin before moving to the next amount.

Build the DP tableCurrent focus
Focus—0Index 0∞Index 1∞Index 2∞Index 3∞Index 4∞Index 5∞Index 6
Coin denominations1, 3, 4
Step 1 of 24
Step 1 of 24

Initialize dp[0] = 0 and other amounts as unreachable. Each index is an amount.

Step-by-step trace

For coins [1,3,4] and amount 6, dp[0..6] becomes [0,1,2,1,1,2,2]. The last state can use a 3 after dp[3], giving two coins. Greedy largest-first would choose 4 + 1 + 1 and use three. With coins [3,4], amount 2 remains unreachable and returns −1.

Complete worked example

python
def min_coins(coins, amount):
    # Preconditions: positive integer coins; amount >= 0.
    dp = [amount + 1] * (amount + 1)
    dp[0] = 0
    for total in range(1, amount + 1):
        for coin in coins:
            if coin <= total:
                dp[total] = min(dp[total], dp[total - coin] + 1)
    return -1 if dp[amount] > amount else dp[amount]

print(min_coins([1, 3, 4], 6)) # 2: 3 + 3
print(min_coins([3, 4], 2))    # -1: unreachable

Expected output

plaintext
2
-1

Time & space complexity

O(amount × number of coin types) time and O(amount) space. This is pseudo-polynomial: amount is a numeric value, not the number of bits used to encode it. Very large targets can make the table impractical.

When to use it

Use when a problem has overlapping subproblems and an optimal solution can be expressed through smaller optimal solutions. Top-down memoization stores recursive answers on demand; bottom-up tabulation fills states in dependency order.

Trade-offs & edge cases

The example minimizes coin count with unlimited reuse; counting combinations or limiting inventory requires different state and transition rules. Inputs require positive integer coins and a nonnegative integer amount. To reconstruct the chosen coins, save which transition improved each state.

Greedy algorithms & proofs

A greedy algorithm commits to a locally best choice without revisiting it. For maximum-cardinality interval scheduling, choose the compatible interval with the earliest finish time. The objective is the number of nonoverlapping intervals, not their total value or occupied duration.

How it works & invariant

Process intervals sorted by increasing finish time. Accept one when its start is at least the end of the last accepted interval. The exchange argument is the proof: replacing the first interval of an optimal schedule with an earlier-finishing choice leaves at least as much room for the rest, so it cannot reduce the achievable count.

Greedy: interval scheduling

Accept compatible intervals in finish-time order. Dimmed intervals were rejected because they overlap a prior choice.

Select compatible intervalsCurrent focus
Focus—[1,3)[3,4)[2,5)[4,7)[6,8)
Selected interval count0
Last accepted finish−∞
Step 1 of 12
Step 1 of 12

Process half-open intervals sorted by increasing finish time.

Step-by-step trace

Process [1,3), [3,4), [2,5), [4,7), [6,8) in finish order. Accept [1,3) and [3,4), reject [2,5), accept [4,7), reject [6,8): print 3. Touching endpoints are compatible because the intervals are half-open. The code fixtures use this finish-sorted order.

Complete worked example

python
# Sorted by finish time; intervals are [start, finish).
intervals = [(1, 3), (3, 4), (2, 5), (4, 7), (6, 8)]
end = float('-inf')
count = 0
for start, finish in intervals:
    if start >= end:
        count += 1
        end = finish
print(count) # 3

Expected output

plaintext
3

Time & space complexity

O(n) time and O(1) scan space when intervals are already finish-sorted, as in these examples. With unsorted input, add O(n log n) sorting time and the selected sorting algorithm’s storage cost.

When to use it

Useful when an exchange or cut argument proves a local decision is safe, including interval scheduling and minimum-spanning-tree choices. State the exact objective before selecting a greedy rule.

Trade-offs & edge cases

A plausible rule is not a proof. Earliest start or shortest duration does not generally maximize interval count, and weighted interval scheduling needs another approach such as dynamic programming. Largest-coin-first already fails on [1,3,4] for amount 6 in the preceding example.

Exercises & explained solutions

Choose a language, copy the relevant complete example and change the inputs before changing the algorithm. Predict the output first. The solutions below explain the reasoning without introducing language-specific code that would be missing from other selections.

1. Find the first duplicate with lower bound

For [2,2,2,5] and target 2, what should lower bound return? What about target 6 and an empty array?

Solution: return 0, 4 and 0 respectively. Equality moves hi leftward rather than returning immediately, preserving the first valid position. The length result means insertion after the last element; check bounds before reading it.

2. Keep a sliding window correct for negative values

For [−5,−2,−7] with width 2, what maximum should be returned?

Solution: −7. The two windows sum to −7 and −9. Initialize best from the first actual window, not zero. Fixed-width sliding sums remain valid with negative elements because each update preserves exactly the same number of terms.

3. Add a graph cycle and a disconnected vertex

Add edge 3 → 0 and an isolated vertex 4 to the traversal fixture. Should BFS from 0 loop forever or visit 4?

Solution: neither. Marking before enqueue means 0 is never enqueued a second time. Vertex 4 is unreachable and stays unvisited. To list all components, start a new traversal from each remaining unvisited vertex. Expand fixed-size queues and visited arrays when adding vertices.

4. Explain why a greedy coin choice fails

With coins [1,3,4] and amount 6, compare repeatedly taking the largest possible coin with the dynamic-programming result.

Solution: greedy chooses 4, 1, 1, but the optimum is 3, 3. A locally largest denomination does not preserve a globally minimum count. Dynamic programming considers all possible final coins for each smaller sum, so dp[6] can reuse the optimal dp[3].

5. Decide whether prefixes or updates dominate

You need thousands of interval sums, but the input changes after every query. Is a plain prefix array always a good choice?

Solution: no. Each point change may require O(n) suffix updates. A Fenwick tree supports point additions and prefix sums in O(log n); a segment tree supports a broader family of associative interval operations. For static data, the simpler O(1) prefix query remains attractive.

6. Decode a byte and distinguish ANY from ALL flags

Interpret binary 11111011 as unsigned and as signed eight-bit two’s complement. If flags = 4 and required = 5, do the ANY and ALL flag tests agree?

Solution: the unsigned value is 251; the signed value is 251 − 256 = −5. The shared flag intersection is 4. ANY succeeds because that intersection is nonzero; ALL fails because 4 does not equal 5. Keep the bit width and the intended membership predicate explicit.

Implementation checklist

  • Specify the result for empty input, duplicates, missing keys, unreachable targets and invalid ranges.
  • State whether an operation mutates input, returns a copy or borrows existing storage.
  • Check allocation ownership, capacity limits, overflow and maximum recursion depth.
  • Distinguish expected, amortized and worst-case claims, and include preprocessing and output costs.
  • Compare optimized code against a simple brute-force oracle on small inputs, then benchmark realistic sizes.
Diagram
100%