Reference
Data structures, in three languages
What each structure is called and how to push, pop, add, remove and look things up in Java, C++ (C++14) and Python. Keep it open while you solve. Costs are the usual time per operation.
Array and dynamic list
A fixed array has a set size. The growable list is what most problems use. Indexes start at 0.
| Operation | Java (int[] / ArrayList<Integer>) | C++ (int[] / vector<int>) | Python (list) | Cost |
|---|---|---|---|---|
| Create empty | List<Integer> a = new ArrayList<>(); | vector<int> a; | a = [] | O(1) |
| Create with size n, all 0 | int[] a = new int[n]; | vector<int> a(n, 0); | a = [0] * n | O(n) |
| Size | a.size() (array: a.length) | a.size() | len(a) | O(1) |
| Get by index | a.get(i) (array: a[i]) | a[i] | a[i] | O(1) |
| Set by index | a.set(i, x) (array: a[i] = x) | a[i] = x; | a[i] = x | O(1) |
| Add at the end | a.add(x) | a.push_back(x); | a.append(x) | O(1) amortised |
| Remove the last | a.remove(a.size() - 1) | a.pop_back(); | a.pop() | O(1) |
| Insert at index i | a.add(i, x) | a.insert(a.begin() + i, x); | a.insert(i, x) | O(n) |
| Remove at index i | a.remove(i) (an int index, not a value) | a.erase(a.begin() + i); | del a[i] | O(n) |
| Contains a value | a.contains(x) | find(a.begin(), a.end(), x) != a.end() | x in a | O(n) |
| Sort ascending | Collections.sort(a) (array: Arrays.sort(a)) | sort(a.begin(), a.end()); | a.sort() | O(n log n) |
| Reverse | Collections.reverse(a) | reverse(a.begin(), a.end()); | a.reverse() | O(n) |
| Smallest and largest | Collections.min(a) / Collections.max(a) | *min_element(a.begin(), a.end()) | min(a) / max(a) | O(n) |
| Copy | new ArrayList<>(a) (array: a.clone()) | vector<int> b = a; | b = a[:] | O(n) |
String
Java and Python strings cannot be changed in place. Use StringBuilder in Java, or a list of characters in Python, when you build one piece by piece.
| Operation | Java (String / StringBuilder) | C++ (string) | Python (str) | Cost |
|---|---|---|---|---|
| Length | s.length() | s.size() | len(s) | O(1) |
| Character at i | s.charAt(i) | s[i] | s[i] | O(1) |
| Substring from i up to j | s.substring(i, j) | s.substr(i, j - i) | s[i:j] | O(j - i) |
| Build by appending | sb.append(c) | s.push_back(c); or s += c; | parts.append(c) then "".join(parts) | O(1) each |
| Reverse | new StringBuilder(s).reverse().toString() | reverse(s.begin(), s.end()); | s[::-1] | O(n) |
| Find a piece | s.indexOf(t) (-1 if missing) | s.find(t) (string::npos if missing) | s.find(t) (-1 if missing) | O(n m) |
| Compare equal | s.equals(t) | s == t | s == t | O(n) |
| Char to its number | (int) c or c - 'a' | int(c) or c - 'a' | ord(c) | O(1) |
| Number to char | (char) ('a' + k) | char('a' + k) | chr(ord('a') + k) | O(1) |
| Digit char to int | c - '0' | c - '0' | int(c) | O(1) |
| To char array / list | s.toCharArray() | (a string already is one) | list(s) | O(n) |
Stack (last in, first out)
Java's old Stack class is slow and discouraged; use ArrayDeque. In C++ pop() only removes and returns nothing, so read top() first. In Python a plain list is the stack.
| Operation | Java (ArrayDeque<Integer>) | C++ (stack<int>) | Python (list) | Cost |
|---|---|---|---|---|
| Create | Deque<Integer> st = new ArrayDeque<>(); | stack<int> st; | st = [] | O(1) |
| Push | st.push(x) | st.push(x); | st.append(x) | O(1) |
| Look at the top | st.peek() (null if empty) | st.top() (empty stack is undefined) | st[-1] | O(1) |
| Pop the top | st.pop() (throws if empty) | st.pop(); (returns nothing) | st.pop() | O(1) |
| Is empty | st.isEmpty() | st.empty() | not st | O(1) |
| Size | st.size() | st.size() | len(st) | O(1) |
Queue (first in, first out)
Do not use a Python list as a queue, since removing from the front is O(n). In C++ pop() returns nothing, so read front() first.
| Operation | Java (ArrayDeque<Integer> (as Queue)) | C++ (queue<int>) | Python (collections.deque) | Cost |
|---|---|---|---|---|
| Create | Queue<Integer> q = new ArrayDeque<>(); | queue<int> q; | from collections import deque
q = deque() | O(1) |
| Add at the back | q.offer(x) (or add) | q.push(x); | q.append(x) | O(1) |
| Look at the front | q.peek() (null if empty) | q.front() | q[0] | O(1) |
| Remove from the front | q.poll() (null if empty) | q.pop(); (returns nothing) | q.popleft() | O(1) |
| Look at the back | (not available on Queue; use Deque peekLast()) | q.back() | q[-1] | O(1) |
| Is empty | q.isEmpty() | q.empty() | not q | O(1) |
| Size | q.size() | q.size() | len(q) | O(1) |
Deque (add and remove at both ends)
Used for sliding windows and monotonic structures. All end operations are O(1).
| Operation | Java (ArrayDeque<Integer>) | C++ (deque<int>) | Python (collections.deque) | Cost |
|---|---|---|---|---|
| Create | Deque<Integer> d = new ArrayDeque<>(); | deque<int> d; | d = deque() | O(1) |
| Add at the front | d.offerFirst(x) (or addFirst) | d.push_front(x); | d.appendleft(x) | O(1) |
| Add at the back | d.offerLast(x) (or addLast) | d.push_back(x); | d.append(x) | O(1) |
| Remove from the front | d.pollFirst() | d.pop_front(); | d.popleft() | O(1) |
| Remove from the back | d.pollLast() | d.pop_back(); | d.pop() | O(1) |
| Look at the front / back | d.peekFirst() / d.peekLast() | d.front() / d.back() | d[0] / d[-1] | O(1) |
Linked list
Problems give you the node class, so you work with next pointers directly. The library lists are for when you just need list behaviour.
| Operation | Java (your own ListNode (LinkedList class exists)) | C++ (your own ListNode (list<int> exists)) | Python (your own ListNode) | Cost |
|---|---|---|---|---|
| Node | class ListNode { int val; ListNode next; } | struct ListNode { int val; ListNode* next; }; | class ListNode: val, next | |
| Create a node | new ListNode(x) | new ListNode(x) | ListNode(x) | O(1) |
| Walk the list | for (ListNode p = head; p != null; p = p.next) | for (ListNode* p = head; p != nullptr; p = p->next) | p = head
while p: p = p.next | O(n) |
| Reach the next value | p.next.val | p->next->val | p.next.val | O(1) |
| Dummy head before the real head | ListNode dummy = new ListNode(0); dummy.next = head; | ListNode dummy(0); dummy.next = head; | dummy = ListNode(0, head) | O(1) |
Hash map (key to value)
Average O(1) per operation. In C++, m[key] creates the key with a default value if it is missing. Order is not kept.
| Operation | Java (HashMap<K, V>) | C++ (unordered_map<K, V>) | Python (dict) | Cost |
|---|---|---|---|---|
| Create | Map<Integer, Integer> m = new HashMap<>(); | unordered_map<int, int> m; | m = {} | O(1) |
| Put / overwrite | m.put(k, v) | m[k] = v; | m[k] = v | O(1) |
| Get | m.get(k) (null if missing) | m[k] (adds k with 0 if missing) or m.at(k) | m[k] (error if missing) | O(1) |
| Get with a default | m.getOrDefault(k, 0) | m.count(k) ? m[k] : 0 | m.get(k, 0) | O(1) |
| Has the key | m.containsKey(k) | m.count(k) > 0 (or m.find(k) != m.end()) | k in m | O(1) |
| Remove a key | m.remove(k) | m.erase(k); | del m[k] or m.pop(k, None) | O(1) |
| Add 1 to a counter | m.merge(k, 1, Integer::sum) | m[k]++; | m[k] = m.get(k, 0) + 1 | O(1) |
| Size | m.size() | m.size() | len(m) | O(1) |
| Loop over entries | for (Map.Entry<Integer,Integer> e : m.entrySet()) | for (auto& kv : m) // kv.first, kv.second | for k, v in m.items(): | O(n) |
Hash set (unique values)
Average O(1) per operation. Use it to ask "have I seen this before?".
| Operation | Java (HashSet<E>) | C++ (unordered_set<E>) | Python (set) | Cost |
|---|---|---|---|---|
| Create | Set<Integer> s = new HashSet<>(); | unordered_set<int> s; | s = set() | O(1) |
| Add | s.add(x) (returns false if already there) | s.insert(x); | s.add(x) | O(1) |
| Contains | s.contains(x) | s.count(x) > 0 | x in s | O(1) |
| Remove | s.remove(x) | s.erase(x); | s.discard(x) | O(1) |
| Size | s.size() | s.size() | len(s) | O(1) |
Sorted map and sorted set
Keys stay in order and every operation is O(log n). Use these when you need the next bigger or next smaller key.
| Operation | Java (TreeMap / TreeSet) | C++ (map / set) | Python ((no built-in; use sorted list and bisect)) | Cost |
|---|---|---|---|---|
| Create | TreeMap<Integer,Integer> m = new TreeMap<>(); | map<int, int> m; | keys = [] # kept sorted | O(1) |
| Smallest key | m.firstKey() | m.begin()->first | keys[0] | O(log n) |
| Largest key | m.lastKey() | m.rbegin()->first | keys[-1] | O(log n) |
| First key at least x | m.ceilingKey(x) | m.lower_bound(x) | keys[bisect.bisect_left(keys, x)] | O(log n) |
| Last key at most x | m.floorKey(x) | prev(m.upper_bound(x)) (check it is not begin) | keys[bisect.bisect_right(keys, x) - 1] | O(log n) |
| Insert in order | m.put(k, v) | m[k] = v; | bisect.insort(keys, k) | O(log n); Python list O(n) |
Heap (priority queue)
Java and Python give a MIN heap. C++ gives a MAX heap by default. To flip one: Java new PriorityQueue<>(Collections.reverseOrder()); C++ priority_queue<int, vector<int>, greater<int>>; Python push the negated value.
| Operation | Java (PriorityQueue<Integer>) | C++ (priority_queue<int>) | Python (heapq (on a list)) | Cost |
|---|---|---|---|---|
| Create min heap | PriorityQueue<Integer> pq = new PriorityQueue<>(); | priority_queue<int, vector<int>, greater<int>> pq; | import heapq
h = [] | O(1) |
| Create max heap | new PriorityQueue<>(Collections.reverseOrder()) | priority_queue<int> pq; | h = [] # push -x, negate on the way out | O(1) |
| Push | pq.offer(x) (or add) | pq.push(x); | heapq.heappush(h, x) | O(log n) |
| Look at the top | pq.peek() | pq.top() | h[0] | O(1) |
| Pop the top | pq.poll() | pq.pop(); (returns nothing) | heapq.heappop(h) | O(log n) |
| Heapify an existing list | new PriorityQueue<>(list) | priority_queue<int> pq(v.begin(), v.end()); | heapq.heapify(h) | O(n) |
| Pairs ordered by first value | new PriorityQueue<>((a, b) -> a[0] - b[0]) (int[] items) | priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> | heapq.heappush(h, (d, node)) | O(log n) |
| Size / is empty | pq.size() / pq.isEmpty() | pq.size() / pq.empty() | len(h) / not h | O(1) |
Pairs, tuples and custom sorting
Needed for graphs, intervals and anything sorted by a second field.
| Operation | Java (int[] / small class) | C++ (pair<int,int>) | Python (tuple) | Cost |
|---|---|---|---|---|
| Make a pair | new int[]{a, b} | make_pair(a, b) or {a, b} | (a, b) | O(1) |
| Read the two parts | p[0], p[1] | p.first, p.second | p[0], p[1] | O(1) |
| Sort by first part | Arrays.sort(arr, (x, y) -> x[0] - y[0]); | sort(v.begin(), v.end()); (pairs sort by first, then second) | v.sort() or v.sort(key=lambda p: p[0]) | O(n log n) |
| Sort by a custom rule | list.sort((x, y) -> Integer.compare(y, x)) | sort(v.begin(), v.end(), [](int x, int y) { return x > y; }); | v.sort(key=lambda x: -x) | O(n log n) |