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.

Array and dynamic list: operations in Java, C++ and Python
OperationJava (int[] / ArrayList<Integer>)C++ (int[] / vector<int>)Python (list)Cost
Create emptyList<Integer> a = new ArrayList<>();vector<int> a;a = []O(1)
Create with size n, all 0int[] a = new int[n];vector<int> a(n, 0);a = [0] * nO(n)
Sizea.size() (array: a.length)a.size()len(a)O(1)
Get by indexa.get(i) (array: a[i])a[i]a[i]O(1)
Set by indexa.set(i, x) (array: a[i] = x)a[i] = x;a[i] = xO(1)
Add at the enda.add(x)a.push_back(x);a.append(x)O(1) amortised
Remove the lasta.remove(a.size() - 1)a.pop_back();a.pop()O(1)
Insert at index ia.add(i, x)a.insert(a.begin() + i, x);a.insert(i, x)O(n)
Remove at index ia.remove(i) (an int index, not a value)a.erase(a.begin() + i);del a[i]O(n)
Contains a valuea.contains(x)find(a.begin(), a.end(), x) != a.end()x in aO(n)
Sort ascendingCollections.sort(a) (array: Arrays.sort(a))sort(a.begin(), a.end());a.sort()O(n log n)
ReverseCollections.reverse(a)reverse(a.begin(), a.end());a.reverse()O(n)
Smallest and largestCollections.min(a) / Collections.max(a)*min_element(a.begin(), a.end())min(a) / max(a)O(n)
Copynew 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.

String: operations in Java, C++ and Python
OperationJava (String / StringBuilder)C++ (string)Python (str)Cost
Lengths.length()s.size()len(s)O(1)
Character at is.charAt(i)s[i]s[i]O(1)
Substring from i up to js.substring(i, j)s.substr(i, j - i)s[i:j]O(j - i)
Build by appendingsb.append(c)s.push_back(c); or s += c;parts.append(c) then "".join(parts)O(1) each
Reversenew StringBuilder(s).reverse().toString()reverse(s.begin(), s.end());s[::-1]O(n)
Find a pieces.indexOf(t) (-1 if missing)s.find(t) (string::npos if missing)s.find(t) (-1 if missing)O(n m)
Compare equals.equals(t)s == ts == tO(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 intc - '0'c - '0'int(c)O(1)
To char array / lists.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.

Stack (last in, first out): operations in Java, C++ and Python
OperationJava (ArrayDeque<Integer>)C++ (stack<int>)Python (list)Cost
CreateDeque<Integer> st = new ArrayDeque<>();stack<int> st;st = []O(1)
Pushst.push(x)st.push(x);st.append(x)O(1)
Look at the topst.peek() (null if empty)st.top() (empty stack is undefined)st[-1]O(1)
Pop the topst.pop() (throws if empty)st.pop(); (returns nothing)st.pop()O(1)
Is emptyst.isEmpty()st.empty()not stO(1)
Sizest.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.

Queue (first in, first out): operations in Java, C++ and Python
OperationJava (ArrayDeque<Integer> (as Queue))C++ (queue<int>)Python (collections.deque)Cost
CreateQueue<Integer> q = new ArrayDeque<>();queue<int> q;from collections import deque q = deque()O(1)
Add at the backq.offer(x) (or add)q.push(x);q.append(x)O(1)
Look at the frontq.peek() (null if empty)q.front()q[0]O(1)
Remove from the frontq.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 emptyq.isEmpty()q.empty()not qO(1)
Sizeq.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).

Deque (add and remove at both ends): operations in Java, C++ and Python
OperationJava (ArrayDeque<Integer>)C++ (deque<int>)Python (collections.deque)Cost
CreateDeque<Integer> d = new ArrayDeque<>();deque<int> d;d = deque()O(1)
Add at the frontd.offerFirst(x) (or addFirst)d.push_front(x);d.appendleft(x)O(1)
Add at the backd.offerLast(x) (or addLast)d.push_back(x);d.append(x)O(1)
Remove from the frontd.pollFirst()d.pop_front();d.popleft()O(1)
Remove from the backd.pollLast()d.pop_back();d.pop()O(1)
Look at the front / backd.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.

