# The Interview Cake Course (0. Algorithmic thinking)

Where to start? At the beginning! We’ve carefully ordered our course to cover the the most important stuff first.

One exception: if you’re already pretty solid on data structures and algorithms, you can probably skip section 0.

## The idea behind big O notation

Big O notation is the language we use for talking about how long an algorithm takes to run . It’s how we compare the efficiency of different approaches to a problem.

It’s like math except it’s an awesome, not-boring kind of math where you get to wave your hands through the details and just focus on what’s basically happening.

With big O notation we express the runtime in terms of—brace yourself— how quickly it grows relative to the input, as the input gets arbitrarily large .

Let’s break that down:

1. how quickly the runtime grows —It’s hard to pin down the exact runtime of an algorithm. It depends on the speed of the processor, what else the computer is running, etc. So instead of talking about the runtime directly, we use big O notation to talk about how quickly the runtime grows .
2. relative to the input —If we were measuring our runtime directly, we could express our speed in seconds. Since we’re measuring how quickly our runtime grows , we need to express our speed in terms of…something else. With Big O notation, we use the size of the input, which we call “nn.” So we can say things like the runtime grows “on the order of the size of the input” (O(n)O(n)) or “on the order of the square of the size of the input” (O(n^2)O(n2)).
3. as the input gets arbitrarily large —Our algorithm may have steps that seem expensive when nn is small but are eclipsed eventually by other steps as nn gets huge. For big O analysis, we care most about the stuff that grows fastest as the input grows, because everything else is quickly eclipsed as nn gets very large. (If you know what an asymptote is, you might see why “big O analysis” is sometimes called “asymptotic analysis.”)

If this seems abstract so far, that’s because it is. Let’s look at some examples.

## Some examples

def print_first_item(items):
print items[0]


This function runs in O(1)O(1) time (or “constant time”) relative to its input . The input list could be 1 item or 1,000 items, but this function would still just require one “step.”

def print_all_items(items):
for item in items:
print item


This function runs in O(n)O(n) time (or “linear time”), where nn is the number of items in the list . If the list has 10 items, we have to print 10 times. If it has 1,000 items, we have to print 1,000 times.

def print_all_possible_ordered_pairs(items):
for first_item in items:
for second_item in items:
print first_item, second_item


Here we’re nesting two loops. If our list has nn items, our outer loop runs nn times and our inner loop runs nn times for each iteration of the outer loop , giving us n^2n2 total prints. Thus this function runs in O(n^2)O(n2) time (or “quadratic time”) . If the list has 10 items, we have to print 100 times. If it has 1,000 items, we have to print 1,000,000 times.

## N could be the actual input, or the size of the input

Both of these functions have O(n)O(n) runtime, even though one takes an integer as its input and the other takes a list:

def say_hi_n_times(n):
for time in xrange(n):
print "hi"

def print_all_items(items):
for item in items:
print item


So sometimes nn is an actual number that’s an input to our function, and other times nn is the number of items in an input list (or an input map, or an input object, etc.).

## Drop the constants

This is why big O notation rules . When you’re calculating the big O complexity of something, you just throw out the constants. So like:

def print_all_items_twice(items):
for item in items:
print item

# Once more, with feeling
for item in items:
print item


This is O(2n)O(2n), which we just call O(n)O(n).

def print_first_item_then_first_half_then_say_hi_100_times(items):
print items[0]

middle_index = len(items) / 2
index = 0
while index < middle_index:
print items[index]
index += 1

for time in xrange(100):
print "hi"


This is O(1 + n/2 + 100)O(1+n/2+100), which we just call O(n)O(n).

Why can we get away with this? Remember, for big O notation we’re looking at what happens as nn gets arbitrarily large . As nn gets really big, adding 100 or dividing by 2 has a decreasingly significant effect.

## Drop the less significant terms

For example:

def print_all_numbers_then_all_pair_sums(numbers):
print "these are the numbers:"
for number in numbers:
print number

print "and these are their sums:"
for first_number in numbers:
for second_number in numbers:
print first_number + second_number


Here our runtime is O(n + n^2)O(n+n2), which we just call O(n^2)O(n2). Even if it was O(n^2/2 + 100n)O(n2/2+100n), it would still be O(n^2)O(n2).

Similarly:

• O(n^3 + 50n^2 + 10000)O(n3+50n2+10000) is O(n^3)O(n3)
• O((n + 30) * (n + 5))O((n+30)∗(n+5)) is O(n^2)O(n2)

Again, we can get away with this because the less significant terms quickly become, well, less significant as nn gets big.

## We’re usually talking about the “worst case”

Often this “worst case” stipulation is implied. But sometimes you can impress your interviewer by saying it explicitly.

Sometimes the worst case runtime is significantly worse than the best case runtime:

def contains(haystack, needle):

# Does the haystack contain the needle?
for item in haystack:
if item == needle:
return True

return False


Here we might have 100 items in our haystack, but the first item might be the needle, in which case we would return in just 1 iteration of our loop.

In general we’d say this is O(n)O(n) runtime and the “worst case” part would be implied. But to be more specific we could say this is worst case O(n)O(n) and best case O(1)O(1) runtime. For some algorithms we can also make rigorous statements about the “average case” runtime.

## Space complexity: the final frontier

Sometimes we want to optimize for using less memory instead of (or in addition to) using less time. Talking about memory cost (or “space complexity”) is very similar to talking about time cost. We simply look at the total size (relative to the size of the input) of any new variables we’re allocating.

This function takes O(1)O(1) space (we use a fixed number of variables):

def say_hi_n_times(n):
for time in xrange(n):
print "hi"


This function takes O(n)O(n) space (the size of hi_list scales with the size of the input):

