Card 04/ 07

ComparisonDifficulty: Intermediate2 min

Built-In Structures in Python vs Java vs TypeScript

Each language provides most structures, and the gaps decide what a listing must write by hand.

Once a program's operations have chosen a structure, the language decides whether that structure is one line of code or a class written by hand. This card covers the built-in that Python, Java and TypeScript each provide for every common structure, and the gaps in each, which are where a choice costs the most work.

A built-in here means a type or module in the language's standard library, the code that ships with the language, as opposed to a package installed separately. For TypeScript that is what Node and the browser provide, since TypeScript adds types to JavaScript and no collections of its own.

The table lists each structure against the three languages. A run in each language checked it: Python found list, deque, dict, set and heapq, and no sorted container; Java created every class named in its column; and TypeScript found Array, Map and Set and no queue, heap or sorted map.

The built-in for each structure in Python, Java and TypeScript
StructurePythonJavaTypeScript
Dynamic arraylistArrayListArray
Stacklist, with append and popArrayDequeArray, with push and pop
Queuecollections.dequeArrayDequeNone
Linked listNoneLinkedListNone
Hash mapdictHashMapMap
Hash setsetHashSetSet
Binary heapheapq, functions on a listPriorityQueueNone
Balanced binary search treeNoneTreeMap, TreeSetNone
Trie, union-find, graphNoneNoneNone

Java is the most complete: every structure up to a balanced binary search tree is a class in java.util. Python lacks one of those, the sorted map, so an ordered question on changing keys means a sorted list kept with bisect, which costs O(n) to insert, or a third-party package such as sortedcontainers. Python's heapq is a set of functions that keep an ordinary list in heap order, and it keeps the smallest item first; the largest first is done by storing negated keys.

TypeScript lacks the most. It has no heap, so a priority queue is written by hand. It has no queue either: Array.shift removes the first element, but the language specification describes it as moving every remaining element down one place, so a busy queue is better kept as an array with a moving head index. It has no sorted map, which leaves a hand-written tree or a sorted array.

No language provides a trie, union-find or a graph. Each is a few dozen lines built from the structures above: a map of children per node, a parent array, and a map of lists.

The rule that follows: choose the structure from the operations first, then check this table. A gap in the table means writing one class by hand, and the choice of structure stays the same.