r/learnprogramming • u/ExplosiveTortuga • Jan 31 '18
Awesome cheat sheet for must know data structures and algorithms
I was searching for materials to review for an upcoming interview and I found the Big-O Cheat Sheet. It's got Big-O information and quick links to all of your basic data structures and algorithms. This is a great resource to check when you're starting a new project or preparing for an interview.
39
u/Dangerpaladin Jan 31 '18
I've got that poster framed, not for reference just so that any females that wander into my house know I am not available for mating purposes.
9
67
u/tzaeru Jan 31 '18
..And then you learn that due to the CPU cache, what you want to use 99% of time is a flat array or a hashmap no matter the theoretical ramifications.
27
Jan 31 '18
Hey, can you expand on this please, this sounds really interesting and I haven't heard it before.
74
u/tzaeru Jan 31 '18
The basic gist is that there's a little bit of memory cache on the CPU itself. For example, the i3-8350K has about 8 megabytes of cache.
When you're processing data, it's much faster to retrieve the data if it's in the CPU cache, talking of like, 100x faster compared to retrieving it from RAM. When the CPU tries to access the main memory, it will basically always first check if the data is already in the cache. If it isn't, it'll retrieve the data from RAM. This is called cache miss. Minimizing cache misses is a major goal of compilers in what goes to producing high-performance code.
Now a flat array is relatively easy to keep in the cache. Copying contigous blocks of memory into the cache is easier for the CPU than copying a similar amount of scattered memory positions, and it's also easier for the CPU to check if a given memory address is in the cache if it can check for ranges of memory that are in the cache. As such, flat arrays, which have a contiguous memory structure (say, you have memory addresses 0 to 100 for the array), are easy to fit in the CPU cache. Meanwhile, let's say, linked lists are not, since the memory they have is scattered all over. You can have root node at memory address 0, pointing to a node at memory address 80, pointing to a node at memory address 126, and so forth. This is not easy to fit into the cache, so the CPU is slower in processing this data.
There are data structures that have been specifically designed with constraints like the above in mind, such as the B-tree. Compared to an ordinary self-balancing binary tree, a B-tree holds blocks of data in its nodes. Even then, though, there's still other reasons for why a simple hashmap or a flat array still may triumph in real world use cases. Compilers can often optimize hashmaps and flat array usage better and do better work with branch prediction and whatnot.
Here's a good though quite low-level video about the subject, here's a pretty good answer at StackOverflow (though do keep in mind that in reality, optimizing memory access is rarely something you needed to do. This is only useful when working on very high-performance code, which most of us do not work with) and here's some benchmarking, for Vector, List and Deque. You can see that the most plausible real case where List is actually better is if the data elements being stored are very large or otherwise very unusual. And here's another benchmark comparing some C++ data structures. You can see that hashmaps triumph in this particular test, though it's a very specific kind of a test.
8
u/WikiTextBot btproof Jan 31 '18
CPU cache
A CPU cache is a hardware cache used by the central processing unit (CPU) of a computer to reduce the average cost (time or energy) to access data from the main memory. A cache is a smaller, faster memory, closer to a processor core, which stores copies of the data from frequently used main memory locations. Most CPUs have different independent caches, including instruction and data caches, where the data cache is usually organized as a hierarchy of more cache levels (L1, L2, etc.).
All modern (fast) CPUs (with few specialized exceptions) have multiple levels of CPU caches.
B-tree
In computer science, a B-tree is a self-balancing tree data structure that keeps data sorted and allows searches, sequential access, insertions, and deletions in logarithmic time. The B-tree is a generalization of a binary search tree in that a node can have more than two children (Comer 1979, p. 123). Unlike self-balancing binary search trees, the B-tree is optimized for systems that read and write large blocks of data.
[ ^PM | Exclude ^me | Exclude from ^subreddit | FAQ / ^Information | ^Source | ^Donate ] Downvote to remove | v0.28
3
u/PM_RUNESCAP_P2P_CODE Feb 10 '18
Hey! Just wanted to say thanks for all the links and explanation. I really learnt something new today, and it was very useful and fun :)
1
u/Bolitho Jan 31 '18
Isn't B-Tree just a shorthand for Balanced Tree? A binary balanced tree is therefore only one special case, where the amount of leaves is limited to two. So why call it ordinary?
2
u/tzaeru Jan 31 '18 edited Jan 31 '18
I suppose it's just a history thing, IIRC B-trees as described by the wikipedia page above were invented after binary search trees and self-balancing binary search trees (such as AVL trees), hence why self-balancing binary search tree is "ordinary" and B-tree is "special".
But you're right, could as well consider it the other way.
14
u/mka696 Jan 31 '18
Your Cpu takes ~1-4 nanoseconds to access its L1 or L2 cache, while it takes ~100 nanoseconds to access Ram. Something like a linked list is a series of nodes that link to each other's memory locations, meaning you always have to access them through Ram. An array is contiguous in memory, so the data can be first stored in the cache, meaning much faster data retrieval.
2
Jan 31 '18
I assume this an optimization the compiler's optimizer will make if it can?
3
u/tzaeru Feb 01 '18
To add to the other answer, the compiler can't directly control the caching behaviour of the CPU. Each time the CPU retrieves something from RAM, it'll grab a whole fixed-size block of memory with it and cache all of that. What the compiler can do is try to make sure that data, which is likely to be processed at roughly the same time, is also organized next to each other in main memory.
Data structures like linked list are very difficult to organize in this way, since the compiler can not know how large the data structure is going to be and it can not know which data is eventually linked to the list until runtime. I suppose it could attempt to reorganize the data every now and then, but this would have quite unexpected performance drawbacks, if even possible in some cases.
Then, in some cases, you do end up with the linked list in contiguous memory, which is actually decently likely if you allocate all of it in one go, in a single thread. But even then, there are other somewhat unintuitive performance drawbacks related to the CPU's ability of executing instructions in parallel, like described in this Stackoverflow answer.
2
u/mka696 Jan 31 '18
Yes. Compiler's will do their best to make this optimization. It's not a good idea to try to out-optimize the compiler, but choosing the right data structures for the job is one of the things you can do to make the compiler's job easier.
12
u/b4ux1t3 Jan 31 '18
Seriously.
Not to mention the fact that most compilers these days a re a lot smarter than the people using them think they are.
This is great for someone taking an intro CS class, but "learning to program" doesn't necessarily mean big O notation anymore.
15
u/Patman128 Jan 31 '18
"learning to program" doesn't necessarily mean big O notation anymore
Honestly, the important thing is that you understand how these things work. If you know how a hash map works it's pretty obvious what its Big-O characteristics are. Just memorizing Big-O is doing yourself a disservice.
2
u/b4ux1t3 Jan 31 '18
Yeah, that's kind of what I'm going for. It's good to know "if I do things this way, it will take longer", but there's no real reason for you to have a reference table for each individual algorithm.
Unless you're literally designing algorithms for things like compilers or crypto. Then it's a different story. But /r/learnprogramming is more of a 101 level thing, and you don't need an in depth understanding of big O to write little web apps.
12
4
Jan 31 '18
Potentially quite useful. Thanks for the link!
What I take from the first chart is that you can probably do most jobs very well with nothing but arrays, stacks, and hash tables.
10
u/EmersonEXE Jan 31 '18
Anyone know a good link or video that can help me wrap my head around this stuff? I've read stuff on it before but it hasn't quite clicked for me.
17
6
u/chain_letter Jan 31 '18
This is actually best viewed as a tight list of important concepts. You can pick a single label, like the Stack structure, and have a great point to start googling, reading, doing exercises, and exploring applications.
Some concepts are more complex than others, and how long until one clicks is different for everyone. There's probably something you learned that seemed easy that a professional today once struggled with, so don't get discouraged.
3
u/PPewt Jan 31 '18
Back insertion/deletion on arrays is O(1) (amortized), not sure why the site doesn't list that. They are already happy to list amortized times (hash tables) and are already happy to list times for special cases (insertion/deletion into stack/queue/LL).
Skip list average case space is O(n). It seems like an oversight to leave this off just because skip lists are the only DS there with a different average vs worst case space cost.
3
u/buckeyebrad24 Jan 31 '18
This is so convenient. Just now covering this in CS, and I'll definitely be using this as a reference.
5
u/Lacobus Jan 31 '18
Just did my first lecture on this yesterday. To say it went over my head is an understatement. Thanks OP.
2
2
u/carie_bear Jan 31 '18
Omg where was this when I took dat structures and algorithms last year. This is beautiful.
18
Jan 31 '18
Don't make the same mistake I did fellas. It's log base 2 on there, not log base e or log base 10
102
u/thirdhaf Jan 31 '18
Those all only differ by a constant factor so they are equivalent for complexity analysis purposes.
10
47
19
u/gaj7 Jan 31 '18
It would be base 2 for, say, binary trees. In a 3-ary tree, any log complexity operation would be log base 3. But as /u/thirdhaf pointed out, logarithms are linearly related, so any base works for big O purposes.
13
u/supermilch Jan 31 '18
log_n(x) = log(x) / log(n)is always good to keep in mind, especially if you need some exotic base or for some reason the one you need isn't available in the standard library of whatever language you're using-10
Jan 31 '18
If I use log base 2, Merge Sort is slower than MSD Radix Sort. But if I use log base 10, Merge Sort ends up being faster. So it makes a difference...
Merge Sort IS log base 2, right???
15
u/KronenR Jan 31 '18
That difference doesn't matter at all O(2n) is equivalent complexity to O(100n) they both are O(n), so log base 2 or log base 10 doesn't matter at all both logs have O(log n) complexity. Faster on the scale you are thinking doesn't matter at all
6
Jan 31 '18
You seem to be severely confused. What is
log of 10 to base 2? It's a constant. What'slog 10 to base 10? Yet another constant. In the first stage of algorithmics, we don't bother about constants. When it comes down to practical applications, the hidden constants can be important, but that comes much later and hardly ever in any programming interviews. For example, both Bubble Sort and Insertion Sort are O(n2), but which would you use for sorting small datasets? Insertion Sort, of course, since the constants are much lower. However, in terms of algorithmic complexity, both are in the same league.EDIT: About your specific question about Merge Sort, yes, it is log to base 2 since you divide the problem set into halves at each stage. Look at logarithms as the inverse of exponents.
12
u/oh_bro_no Jan 31 '18
Why is this comment still upvoted? It's factually incorrect. No offense to the author, but someone new might get confused by this.
9
Jan 31 '18
It's an inherent failure of
learnXorXquestionsorXcareeradvicecommunities: most of the readers don't know the material well, and will upvote anything that seems to be helpful.With development the failure is doubled because many hiring managers and Internet 'authorities' don't know the material well either. I wouldn't be surprised if OP's tidbit came directly from an interview, or a source claiming to be interview advice.
For the new folks - Big O is a very, very, very general measure of complexity. It doesn't dive into specific numbers, other than exponents. If your Big O contains a number that is not an exponent, you are wrong. (If you're right, you're a senior engineer at Google or Facebook and you should trust yourself over random people on the Internet.)
2
u/gaj7 Jan 31 '18
I think the real problem is that you are memorizing complexities rather than understanding them. The reason the average complexity for adding an element of a binary search tree is log2 n is because, on average, the tree will be balanced, and a balanced binary tree has a height of log2 n. Since the add function traverses from root to leaf, the dominating step of that function will be that approximately log2 n length traversal.
1
u/daniel_h_r Jan 31 '18
It's only the order what matters, the constant are irrelevant.
The difference between bases is only a multiplicative constant.
3
u/Sif_ Jan 31 '18
As someone just finishing 'head first javascript'...wtf am i even looking at here? lol
2
1
u/BlackCatCode Jan 31 '18
when it says stack/queue are O(n) to access, do they mean accessing a specific index other than the top element? Is that why it's not O(1)? Or am I overlooking something super obvious? I always thought accessing specific indices on these structures was something that's not technically even part of the data structure and shouldn't be possible, but just something many languages give you the ability to do because they're built on top of arrays anyway so why not give users that ability.
2
u/PPewt Jan 31 '18
when it says stack/queue are O(n) to access, do they mean accessing a specific index other than the top element? Is that why it's not O(1)? Or am I overlooking something super obvious? I always thought accessing specific indices on these structures was something that's not technically even part of the data structure and shouldn't be possible, but just something many languages give you the ability to do because they're built on top of arrays anyway so why not give users that ability.
They should really be labeled N/A since, as you said, the operations aren't supported. That said, they definitely shouldn't be labeled O(1): while Stacks & Queues are usually implemented using arrays since that turns out to be the most practical, you could in theory implement them using a linked list or something.
1
0
0
271
u/4THOT Jan 31 '18
>open link
>see it's already bookmarked
>feelsbadman
Here's a site with a more accessible approach to explaining Big-O