Linked list: operations in Java, C++ and Python
OperationJava (your own ListNode (LinkedList class exists))C++ (your own ListNode (list<int> exists))Python (your own ListNode)Cost
Nodeclass ListNode { int val; ListNode next; }struct ListNode { int val; ListNode* next; };class ListNode: val, next
Create a nodenew ListNode(x)new ListNode(x)ListNode(x)O(1)
Walk the listfor (ListNode p = head; p != null; p = p.next)for (ListNode* p = head; p != nullptr; p = p->next)p = head while p: p = p.nextO(n)
Reach the next valuep.next.valp->next->valp.next.valO(1)
Dummy head before the real headListNode 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.

Hash map (key to value): operations in Java, C++ and Python
OperationJava (HashMap<K, V>)C++ (unordered_map<K, V>)Python (dict)Cost
CreateMap<Integer, Integer> m = new HashMap<>();unordered_map<int, int> m;m = {}O(1)
Put / overwritem.put(k, v)m[k] = v;m[k] = vO(1)
Getm.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 defaultm.getOrDefault(k, 0)m.count(k) ? m[k] : 0m.get(k, 0)O(1)
Has the keym.containsKey(k)m.count(k) > 0 (or m.find(k) != m.end())k in mO(1)
Remove a keym.remove(k)m.erase(k);del m[k] or m.pop(k, None)O(1)
Add 1 to a counterm.merge(k, 1, Integer::sum)m[k]++;m[k] = m.get(k, 0) + 1O(1)
Sizem.size()m.size()len(m)O(1)
Loop over entriesfor (Map.Entry<Integer,Integer> e : m.entrySet())for (auto& kv : m) // kv.first, kv.secondfor 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?".

Hash set (unique values): operations in Java, C++ and Python
OperationJava (HashSet<E>)C++ (unordered_set<E>)Python (set)Cost
CreateSet<Integer> s = new HashSet<>();unordered_set<int> s;s = set()O(1)
Adds.add(x) (returns false if already there)s.insert(x);s.add(x)O(1)
Containss.contains(x)s.count(x) > 0x in sO(1)
Removes.remove(x)s.erase(x);s.discard(x)O(1)
Sizes.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.

Sorted map and sorted set: operations in Java, C++ and Python
OperationJava (TreeMap / TreeSet)C++ (map / set)Python ((no built-in; use sorted list and bisect))Cost
CreateTreeMap<Integer,Integer> m = new TreeMap<>();map<int, int> m;keys = [] # kept sortedO(1)
Smallest keym.firstKey()m.begin()->firstkeys[0]O(log n)
Largest keym.lastKey()m.rbegin()->firstkeys[-1]O(log n)
First key at least xm.ceilingKey(x)m.lower_bound(x)keys[bisect.bisect_left(keys, x)]O(log n)
Last key at most xm.floorKey(x)prev(m.upper_bound(x)) (check it is not begin)keys[bisect.bisect_right(keys, x) - 1]O(log n)
Insert in orderm.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.

Heap (priority queue): operations in Java, C++ and Python
OperationJava (PriorityQueue<Integer>)C++ (priority_queue<int>)Python (heapq (on a list))Cost
Create min heapPriorityQueue<Integer> pq = new PriorityQueue<>();priority_queue<int, vector<int>, greater<int>> pq;import heapq h = []O(1)
Create max heapnew PriorityQueue<>(Collections.reverseOrder())priority_queue<int> pq;h = [] # push -x, negate on the way outO(1)
Pushpq.offer(x) (or add)pq.push(x);heapq.heappush(h, x)O(log n)
Look at the toppq.peek()pq.top()h[0]O(1)
Pop the toppq.poll()pq.pop(); (returns nothing)heapq.heappop(h)O(log n)
Heapify an existing listnew PriorityQueue<>(list)priority_queue<int> pq(v.begin(), v.end());heapq.heapify(h)O(n)
Pairs ordered by first valuenew 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 emptypq.size() / pq.isEmpty()pq.size() / pq.empty()len(h) / not hO(1)

Pairs, tuples and custom sorting

Needed for graphs, intervals and anything sorted by a second field.

Pairs, tuples and custom sorting: operations in Java, C++ and Python
OperationJava (int[] / small class)C++ (pair<int,int>)Python (tuple)Cost
Make a pairnew int[]{a, b}make_pair(a, b) or {a, b}(a, b)O(1)
Read the two partsp[0], p[1]p.first, p.secondp[0], p[1]O(1)
Sort by first partArrays.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 rulelist.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)