def list_of_hi_n_times(n):
hi_list = []
for time in xrange(n):
hi_list.append("hi")
return hi_list


Usually when we talk about space complexity, we’re talking about additional space , so we don’t include space taken up by the inputs. For example, this function takes constant space even though the input has nn items:

def get_largest_item(items):
largest = float('-inf')
for item in items:
if item > largest:
largest = item
return largest


Sometimes there’s a tradeoff between saving time and saving space , so you have to decide which one you’re optimizing for.

## Big O analysis is awesome except when it’s not

You should make a habit of thinking about the time and space complexity of algorithms as you design them . Before long this’ll become second nature, allowing you to see optimizations and potential performance issues right away.

Asymptotic analysis is a powerful tool, but wield it wisely.

Big O ignores constants, but sometimes the constants matter . If we have a script that takes 5 hours to run, an optimization that divides the runtime by 5 might not affect big O, but it still saves you 4 hours of waiting.

Beware of premature optimization . Sometimes optimizing time or space negatively impacts readability or coding time. For a young startup it might be more important to write code that’s easy to ship quickly or easy to understand later, even if this means it’s less time and space efficient than it could be.

But that doesn’t mean startups don’t care about big O analysis. A great engineer (startup or otherwise) knows how to strike the right balance between runtime, space, implementation time, maintainability, and readability.

You should develop the skill to see time and space optimizations, as well as the wisdom to judge if those optimizations are worthwhile.

# Data Structures for Coding Interviews

## Computer science in plain English

To really understand how data structures work , we’re going to derive each of them from scratch. Starting with bits.

Don’t worry—we’ll skip the convoluted academic jargon and proofs.

We’ll cover:

## Random Access Memory (RAM)

When a computer is running code, it needs to keep track of variables (numbers, strings, arrays, etc.).

Variables are stored in random access memory ( RAM ). We sometimes call RAM “working memory” or just “memory.”

RAM is not where mp3s and apps get stored. In addition to “memory,” your computer has storage (sometimes called “persistent storage” or “disc”). While memory is where we keep the variables our functions allocate as they crunch data for us, storage is where we keep files like mp3s, videos, Word documents, and even executable programs or apps.

Memory (or RAM) is faster but has less space, while storage (or “disc”) is slower but has more space. A modern laptop might have ~500GB of storage but only ~16GB of RAM.

Think of RAM like a really tall bookcase with a lot of shelves. Like, billions of shelves.

It just keeps going down. Again, picture billions of these shelves.

The shelves are numbered.

We call a shelf’s number its address .

Each shelf holds 8 bits . A bit is a tiny electrical switch that can be turned “on” or “off.” But instead of calling it “on” or “off” we call it 1 or 0.

8 bits is called a byte . So each shelf has one byte (8 bits) of storage.

Of course, we also have a processor that does all the real work inside our computer:

It’s connected to a memory controller . The memory controller does the actual reading and writing to and from RAM. It has a direct connection to each shelf of RAM.

That direct connection is important. It means we can access address 0 and then immediately access address 918,873 without having to “climb down” our massive bookshelf of RAM.

That’s why we call it Random Access Memory (RAM)—we can Access the bits at any Random address in Memory right away.

Spinning hard drives don’t have this “random access” superpower, because there’s no direct connection to each byte on the disc. Instead, there’s a reader—called a head —that moves along the surface of a spinning storage disc (like the needle on a record player). Reading bytes that are far apart takes longer because you have to wait for the head to physically move along the disc.

Even though the memory controller can jump between far-apart memory addresses quickly, programs tend to access memory that’s nearby. So computers are tuned to get an extra speed boost when reading memory addresses that’re close to each other . Here’s how it works:

The processor has a cache where it stores a copy of stuff it’s recently read from RAM.

Actually, it has a series of caches. But we can picture them all lumped together as one cache like this.

This cache is much faster to read from than RAM, so the processor saves time whenever it can read something from cache instead of going out to RAM.

When the processor asks for the contents of a given memory address, the memory controller also sends the contents of a handful of nearby memory addresses. And the processor puts all of it in the cache.

So if the processor asks for the contents of address 951, then 952, then 953, then 954…it’ll go out to RAM once for that first read, and the subsequent reads will come straight from the super-fast cache.

## Binary numbers

Let’s put those bits to use. Let’s store some stuff. Starting with numbers.

The number system we usually use (the one you probably learned in elementary school) is called base 10 , because each digit has ten possible values (1, 2, 3, 4, 5, 6, 7, 8, 9, and 0).

But computers don’t have digits with ten possible values. They have bits with two possible values. So they use base 2 numbers.

Base 10 is also called decimal . Base 2 is also called binary .

To understand binary, let’s take a closer look at how decimal numbers work. Take the number “101” in decimal:

Notice we have two "1"s here, but they don’t mean the same thing. The leftmost “1” means 100, and the rightmost “1” means 1. That’s because the leftmost “1” is in the hundreds place, while the rightmost “1” is in the ones place. And the “0” between them is in the tens place.

So this “101” in base 10 is telling us we have "1 hundred, 0 tens, and 1 one."

Notice how the places in base 10 (ones place, tens place, hundreds place, etc.) are sequential powers of 10 :

• 10^0=1100=1
• 10^1=10101=10
• 10^2=100102=100
• 10^3=1000103=1000
• etc.

The places in binary (base 2) are sequential powers of 2 :

• 2^0=120=1
• 2^1=221=2
• 2^2=422=4
• 2^3=823=8
• etc.

So let’s take that same “101” but this time let’s read it as a binary number:

Reading this from right to left: we have a 1 in the ones place, a 0 in the twos place, and a 1 in the fours place. So our total is 4 + 0 + 1 which is 5.

Here’s how we’d count up to 12 in binary:

Decimal Binary
00 0000
11 0001
22 0010
33 0011
44 0100
55 0101
66 0110
77 0111
88 1000
99 1001
1010 1010
1111 1011
1212 1100

So far we’ve been talking about unsigned integers (“unsigned” means non-negative, and “integer” means a whole number, not a fraction or decimal). Storing other numbers isn’t hard though. Here’s how some other numbers could be stored:

Fractions: Store two numbers: the numerator and the denominator.

Decimals: Also two numbers: 1) the number with the decimal point taken out, and 2) the position where the decimal point goes (how many digits over from the leftmost digit).

Negative Numbers: Reserve the leftmost bit for expressing the sign of the number. 0 for positive and 1 for negative.

In reality we usually do something slightly fancier for each of these. But these approaches work , and they show how we can express some complex stuff with just 1s and 0s.

We’ve talked about base 10 and base 2…you may have also seen base 16 , also called hexadecimal or hex .

In hex, our possible values for each digit are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, and f. Hex numbers are often prefixed with “0x” or “#”.

In CSS, colors are sometimes expressed in hex. Interview Cake’s signature blue color is “#5bc0de”.

## Fixed-width integers

How many different numbers can we express with 1 byte (8 bits)?

2^8=25628=256 different numbers. How did we know to take 2^828?

What happens if we have the number 255 in an 8-bit unsigned integer (1111 1111 in binary) and we add 1? The answer (256) needs a 9th bit (1 0000 0000). But we only have 8 bits!

This is called an integer overflow . At best, we might just get an error. At worst, our computer might compute the correct answer but then just throw out the 9th bit, giving us zero (0000 0000) instead of 256 (1 0000 0000)! (Python actually notices that the result won’t fit and automatically allocates more bits to store the larger number.)

The 256 possibilities we get with 1 byte are pretty limiting. So we usually use 4 or 8 bytes (32 or 64 bits) for storing integers .

• 32-bit integers have 2^{32}232 possible values—more than 4 billion
• 64-bit integers have 2^{64}264 possible values—more than 10 billion billion (10^{19}1019).

"How come I’ve never had to think about how many bits my integers are?" Maybe you have but just didn’t know it.

Have you ever noticed how in some languages (like Java and C) sometimes numbers are Integers and sometimes they’re Longs? The difference is the number of bits (in Java, Integers are 32 bits and Longs are 64).

Ever created a table in SQL? When you specify that a column will hold integers, you have to specify how many bytes: 1 byte (tinyint), 2 bytes (smallint), 4 bytes (int), or 8 bytes (bigint).

When is 32 bits not enough? When you’re counting views on a viral video . YouTube famously ran into trouble when the Gangnam Style video hit over 2^{31}231 views, forcing them to upgrade their view counts from 32-bit to 64-bit signed integers.

Most integers are fixed-width or fixed-length , which means the number of bits they take up doesn’t change.

It’s usually safe to assume an integer is fixed-width unless you’re told otherwise. Variable-size numbers exist , but they’re only used in special cases.

If we have a 64-bit fixed-length integer, it doesn’t matter if that integer is 0 or 193,457—it still takes up the same amount of space in RAM: 64 bits.

Are you familiar with big O notation? It’s a tool we use for talking about how much time an algorithm takes to run or how much space a data structure takes up in RAM. It’s pretty simple:

O(1)O(1) or constant means the time or space stays about the same even as the dataset gets bigger and bigger.

O(n)O(n) or linear means the time or space grows proportionally as the dataset grows.

So O(1)O(1) space is much smaller than O(n)O(n) space. And O(1)O(1) time is much faster than O(n)O(n) time.

That’s all you need for this piece. But if you’re curious, you can read our whole big O explainer here.

In big O notation, we say fixed-width integers take up constant space or O(1)O(1) space.

And because they have a constant number of bits, most simple operations on fixed-width integers (addition, subtraction, multiplication, division) take constant time (O(1)O(1) time) .

So fixed-width integers are very space efficient and time efficient.

But that efficiency comes at a cost— their values are limited . Specifically, they’re limited to 2^n2n possibilities, where nn is the number of bits.

So there’s a tradeoff. As we’ll see, that’s a trend in data structures—to get a nice property, we’ll often have to lose something.

## Arrays

Ok, so we know how to store individual numbers. Let’s talk about storing several numbers .

That’s right, things are starting to heat up .

Suppose we wanted to keep a count of how many bottles of kombucha we drink every day.

Let’s store each day’s kombucha count in an 8-bit, fixed-width, unsigned integer. That should be plenty—we’re not likely to get through more than 256 (2^828) bottles in a single day , right?

And let’s store the kombucha counts right next to each other in RAM, starting at memory address 0:

Bam. That’s an array . RAM is basically an array already.

Just like with RAM, the elements of an array are numbered. We call that number the index of the array element (plural: indices). In this example, each array element’s index is the same as its address in RAM.

But that’s not usually true. Suppose another program like Spotify had already stored some information at memory address 2:

We’d have to start our array below it, for example at memory address 3. So index 0 in our array would be at memory address 3, and index 1 would be at memory address 4, etc.:

Suppose we wanted to get the kombucha count at index 4 in our array. How do we figure out what address in memory to go to? Simple math:

Take the array’s starting address (3), add the index we’re looking for (4), and that’s the address of the item we’re looking for. 3 + 4 = 7. In general, for getting the nnth item in our array:

This works out nicely because the size of the addressed memory slots and the size of each kombucha count are both 1 byte. So a slot in our array corresponds to a slot in RAM.

But that’s not always the case. In fact, it’s usually not the case. We usually use 64-bit integers.

So how do we build an array of 64-bit (8 byte) integers on top of our 8-bit (1 byte) memory slots?

We simply give each array index 8 address slots instead of 1:

So we can still use simple math to grab the start of the nthnth item in our array—just gotta throw in some multiplication:

\text{address of nth item in array} =address of nth item in array=\text{address of array start} + (n * \text{size of each item in bytes})address of array start+(n∗size of each item in bytes)

Don’t worry—adding this multiplication doesn’t really slow us down. Remember: addition, subtraction, multiplication, and division of fixed-width integers takes O(1)O(1) time. So all the math we’re using here to get the address of the nnth item in the array takes O(1)O(1) time.

And remember how we said the memory controller has a direct connection to each slot in RAM? That means we can read the stuff at any given memory address in O(1)O(1) time.

Together, this means looking up the contents of a given array index is O(1)O(1) time. This fast lookup capability is the most important property of arrays.

But the formula we used to get the address of the nnth item in our array only works if :

1. Each item in the array is the same size (takes up the same number of bytes).
2. The array is uninterrupted (contiguous) in memory . There can’t be any gaps in the array…like to “skip over” a memory slot Spotify was already using.

These things make our formula for finding the nnth item work because they make our array predictable . We can predict exactly where in memory the nnth element of our array will be.

But they also constrain what kinds of things we can put in an array. Every item has to be the same size. And if our array is going to store a lot of stuff, we’ll need a bunch of uninterrupted free space in RAM. Which gets hard when most of our RAM is already occupied by other programs (like Spotify).

That’s the tradeoff. Arrays have fast lookups (O(1)O(1) time), but each item in the array needs to be the same size, and you need a big block of uninterrupted free memory to store the array.

## Strings

Okay, let’s store some words.

A series of characters (letters, punctuation, etc.) is called a string .

We already know one way to store a series of things —arrays. But how can an array store characters instead of numbers?

Easy. Let’s define a mapping between numbers and characters. Let’s say “A” is 1 (or 0000 0001 in binary), “B” is 2 (or 0000 0010 in binary), etc. Bam. Now we have characters.

This mapping of numbers to characters is called a character encoding . One common character encoding is “ASCII”. Here’s how the alphabet is encoded in ASCII:

A: 01000001

S: 01010011

k: 01101011

B: 01000010

T: 01010100

l: 01101100

C: 01000011

U: 01010101

m: 01101101

D: 01000100

V: 01010110

n: 01111110

E: 01000101

W: 01010111

o: 01101111

F: 01000110

X: 01011000

p: 01110000

G: 01000111

Y: 01011001

q: 01110001

H: 01001000

Z: 01011010

r: 01110010

I: 01001001

a: 01100001

s: 01110011

J: 01001010

b: 01100010

t: 01110100

K: 01001011

c: 01100011

u: 01110101

L: 01001100

d: 01100100

v: 01110110

M: 01001101

e: 01100101

w: 01110111

N: 01001110

f: 01100110

x: 01111000

O: 01001111

g: 01100111

y: 01111001

P: 01010000

h: 01101000

z: 01111010

Q: 01010001

i: 01101001

R: 01010010

j: 01101010

You get the idea. So since we can express characters as 8-bit integers, we can express strings as arrays of 8-bit numbers characters.

## Pointers

Remember how we said every item in an array had to be the same size? Let’s dig into that a little more.

Suppose we wanted to store a bunch of ideas for baby names. Because we’ve got some really cute ones.

Each name is a string. Which is really an array. And now we want to store those arrays in an array. Whoa .

Now, what if our baby names have different lengths? That’d violate our rule that all the items in an array need to be the same size!

We could put our baby names in arbitrarily large arrays (say, 13 characters each), and just use a special character to mark the end of the string within each array…

“Wigglesworth” is a cute baby name, right?

But look at all that wasted space after “Bill”. And what if we wanted to store a string that was more than 13 characters? We’d be out of luck.

There’s a better way. Instead of storing the strings right inside our array, let’s just put the strings wherever we can fit them in memory. Then we’ll have each element in our array hold the address in memory of its corresponding string. Each address is an integer, so really our outer array is just an array of integers. We can call each of these integers a pointer , since it points to another spot in memory.

The pointers are marked with a * at the beginning.

Pretty clever, right? This fixes both the disadvantages of arrays:

1. The items don’t have to be the same length—each string can be as long or as short as we want.
2. We don’t need enough uninterrupted free memory to store all our strings next to each other—we can place each of them separately, wherever there’s space in RAM.

We fixed it! No more tradeoffs. Right?

Nope. Now we have a new tradeoff:

Remember how the memory controller sends the contents of nearby memory addresses to the processor with each read? And the processor caches them? So reading sequential addresses in RAM is faster because we can get most of those reads right from the cache?

Our original array was very cache-friendly , because everything was sequential. So reading from the 0th index, then the 1st index, then the 2nd, etc. got an extra speedup from the processor cache.

But the pointers in this array make it not cache-friendly , because the baby names are scattered randomly around RAM. So reading from the 0th index, then the 1st index, etc. doesn’t get that extra speedup from the cache.

That’s the tradeoff. This pointer-based array requires less uninterrupted memory and can accommodate elements that aren’t all the same size, but it’s slower because it’s not cache-friendly.

This slowdown isn’t reflected in the big O time cost. Lookups in this pointer-based array are still O(1)O(1) time.

## Dynamic arrays

Let’s build a very simple word processor. What data structure should we use to store the text as our user writes it?

Strings are stored as arrays, right? So we should use an array?

Here’s where that gets tricky: when we allocate an array in a low-level language like C or Java, we have to specify upfront how many indices we want our array to have.

There’s a reason for this—the computer has to reserve space in memory for the array and commit to not letting anything else use that space. We can’t have some other program overwriting the elements in our array!

The computer can’t reserve all its memory for a single array. So we have to tell it how much to reserve.

But for our word processor, we don’t know ahead of time how long the user’s document is going to be! So what can we do?

Just make an array and program it to resize itself when it runs out of space! This is called a dynamic array , and it’s built on top of a normal array.

Python, Ruby, and JavaScript use dynamic arrays for their default array-like data structures. In Python, they’re called “lists.” Other languages have both. For example, in Java, array is a static array (whose size we have to define ahead of time) and ArrayList is a dynamic array.

Here’s how it works:

When you allocate a dynamic array, your dynamic array implementation makes an underlying static array . The starting size depends on the implementation—let’s say our implementation uses 10 indices:

Say you append 4 items to your dynamic array:

At this point, our dynamic array contains 4 items. It has a length of 4. But the underlying array has a length of 10.

We’d say this dynamic array’s size is 4 and its capacity is 10.

The dynamic array stores an end_index to keep track of where the dynamic array ends and the extra capacity begins.

If you keep appending, at some point you’ll use up the full capacity of the underlying array:

Next time you append, the dynamic array implementation will do a few things under the hood to make it work:

1. Make a new, bigger array. Usually twice as big.

Why not just extend the existing array? Because that memory might already be taken. Say we have Spotify open and it’s using a handful of memory addresses right after the end of our old array. We’ll have to skip that memory and reserve the next 20 uninterrupted memory slots for our new array:

2. Copy each element from the old array into the new array.

3. Free up the old array. This tells the operating system, “you can use this memory for something else now.”

We could call these special appends “doubling” appends since they require us to make a new array that’s (usually) double the size of the old one.

Appending an item to an array is usually an O(1)O(1) time operation, but a single doubling append is an O(n)O(n) time operation since we have to copy all nn items from our array.

Does that mean an append operation on a dynamic array is always worst-case O(n)O(n) time? Yes. So if we make an empty dynamic array and append nn items, that has some crazy time cost like O(n^2)O(n2) or O(n!)O(n!)?!?! Not quite.

While the time cost of each special O(n)O(n) doubling append doubles each time, the number of O(1)O(1) appends you get until the next doubling append also doubles. This kind of “cancels out,” and we can say each append has an average cost or amortized cost of O(1)O(1). ↴

Given this, in industry we usually wave our hands and say dynamic arrays have a time cost of O(1)O(1) for appends, even though strictly speaking that’s only true for the average case or the amortized cost.

In an interview, if we were worried about that O(n)O(n)-time worst-case cost of appends, we might try to use a normal, non-dynamic array.

The advantage of dynamic arrays over arrays is that you don’t have to specify the size ahead of time, but the disadvantage is that some appends can be expensive . That’s the tradeoff.

But what if we wanted the best of both worlds…

Our word processor is definitely going to need fast appends—appending to the document is like the main thing you do with a word processor.

Can we build a data structure that can store a string, has fast appends, and doesn’t require you to say how long the string will be ahead of time?

Let’s focus first on not having to know the length of our string ahead of time. Remember how we used pointers to get around length issues with our array of baby names?

What if we pushed that idea even further?

What if each character in our string were a two-index array with:

1. the character itself
2. a pointer to the next character

We would call each of these two-item arrays a node and we’d call this series of nodes a linked list .

Here’s how we’d actually implement it in memory:

Notice how we’re free to store our nodes wherever we can find two open slots in memory. They don’t have to be next to each other. They don’t even have to be in order :

“But that’s not cache-friendly,” you may be thinking. Good point! We’ll get to that.

The first node of a linked list is called the head , and the last node is usually called the tail .

Confusingly, some people prefer to use “tail” to refer to everything after the head of a linked list. In an interview it’s fine to use either definition. Briefly say which definition you’re using, just to be clear.

It’s important to have a pointer variable referencing the head of the list—otherwise we’d be unable to find our way back to the start of the list!

We’ll also sometimes keep a pointer to the tail. That comes in handy when we want to add something new to the end of the linked list. In fact, let’s try that out:

Suppose we wanted to add an “S” to the end, to make it “LOGS”. How would we do that?

Easy. We just put it in a new node:

And tweak some pointers:

1. Grab the last letter, which is “G”. Our tail pointer lets us do this in O(1)O(1) time.

1. Point the last letter’s next to the letter we’re appending (“S”).

1. Update the tail pointer to point to our new last letter, “S”.

That’s O(1)O(1) time.

Why is it O(1)O(1) time? Because the runtime doesn’t get bigger if the string gets bigger. No matter how many characters are in our string, we still just have to tweak a couple pointers for any append.

Now, what if instead of a linked list, our string had been a dynamic array ? We might not have any room at the end, forcing us to do one of those doubling operations to make space:

So with a dynamic array, our append would have a worst-case time cost of O(n)O(n).

Linked lists have worst-case O(1)O(1)-time appends, which is better than the worst-case O(n)O(n) time of dynamic arrays.

That worst-case part is important. The average case runtime for appends to linked lists and dynamic arrays is the same: O(1)O(1).

Now, what if we wanted to pre pend something to our string? Let’s say we wanted to put a “B” at the beginning.

For our linked list, it’s just as easy as appending. Create the node:

And tweak some pointers:

1. Point “B”'s next to “L”.
2. Point the head to “B”.

Bam. O(1)O(1) time again.

But if our string were a dynamic array

And we wanted to add in that “B”:

Eep. We have to make room for the “B”!

We have to move each character one space down:

Now we can drop the “B” in there:

What’s our time cost here?

It’s all in the step where we made room for the first letter. We had to move all nn characters in our string. One at a time. That’s O(n)O(n) time.

So linked lists have faster pre pends (O(1)O(1) time) than dynamic arrays (O(n)O(n) time).

No “worst case” caveat this time—prepends for dynamic arrays are always O(n)O(n) time. And prepends for linked lists are always O(1)O(1) time.

These quick appends and prepends for linked lists come from the fact that linked list nodes can go anywhere in memory. They don’t have to sit right next to each other the way items in an array do.

So if linked lists are so great, why do we usually store strings in an array? Because arrays have O(1)O(1)-time lookups. And those constant-time lookups come from the fact that all the array elements are lined up next to each other in memory.

Lookups with a linked list are more of a process, because we have no way of knowing where the iith node is in memory. So we have to walk through the linked list node by node, counting as we go, until we hit the iith item.

def get_ith_item_in_linked_list(head, i):
if i < 0:
raise ValueError("i can't be negative: %d" % i)

current_position = 0
while current_node:
if current_position == i:
# Found it!
return current_node

# Move on to the next node
current_node = current_node.next
current_position += 1

raise ValueError('List has fewer than i + 1 (%d) nodes' % (i + 1))


That’s i + 1i+1 steps down our linked list to get to the iith node (we made our function zero-based to match indices in arrays). So linked lists have O(i)O(i)-time lookups. Much slower than the O(1)O(1)-time lookups for arrays and dynamic arrays.

Not only that— walking down a linked list is not cache-friendly. Because the next node could be anywhere in memory, we don’t get any benefit from the processor cache. This means lookups in a linked list are even slower.

So the tradeoff with linked lists is they have faster prepends and faster appends than dynamic arrays, but they have slower lookups.

## Hash tables

Quick lookups are often really important. For that reason, we tend to use arrays (O(1)O(1)-time lookups) much more often than linked lists (O(i)O(i)-time lookups).

For example, suppose we wanted to count how many times each ASCII character appears in Romeo and Juliet. How would we store those counts?

We can use arrays in a clever way here. Remember—characters are just numbers. In ASCII (a common character encoding) ‘A’ is 65, ‘B’ is 66, etc.

So we can use the character('s number value) as the index in our array, and store the count for that character at that index in the array:

With this array, we can look up (and edit) the count for any character in constant time. Because we can access any index in our array in constant time.

Something interesting is happening here—this array isn’t just a list of values. This array is storing two things: characters and counts. The characters are implied by the indices.

So we can think of an array as a table with two columns …except you don’t really get to pick the values in one column (the indices)—they’re always 0, 1, 2, 3, etc.

But what if we wanted to put any value in that column and still get quick lookups?

Suppose we wanted to count the number of times each word appears in Romeo and Juliet. Can we adapt our array?

Translating a character into an array index was easy. But we’ll have to do something more clever to translate a word (a string) into an array index…

Here’s one way we could do it:

Grab the number value for each character and add those up.

The result is 429. But what if we only have 30 slots in our array? We’ll use a common trick for forcing a number into a specific range: the modulus operator (%). ↴ Modding our sum by 30 ensures we get a whole number that’s less than 30 (and at least 0):

429 : % : 30 = 9429%30=9

Bam. That’ll get us from a word (or any string) to an array index.

This data structure is called a hash table or hash map . In our hash table, the counts are the values and the words (“lies,” etc.) are the keys (analogous to the indices in an array). The process we used to translate a key into an array index is called a hashing function .

The hashing functions used in modern systems get pretty complicated—the one we used here is a simplified example.

Note that our quick lookups are only in one direction—we can quickly get the value for a given key, but the only way to get the key for a given value is to walk through all the values and keys.

Same thing with arrays—we can quickly look up the value at a given index, but the only way to figure out the index for a given value is to walk through the whole array.

One problem—what if two keys hash to the same index in our array? Look at “lies” and “foes”:

They both sum up to 429! So of course they’ll have the same answer when we mod by 30:

429 : % : 30 = 9429%30=9

So our hashing function gives us the same answer for “lies” and “foes.” This is called a hash collision . There are a few different strategies for dealing with them.

Here’s a common one: instead of storing the actual values in our array, let’s have each array slot hold a pointer to a linked list holding the counts for all the words that hash to that index:

One problem—how do we know which count is for “lies” and which is for “foes”? To fix this, we’ll store the word as well as the count in each linked list node:

“But wait!” you may be thinking, “Now lookups in our hash table take O(n)O(n) time in the worst case, since we have to walk down a linked list.” That’s true! You could even say that in the worst case every key creates a hash collision, so our whole hash table degrades to a linked list .

In industry though, we usually wave our hands and say collisions are rare enough that on average lookups in a hash table are O(1)O(1) time . And there are fancy algorithms that keep the number of collisions low and keep the lengths of our linked lists nice and short.

But that’s sort of the tradeoff with hash tables. You get fast lookups by key…except some lookups could be slow. And of course, you only get those fast lookups in one direction—looking up the key for a given value still takes O(n)O(n) time.

## Summary

Arrays have O(1)O(1)-time lookups. But you need enough uninterrupted space in RAM to store the whole array. And the array items need to be the same size.

But if your array stores pointers to the actual array items (like we did with our list of baby names), you can get around both those weaknesses. You can store each array item wherever there’s space in RAM, and the array items can be different sizes. The tradeoff is that now your array is slower because it’s not cache-friendly.

Another problem with arrays is you have to specify their sizes ahead of time. There are two ways to get around this: dynamic arrays and linked lists . Linked lists have faster appends and prepends than dynamic arrays, but dynamic arrays have faster lookups.

Fast lookups are really useful, especially if you can look things up not just by indices (0, 1, 2, 3, etc.) but by arbitrary keys (“lies”, “foes”…any string ). That’s what hash tables are for. The only problem with hash tables is they have to deal with hash collisions, which means some lookups could be a bit slow.

Each data structure has tradeoffs. You can’t have it all.

So you have to know what’s important in the problem you’re working on. What does your data structure need to do quickly ? Is it lookups by index? Is it appends or prepends?

Once you know what’s important, you can pick the data structure that does it best.

# Logarithms

## What logarithm even means

Here’s what a logarithm is asking:

"What power must we raise this base to, in order to get this answer?"

So if we say:

\log_{10}{100}log10​100

The 10 is called the base (makes sense—it’s on the bottom). Think of the 100 as the “answer.” It’s what we’re taking the log of . So this expression would be pronounced “log base 10 of 100.”

And all it means is, “What power do we need to raise this base (1010) to, to get this answer (100100)?”

10^x = 10010x=100

What xx gets us our result of 100100? The answer is 22:

10^2 = 100102=100

So we can say:

\log_{10}{100} = 2log10​100=2

The “answer” part could be surrounded by parentheses, or not. So we can say \log_{10}{(100)}log10​(100) or \log_{10}{100}log10​100. Either one’s fine.

## What logarithms are used for

The main thing we use logarithms for is solving for xx when xx is in an exponent .

So if we wanted to solve this:

10^x = 10010x=100

We need to bring the xx down from the exponent somehow. And logarithms give us a trick for doing that.

We take the \log_{10}log10​ of both sides (we can do this—the two sides of the equation are still equal):

\log_{10}{10^x} = \log_{10}{100}log10​10x=log10​100

Now the left-hand side is asking, “what power must we raise 1010 to in order to get 10^x10x?” The answer, of course, is xx. So we can simplify that whole left side to just “xx”:

x = \log_{10}{100}x=log10​100

We’ve pulled the xx down from the exponent!

Now we just have to evaluate the right side. What power do we have to raise 1010 to in order to get 100100? The answer is still 22.

x = 2x=2

That’s how we use logarithms to pull a variable down from an exponent.

## Logarithm rules

These are helpful if you’re trying to do some algebra stuff with logs.

Simplification: \log_{b}{(b^x)} = xlogb​(bx)=x . . . Useful for bringing a variable down from an exponent.

Multiplication: \log_{b}{(x*y)} = \log_{b}{(x)} + \log_{b}{(y)}logb​(x∗y)=logb​(x)+logb​(y)

Division: \log_{b}{(x/y)} = \log_{b}{(x)} - \log_{b}{(y)}logb​(x/y)=logb​(x)−logb​(y)

Powers: \log_{b}{(x^y)} = y * \log_{b}{(x)}logb​(xy)=y∗logb​(x)

Change of base: \log_{b}{(x)} = \frac{\log_{c}{(x)} }{\log_{c}{(b)} }logb​(x)=logc​(b)logc​(x)​ . . . Useful for changing the base of a logarithm from bb to cc.

## Where logs come up in algorithms and interviews

"How many times must we double 1 before we get to nn" is a question we often ask ourselves in computer science. Or, equivalently, "How many times must we divide nn in half in order to get back down to 1?"

Can you see how those are the same question? We’re just going in different directions! From nn to 1 by dividing by 2, or from 1 to nn by multiplying by 2. Either way, it’s the same number of times that we have to do it.

The answer to both of these questions is \log_{2}{n}log2​n.

It’s okay if it’s not obvious yet why that’s true. We’ll derive it with some examples.

## Logarithms in binary search (ex. 1)

This comes up in the time cost of binary search , which is an algorithm for finding a target number in a sorted list. The process goes like this:

1. Start with the middle number: is it bigger or smaller than our target number? Since the list is sorted, this tells us if the target would be in the left half or the right half of our list.
2. We’ve effectively divided the problem in half . We can “rule out” the whole half of the list that we know doesn’t contain the target number.
3. Repeat the same approach (of starting in the middle) on the new half-size problem . Then do it again and again, until we either find the number or “rule out” the whole set.

In code:

def binary_search(target, nums):
"""See if target appears in nums"""
# We think of floor_index and ceiling_index as "walls" around
# the possible positions of our target so by -1 below we mean
# to start our wall "to the left" of the 0th index
# (we *don't* mean "the last index")
floor_index = -1
ceiling_index = len(nums)

# If there isn't at least 1 index between floor and ceiling,
# we've run out of guesses and the number must not be present
while floor_index + 1 < ceiling_index:
# Find the index ~halfway between the floor and ceiling
# We use integer division, so we'll never get a "half index"
distance = ceiling_index - floor_index
half_distance = distance / 2
guess_index = floor_index + half_distance

guess_value = nums[guess_index]
if guess_value == target:
return True

if guess_value > target:
# Target is to the left, so move ceiling to the left
ceiling_index = guess_index
else:
# Target is to the right, so move floor to the right
floor_index = guess_index

return False


So what’s the time cost of binary search? The only non-constant part of our time cost is the number of times our while loop runs. Each step of our while loop cuts the range (dictated by floor_index and ceiling_index) in half, until our range has just one element left.

So the question is, "how many times must we divide our original list size (nn) in half until we get down to 1?"

n * \frac{1}{2} * \frac{1}{2} * \frac{1}{2} * \frac{1}{2} * … = 1n∗21​∗21​∗21​∗21​∗…=1

How many \frac{1}{2}21​’s are there? We don’t know yet, but we can call that number xx:

n * (\frac{1}{2})^x = 1n∗(21​)x=1

Now we solve for xx:

n * \frac{1^x}{2^x} = 1n∗2x1x​=1n * \frac{1}{2^x} = 1n∗2x1​=1\frac{n}{2^x} = 12xn​=1n = 2^xn=2x

Now to get the xx out of that exponent! We’ll use the same trick as last time.

Take the \log_{2}log2​ of both sides…

\log_{2}{n} = \log_{2}{2^x}log2​n=log2​2x

The right hand side asks, “what power must we raise 22 to, to get 2^x2x?” Well, that’s just xx.

\log_{2}{n} = xlog2​n=x

So there it is. The total time cost of binary search is O(\log_{2}{n})O(log2​n).

## Logarithms in sorting (ex. 2)

Sorting costs O(n\log_{2}{n})O(nlog2​n) time in general . More specifically, O(n\log_{2}{n})O(nlog2​n) is the best worst-case runtime we can get for sorting.

That’s our best runtime for comparison-based sorting. If we can tightly bound the range of possible numbers in our list, we can use a hash map do it in O(n)O(n) time with counting sort.

The easiest way to see why is to look at merge sort. In merge sort, the idea is to divide the list in half, sort the two halves, and then merge the two sorted halves into one sorted whole. But how do we sort the two halves? Well, we divide them in half, sort them, and merge the sorted halves…and so on.

def merge_sort(list_to_sort):
# Base case: lists with fewer than 2 elements are sorted
if len(list_to_sort) < 2:
return list_to_sort

# Step 1: divide the list in half
# We use integer division, so we'll never get a "half index"
mid_index = len(list_to_sort) / 2
left  = list_to_sort[:mid_index]
right = list_to_sort[mid_index:]

# Step 2: sort each half
sorted_left  = merge_sort(left)
sorted_right = merge_sort(right)

# Step 3: merge the sorted halves
sorted_list = []
current_index_left = 0
current_index_right = 0

# sortedLeft's first element comes next
# if it's less than sortedRight's first
# element or if sortedRight is exhausted
while len(sorted_list) < len(left) + len(right):
if ((current_index_left < len(left)) and
(current_index_right == len(right) or
sorted_left[current_index_left] < sorted_right[current_index_right])):
sorted_list.append(sorted_left[current_index_left])
current_index_left += 1
else:
sorted_list.append(sorted_right[current_index_right])
current_index_right += 1
return sorted_list


So what’s our total time cost? O(n\log_{2}{n})O(nlog2​n). The \log_{2}{n}log2​n comes from the number of times we have to cut nn in half to get down to sublists of just 1 element (our base case). The additional nn comes from the time cost of merging all nn items together each time we merge two sorted sublists.

### Logarithms in binary trees (ex. 3)

In a binary tree, each node has two or fewer children.

The tree above is special because each “level” or “tier” of the tree is full. There aren’t any gaps. We call such a tree " perfect ."

One question we might ask is, if there are nn nodes in total , what’s the tree’s height (hh)? In other words, how many levels does the tree have?

If we count the number of nodes on each level , we can notice that it successively doubles as we go:

That brings back our refrain, “how many times must we double 1 to get to nn.” But this time, we’re not doubling 1 to get to nn; nn is the total number of nodes in the tree . We’re doubling 1 until we get to . . . the number of nodes on the last level of the tree.

How many nodes does the last level have? Look back at the diagram above.

The last level has about half of the total number of nodes on the tree. If you add up the number of nodes on all the levels except the last one, you get about the number of nodes on the last level—1 less.

1 + 2 + 4 + 8 = 151+2+4+8=15

The exact formula for the number of nodes on the last level is:

\frac{n+1}{2}2n+1​

Where does the +1 come from?

The number of nodes in our perfect binary tree is always odd. We know this because the first level always has 1 node, and the other levels always have an even number of nodes. Adding a bunch of even numbers always gives us an even number, and adding 1 to that result always gives us an odd number.

Taking half of an odd number gives us a fraction. So if the last level had exactly half of our nn nodes, it would have to have a “half-node.” But that’s not a thing.

Instead, it has the “rounded up” version of half of our odd nn nodes. In other words, it has the exact half of the one-greater-and-thus- even number of nodes n+1n+1. Hence \frac{n+1}{2}2n+1​

So our height (hh) is the same as “the number of times we have to double 1 to get to \frac{n+1}{2}2n+1​.” So we can phrase this as a logarithm:

h \approx \log_{2}{(\frac{n+1}{2})}h≈log2​(2n+1​)

One adjustment: Consider a perfect, 2-level tree. There are 2 levels overall, but the “number of times we have to double 1 to get to 2” is just 1 . Our height is in fact one more than our number of doublings. So we add 1:

h = \log_{2}{(\frac{n+1}{2})} + 1h=log2​(2n+1​)+1

We can apply some of our logarithm rules to simplify this:

h = \log_{2}{(\frac{n+1}{2})} + 1h=log2​(2n+1​)+1h = \log_{2}{(n+1)} - \log_{2}{(2)} + 1h=log2​(n+1)−log2​(2)+1h = \log_{2}{(n+1)} - 1 + 1h=log2​(n+1)−1+1h = \log_{2}{(n+1)}h=log2​(n+1)

## Conventions with bases

Sometimes people don’t include a base. In computer science, it’s usually implied that the base is 2. So \log{n}logn generally means \log_{2}{n}log2​n.

Some folks might remember that in most other maths, an unspecified base is implied to be 10. Or sometimes the special constant ee. (Don’t worry if you don’t know what ee is.)

There’s a specific notation for log base 2 that’s sometimes used: \lglg. So we could say \lg{n}lgn, or n\lg{n}nlgn (which comes up a lot in sorting). We use this notation a lot on Interview Cake, but it’s worth noting that not everyone uses it.

Some folks might know there’s a similar-ish specific notation for log base ee: \lnln (pronounced “natural log”).

In big O notation the base is considered a constant. So folks usually don’t include it. People usually say O(\log{n})O(logn), not O(\log_{2}{n})O(log2​n),

But people might still use the special notation \lg{n}lgn, as in O(\lg{n})O(lgn). It saves us from having to write an “o”