The cost table, and lists
A data structure is a promise about which operations are cheap. Kotlin gives you most of them ready-made — some from the Kotlin standard library (listOf, mutableMapOf, ArrayDeque) and some straight from the JDK (java.util.PriorityQueue, java.util.TreeMap), because Kotlin on the JVM can use every Java class directly. Knowing the cost of each operation is what lets you pick the right one, and it is exactly what interviewers probe.
| Structure (Kotlin type) | Access | Search | Insert | Delete |
|---|---|---|---|---|
MutableList / ArrayList | O(1) by index | O(n) | O(1) amortised at end, O(n) at front | O(1) at end, O(n) at front |
ArrayDeque (stack or queue) | O(1) either end | O(n) | O(1) either end | O(1) either end |
| Linked list (hand-built) | O(n) | O(n) | O(1) at head / known node | O(1) at head / known node |
HashMap / HashSet / mutableMapOf | — | O(1) average | O(1) average | O(1) average |
TreeMap / sortedSetOf | — | O(log n) | O(log n) | O(log n) |
| Binary search tree (hand-built) | — | O(log n) balanced, O(n) worst | O(log n) balanced | O(log n) balanced |
PriorityQueue (binary heap) | O(1) min only | O(n) | O(log n) | O(log n) remove min |
| Graph (adjacency list) | — | O(V + E) with BFS/DFS | O(1) add edge | O(degree) remove edge |
listOf gives a read-only List; mutableListOf gives a MutableList backed by a JVM ArrayList — a resizable array. Reading by index is instant, appending at the end is cheap, but inserting at index 0 shifts every element one slot to the right. arrayOf / IntArray are fixed-size JVM arrays: use IntArray for large numeric work because it stores raw ints instead of boxed Integer objects.
fun main() {
val nums = mutableListOf(5, 3, 8)
nums.add(1) // append: O(1) amortised
nums.add(0, 9) // insert at front: shifts everything, O(n)
println(nums)
println(nums[2]) // index access: O(1)
nums.removeAt(0)
println(nums)
println(nums.size)
val squares = IntArray(5) { i -> i * i } // fixed size, unboxed ints
println(squares.joinToString())
println(squares.sum())
}[9, 5, 3, 8, 1]
3
[5, 3, 8, 1]
4
0, 1, 4, 9, 16
30Time the difference yourself: add 100,000 numbers with add(x), then another 100,000 with add(0, x), measuring each loop with kotlin.system.measureTimeMillis.
