Your standard library: C++ STL, Java Collections, Python built-ins
1 Pieces every problem needs
Most problems need the same few tools. We collect values in a list that grows. We ask "have we seen this value before?" thousands of times. We put values in order, or keep taking the smallest one.
Every language ships these ready-made in its standard library: the code that comes with the language. In C++, the part we use is the Standard Template Library (STL).
Each section shows one structure in all seven languages, with each line's result in a comment. The C++ code leaves out the headers, such as <vector> and <queue>.
2 The dynamic array
A plain array has a fixed size, but often we do not know the size in advance. A dynamic array grows as we add values at the end. Underneath it is still an array, so reading any index takes one step.
C++
Store what append returns. append may build a new slice, so we always write nums = append(nums, 6).
get and set, not brackets. An ArrayList has no nums[i].
- Adding or removing at the end: about one step. Now and then the array moves to a bigger block of memory. This is rare, so it averages out.
- Adding or removing at the front: about n steps. Every value shifts one place. In a loop over 10⁵ values, that adds up to around 10¹⁰ steps, and the code gets Time Limit Exceeded (TLE).
3 The hash map
A hash map stores pairs of a key and a value, such as a word and its count. Given a key, it finds the value in about one step, however many pairs it holds. A dynamic array would check its values one by one.
C++
A missing key gets added. counts["kiwi"] quietly adds kiwi with the value 0, so the code checks with count first.
Order. A loop gives the keys in no fixed order. The sorted map is map.
A missing key gives null. Storing null in an int crashes, so the code reads with getOrDefault.
Order. A loop gives the keys in no fixed order. The sorted map is TreeMap.
A missing key is a Runtime Error. counts["kiwi"] stops the program, so the code reads with get("kiwi", 0).
Order. A loop gives the keys in the order they were added. There is no sorted map built in, so we sort the keys when we need them in order.
A missing key gives undefined. The code reads with ?? 0 to get 0 instead.
Order. A loop gives the keys in the order they were added. There is no sorted map built in, so we sort the keys when we need them in order.
A missing key reads as 0. No check is needed for a count.
Order. A loop gives the keys in no fixed order. There is no sorted map built in, so we sort the keys when we need them in order.
A missing key is a Runtime Error. counts["kiwi"] stops the program, so the code reads with get and unwrap_or(0).
Order. A loop gives the keys in no fixed order. The sorted map is BTreeMap.
A missing key is a Runtime Error. counts["kiwi"] stops the program, so the code reads with GetValueOrDefault.
Order. A loop gives the keys in no fixed order. The sorted map is SortedDictionary.
- Cost: about one step to put, get, check or remove a key.
- Sorted map. Where a language has one, it keeps the keys sorted, at about log n steps an operation.
4 The hash set
A hash set keeps keys with no values. It answers one question: is this key here? We use it to skip values we have already seen, and to count different values. Building one from an array drops the repeats.
C++
No set type. We use a map from the key to bool. A missing key reads as false.
- Cost: about one step to add, check or remove. Building from n values takes about n steps.
- No order, as with the hash map. The sorted version is
set.
5 Sorting, and sorting by a rule
Every language has a built-in sort. It takes about n log n steps: around 2 × 10⁶ for 10⁵ values, well under a second.
C++
Always pass a compare function. With none, sort compares values as text, so [8, 3, 10, 5].sort() gives [10, 3, 5, 8].
A plain int[] sorts only smallest first. For largest first, use a List<Integer> as above, or read the sorted array from the end.
sorted returns a new list. sort changes the list itself.
For an order of our own, such as shortest word first with ties in alphabetical order, we tell the sort how to compare two values a and b. The note under the code says how each language asks.
C++
True or false. The comparator returns true when a must come before b.
A sign. Negative means a goes first, positive means b goes first, and zero means a tie.
A sign. Negative means a goes first, positive means b goes first, and zero means a tie.
A sign. Negative means a goes first, positive means b goes first, and zero means a tie.
A sign. Negative means a goes first, positive means b goes first, and zero means a tie.
An Ordering. Less means a goes first, Greater means b goes first, and Equal means a tie.
A key. A key function turns each value into a key, and the sort orders the keys. Here the key is (len(word), word). Pairs compare by the first item, then by the second on a tie.
6 The stack
A stack hands back the value added last, like a pile of plates. We add and take from the top only. We use one when the latest value must be handled first, as in matching brackets.
C++
No stack type needed. A dynamic array does the job, and its end is the top.
No stack type needed. A dynamic array does the job, and its end is the top.
No stack type needed. A dynamic array does the job, and its end is the top.
No stack type needed. A dynamic array does the job, and its end is the top.
pop returns nothing. Read top() first, then call pop().
- Cost: about one step to push, look at the top, or pop.
- Check for empty first. Popping an empty stack is a Runtime Error in most languages. JavaScript returns
undefinedinstead, which hides the bug.
7 The queue and the deque
A queue hands back the value added first, like a line at a ticket counter. Values join at the back and leave from the front. A deque, short for double-ended queue, adds and removes at both ends.
C++
No queue or deque. shift() removes the front but takes about n steps, so a queue of 10⁵ values gets TLE. Keep the index of the front instead, as the code does.
A slice for a queue, container/list for a deque. A list holds values of any type, so we read one back with dq.Front().Value.(int).
LinkedList as the deque. C# has no deque type.
- Cost: about one step for each add and remove, at either end.
8 The heap
A heap, also called a priority queue, always hands back the smallest value, or always the largest. It keeps only the top ready, not every value sorted, so it is cheaper than sorting again after each add. We use one for "the k largest values" or "always take the cheapest next".
C++
Largest on top by default. For smallest on top, pass greater<int> as the third type.
Smallest on top by default. For largest on top, pass Collections.reverseOrder().
Smallest on top. For largest on top, push -x, and negate again on the way out.
No heap. The Heaps topic builds one.
On top is whatever Less says. < puts the smallest on top, and > the largest.
Call heap.Push and heap.Pop. Our own Push and Pop only change the end of the slice. The package calls them and keeps the order.
Largest on top by default. For smallest on top, wrap each value in Reverse.
Smallest on top by default. For largest on top, pass a reversed Comparer.
A value and a priority. Enqueue takes both. For plain numbers we pass the number twice.
- Cost. Looking at the top takes one step. Adding and removing take about log n steps, around 17 for 10⁵ values.
9 Mistakes, and when to use which
- Searching a list instead of a set.
x in numson a Python list andlist.contains(x)in Java check values one by one. In a loop over 10⁵ values, that is around 10¹⁰ steps and TLE. A hash set makes each check about one step. - Changing a map or set while looping over it. In several languages, adding or removing keys inside the loop is a Runtime Error or a crash. Note the keys to change, then change them after the loop.
- C++:
<=in a comparator. A comparator must returnfalsefor two equal values. With<=,sortcan read past the end of the array and crash with a Runtime Error.
Most problems in this subtopic are a few lines once we pick the right piece:
| The problem needs | Reach for |
|---|---|
| a list of unknown length | dynamic array |
| "have we seen this?" or "how many different?" | hash set |
| "how many times?" or a value for each key | hash map |
| keys kept in sorted order | sorted map |
| values in an order | sort, with a rule if needed |
| the latest value first | stack |
| values in the order they came | queue |
| adding or removing at both ends | deque |
| the smallest or largest, again and again | heap |
The next lesson, on time and space complexity, gives these step counts a proper notation.
The habit to keep: in your language, write each code block above from memory once. Keep a short page of these calls until you no longer need it.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.