Bitpath

Algorithm Foundations

Start here. Learn to count the steps your code takes, then use that on the three structures every other algorithm is built from: arrays, strings and hash maps.

  • Beginner
  • 4 units, 12 lessons, 142 exercises
  • Python, JavaScript or TypeScript
  • Builds on loops, functions, lists

Unit 01 · 3 lessons

Counting steps

Estimate how the work in your code grows with its input

  1. > start01Growth, not seconds
  2. 02Loops inside loops
  3. BOSSTwenty questions
Unit prize
  1. 01
    Growth, not seconds

    Count loop runs: constant and linear time

  2. 02
    Loops inside loops

    Nested loops multiply: quadratic time

  3. BOSS
    Twenty questions

    Halving makes a million shrink to 20

Read the unit guide

Big-O answers one question: when the input gets bigger, how much more work does the code do? It counts steps, not seconds, so the answer is the same on a phone and on a supercomputer.

Count how often the innermost line runs for an input of size n. No dependence on n is O(1), constant. One loop over the input is O(n), linear. A loop inside a loop over the same input is O(n²), quadratic: double n and the work quadruples.

Loops one after another add (n + n is still O(n)). Loops inside each other multiply. Then simplify: drop constants and smaller terms, so 3n + 10 is O(n) and n² + n is O(n²). Only the fastest-growing term matters once n is large.

Halving is the cheap trick behind fast algorithms. If every step throws away half of what is left, a million items are gone in about 20 steps. That is O(log n).

Unless someone says otherwise, Big-O means the worst case: the input that makes the code work hardest. From best to worst growth: O(1), O(log n), O(n), O(n log n), O(n²), O(2ⁿ).

Memory is counted the same way. A few variables are O(1) space; a new list as long as the input is O(n) space.

Unit 02 · 3 lessons

Arrays

Know what every array operation costs before you use it

  1. 01Index and scan
  2. 02The cost of moving
  3. BOSSReverse in place
Unit prize
  1. 01
    Index and scan

    Jump to a slot in O(1), search in O(n)

  2. 02
    The cost of moving

    Cheap at the end, expensive at the front

  3. BOSS
    Reverse in place

    Two indexes, swaps, and no extra memory

Read the unit guide

An array (a list in Python) keeps its items side by side in one block of memory, numbered from 0 to n - 1. Because the position of item i can be computed directly, reading or writing by index is O(1) whatever the size.

Finding a value is different: with no order to exploit, you must scan. Largest item, first negative, "is 7 in here?" are all one pass, O(n). Start a running best from the first item, never from 0.

The end of an array is cheap and the front is expensive. Appending and popping at the end touch one slot: O(1) (amortised, because the array occasionally doubles its storage). Inserting or removing at the front shifts every other item: O(n). Doing that inside a loop is a hidden O(n²).

Assignment never copies. b = a gives the same array a second name, so a change through one shows through the other. A real copy (a slice, a spread) costs O(n) time and O(n) memory.

Working in place means rearranging the array you were given using only a few variables: O(1) extra space. The classic tool is two indexes that start at the ends and walk toward each other, swapping as they go. Stop when they meet: i < j.

Reading past the end is the classic bug. Python raises an IndexError at once; JavaScript quietly returns undefined and fails somewhere else later.

Unit 03 · 3 lessons

Strings

Treat text as an array of characters that can never change

  1. 01Strings don't change
  2. 02Counting characters
  3. BOSSPalindromes and anagrams
Unit prize
  1. 01
    Strings don't change

    Every edit builds a new string

  2. 02
    Counting characters

    Letters are numbers: count them in 26 slots

  3. BOSS
    Palindromes and anagrams

    Two ends moving inward, and counting letters

Read the unit guide

A string is an array of characters you can read but not write. Indexing and length are O(1), exactly as for arrays. What you cannot do is change a character in place: strings are immutable in Python, JavaScript and TypeScript alike.

Every "change" therefore builds a new string and copies the old characters across. Adding one character to a string of n characters is O(n), so growing a string with += inside a loop can cost O(n²) in total. The reliable pattern is to collect the pieces in a list and join them once at the end: O(n).

Characters are numbers underneath. The lowercase letters have consecutive codes starting at 97 for "a", so code - 97 turns a letter into an index from 0 to 25. That makes a 26-slot array a tiny, fast table for counting letters, and its size never depends on the input: O(1) extra space.

Two ends moving inward is the tool for palindromes: compare the first character with the last, step both indexes, stop when they meet. That is n / 2 comparisons and no extra memory.

Anagrams are words with identical letter counts. Sorting both words and comparing costs O(n log n); counting letters costs O(n). Check the lengths first: if they differ, the answer is already no.

The classic pitfalls: forgetting that string methods return a new string instead of changing the old one, and forgetting that "A" and "a" have different codes.

Unit 04 · 3 lessons

Hash maps and sets

Trade a little memory for instant lookup

  1. 01Instant lookup
  2. 02Counting with a map
  3. BOSSTwo Sum
Unit prize
  1. 01
    Instant lookup

    Sets and maps answer in one step

  2. 02
    Counting with a map

    The frequency-map idiom, in one pass

  3. BOSS
    Two Sum

    From every pair to one pass with a map

Read the unit guide

A hash set answers "have I seen this value?" and a hash map answers "what is stored under this key?", both in O(1) on average, however much they hold. They do it by computing a slot number from the value itself and jumping there, like array indexing with any value as the index. The price is O(n) extra memory and no positions: you cannot ask a set for its third item.

Sets are for membership and for removing duplicates. A list answers "is x in here?" by scanning, O(n); put the items in a set first and each check is one step. That single swap turns many O(n²) loops into O(n).

Maps are for remembering something about each key. The counting idiom is the one to know by heart: for each item, read its current count (0 if it is missing), add one, and store it back. One pass, O(n).

A missing key behaves differently in each language. Python's square brackets raise a KeyError, while get returns None or a default you choose. JavaScript's Map.get returns undefined. Decide what "missing" should mean before you look anything up.

The pattern behind Two Sum, and a great many interview problems: walk the list once, and at each item ask the map whether the partner you need has already gone by. Check first, then store the current item, so that an item can never be paired with itself.

The trade-off is always the same: O(n) memory buys O(n) time. When the keys come from a small fixed range, such as the letters a to z, a plain array of counters is simpler and faster.

Learn Algorithm Foundations on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy