Kotlin Track

Kotlin Track

Seven posts prepare you for the coding side of a senior loop in Kotlin: thirty algorithm problems, a debugging round, and three rounds of conceptual questions about coroutines, the JVM, and functional style. This page indexes all of them in one place. Use the problem tables to choose what to practice, the question index to rehearse the spoken answers, and the snippet at the bottom to warm up your hands before the call.

Every gotcha from these posts is also on the Gotchas page and in the Quiz. This page does not repeat them; it arranges them by the symptom they cause.

Reading Order

# Post Round it prepares for Read it for
1 Ten Coding Interview Questions in Kotlin Coding screen The ten core patterns and the first set of Kotlin traps
2 Ten More Coding Interview Questions Coding screen Monotonic stacks, two pointers, topological sort, quickselect, backtracking, the trie
3 Part Three Coding screen Union-find, Dijkstra, KMP, two-dimensional DP, and the bit operators Kotlin names differently
4 “Find the Bug in This Function” Debugging or code-review round A four-step method, and ten planted bugs taken from the first three posts
5 Concurrency in Kotlin Language deep-dive Structured concurrency, cancellation, dispatchers, failure propagation
6 JVM Runtime Questions Language deep-dive, senior and staff The memory model, boxing, initialization, garbage collection, the JIT (just-in-time compiler), and diagnosis
7 Functional Programming in Kotlin Design discussion in code Real immutability, sealed types, error channels, laziness, and where purity stops paying

Read the first three in order: each one’s traps assume the previous ones. The find-the-bug post plants bugs from the first two coding posts and from the concurrency post, so it works best as a test after those, and it covers coroutines only lightly. Posts 5 to 7 stand alone.

Recognize the Pattern From the Prompt

Most of a coding round is recognizing which pattern the problem is. These are the phrases that give it away.

If the prompt says Reach for Worked example
“Pair that sums to”, “seen before”, “count occurrences” Hash map, check before insert Two Sum
“Longest or shortest contiguous substring or subarray such that” Sliding window Longest Substring
“Next greater”, “next warmer”, “how many days until” Monotonic stack of indices Daily Temperatures
“Balanced”, “nested”, “matching brackets” Stack Valid Parentheses
“Overlapping intervals”, “minimum rooms” Sort by start, then sweep or keep a heap of end times Merge Intervals, Meeting Rooms II
“Top k”, “k largest”, “k most frequent” Heap of size k, or quickselect Top K Frequent, Kth Largest
“Sorted but rotated”, “find in log time” Binary search on the index Rotated Search
“Smallest speed or capacity that still works” Binary search on the answer Koko
“Prerequisites”, “build order”, “is there a cycle” Topological sort Course Schedule
“How many groups”, “are these connected”, edges arriving one at a time Union-find Connected Components
“Regions in a grid”, “fewest steps” with equal costs Breadth-first search Number of Islands
“Cheapest” or “fastest” path with non-negative weights Dijkstra Network Delay
“Fewest coins”, “number of ways”, “longest common” Dynamic programming Coin Change, LCS
“All combinations”, “every subset” Backtracking, copying the path Subsets
“Starts with”, “autocomplete”, “prefix” Trie Trie
“Every number appears twice except one” XOR Single Number
“Median of a stream”, “running middle” Two heaps Stream Median
“O(1) get and put with eviction” Hash map plus linked list LRU Cache

The Thirty Problems, by Pattern Family

Each post lists its ten problems in the order it teaches them. Here the thirty are grouped by family instead, so you can practice one family at a time and see which ones you avoid. The last column is the one sentence from the post that tells the interviewer you know the pattern.

Arrays and hashing

Problem Part Pattern Time Space Say this
Two Sum 1 Hash map O(n) O(n) Check before insert
Group Anagrams 2 Canonical key O(nk) O(nk) Count array, comma-joined
Product Except Self 2 Prefix and suffix scan O(n) O(1) Two passes, no division
Merge Intervals 1 Sort and sweep O(n log n) O(n) Sort first; maxOf on the end

Stacks

Problem Part Pattern Time Space Say this
Valid Parentheses 1 Stack O(n) O(n) Empty stack at the end
Daily Temperatures 2 Monotonic stack O(n) O(n) Indices; strict <; each pushed once

Pointers and windows

Problem Part Pattern Time Space Say this
Longest Substring 1 Sliding window O(n) O(k) it >= left
Trapping Rain Water 2 Two pointers O(n) O(1) Move the shorter wall
Reverse and Cycle 1 Pointers O(n) O(1) Save next; ===
Problem Part Pattern Time Space Say this
Rotated Search 1 Binary search O(log n) O(1) <= on the sorted-half test
Koko Eating Bananas 3 Binary search on the answer O(n log M) O(1) Monotonic feasibility; lo < hi, hi = mid
Longest Increasing Subsequence 3 Patience sorting O(n log n) O(n) tails is sorted, not the subsequence

Heaps and selection

Problem Part Pattern Time Space Say this
Top K Frequent 1 Min-heap of size k O(n log k) O(n) Min-heap, not max
Kth Largest 2 Quickselect O(n) expected O(1) Index n - k; random pivot
Meeting Rooms II 3 Heap of end times O(n log n) O(n) Sort by start; pop the earliest end if free
Stream Median 3 Two heaps O(log n) insert O(n) Route through low; / 2.0

Graphs

Problem Part Pattern Time Space Say this
Number of Islands 1 Grid BFS (breadth-first search) O(rc) O(rc) Mark on enqueue; iterative
Course Schedule 2 Topological sort O(V + E) O(V + E) taken == numCourses is the cycle check
Connected Components 3 Union-find ~O(α(n)) per op O(n) Both compression and rank; union returns false on a redundant edge
Network Delay 3 Dijkstra O((V + E) log V) O(V + E) Skip stale heap entries; non-negative weights only

Trees and recursion

Problem Part Pattern Time Space Say this
Validate BST 2 Bounded recursion O(n) O(h) Carry Long bounds
Subsets 2 Backtracking O(n 2ⁿ) O(n 2ⁿ) Copy the path
Serialize a Tree 3 Preorder with sentinels O(n) O(n) The null marker makes it unique

Dynamic programming

Problem Part Pattern Time Space Say this
Coin Change 1 Bottom-up DP O(amount × coins) O(amount) amount + 1 as infinity
Maximum Subarray 2 Kadane O(n) O(1) Extend or restart; start at nums[0]
Longest Common Subsequence 3 Two-dimensional DP O(mn) O(mn) One-based table; extend the diagonal on a match

Bits and strings

Problem Part Pattern Time Space Say this
Single Number 3 XOR O(n) O(1) Pairs cancel; n and (n - 1) clears a bit
Substring Search 3 KMP (Knuth-Morris-Pratt) O(n + m) O(m) The failure table slides, never restarts

Design

Problem Part Pattern Time Space Say this
LRU Cache 1 Hash map plus linked list O(1) O(capacity) accessOrder = true; know the manual version
Trie 2 Prefix tree O(k) O(chars × 26) The terminal flag

Find the Bug: Where Each Bug Came From

The ten functions in the debugging post are broken versions of code this track already taught. If you cannot find a bug, go back to the correct version it was taken from.

Buggy function Failing input Class of bug The correct version
Two Sum [3, 3], target 6 Order of operations Two Sum: check before insert
Longest Substring "abba" Invariant violation (window moved left) Longest Substring: it >= left
LRU Cache put, put, get, put, get Wrong configuration (insertion order) LRU Cache: accessOrder = true
Maximum Subarray All negative Wrong initial value Kadane: start at nums[0]
Validate BST Grandchild violates grandparent Missing invariant propagation Validate BST: carry bounds
Subsets Any input Aliasing (live list stored) Subsets: copy the path
Make a Grid Write one cell Aliasing (shared row) Part two, gotcha 5: allocate in the lambda
Trie Prefix of an inserted word Missing state (terminal flag) Trie: the terminal flag
Worker Cancel mid-wait Swallowed cancellation Cancellation: rethrow CancellationException
Cleanup Cancel mid-body Suspension after cancellation Cancellation: wrap in NonCancellable

The Conceptual Questions

The last three posts are not about problems; they are about questions you answer out loud. Each row is a question as an interviewer asks it, the answer in one line, and the step that develops it. Rehearse the one-liner first, then the full step.

Coroutines and concurrency

They ask The one-line answer Full answer
“Explain coroutines.” A coroutine suspends without blocking its thread; jobs form a tree; cancellation flows down, failure flows up unless a supervisor stops it Step 1
“Run these calls in parallel.” async each one inside coroutineScope, then awaitAll(); never async { }.await() inside a map Step 2
“Why is my cancelled coroutine still running?” Cancellation is cooperative: CPU loops check isActive; CancellationException is rethrown; suspending cleanup runs under NonCancellable Step 3
“Which dispatcher, and how do you cap concurrency?” Default for CPU work, IO for blocking calls (it has a cap too), and a Semaphore for the limit you choose Step 4
“One async child fails. What happens?” Under coroutineScope it cancels the siblings and the scope immediately, even if no one calls await(); under supervisorScope it stays in the child until await() Step 5
“How do you protect a shared counter?” A Mutex, an atomic, confinement to one thread, or an actor; @Volatile does not make ++ atomic Step 6
“Flow or Channel?” A Flow is cold and replays for each collector; a Channel is hot and delivers each value to exactly one receiver Step 7
“Fetch N URLs, at most k in flight, with a timeout, tolerating failure.” supervisorScope, a Semaphore, withTimeoutOrNull, and a catch that rethrows cancellation Step 8

The JVM underneath

They ask The one-line answer Full answer
“What does @Volatile guarantee?” Visibility and ordering for a single read or write; not atomicity for a read-modify-write Step 1
“synchronized or Mutex?” synchronized holds a thread and cannot span a suspension; Mutex holds a coroutine, can, and is not reentrant Step 2
“What is the runtime type of this?” Int is a primitive; Int? and List<Int> hold Integer; a value class boxes once it is nullable or a generic argument Step 3
“Is by lazy thread-safe? Is object?” lazy synchronizes by default; object initializes under the class-init lock, and initializers that touch each other can deadlock Step 4
“Why does this listener leak?” An inner class captures its outer instance; a nested class, the Kotlin default, does not Step 5
“We have GC pauses. What do you change?” The allocation rate and the live set, before the collector flags Step 6
“Why is your benchmark wrong?” No warm-up, and a discarded result that the JIT deletes; use JMH (Java Microbenchmark Harness) Step 7
“NoSuchMethodError in production.” Compiled against one version, running against another; pin -Xjdk-release and one Kotlin version across modules Step 8
“How would you diagnose it?” Thread dump, GC log, heap dump on OOM (out-of-memory error), and JFR (Java Flight Recorder), always on Step 9

Functional style

They ask The one-line answer Full answer
“What does functional programming mean to you?” Data that does not change, functions that touch nothing else, types that say everything; applied to the domain and relaxed at the edges Step 1
“Is a val list immutable?” No: List is a read-only view, and copy() is shallow; copy at boundaries and keep vals all the way down Step 2
“Model this so bad states cannot exist.” A sealed hierarchy, matched with a when that has no else Step 3
“Exceptions, Result, or sealed errors?” T? for absent, Result at technical boundaries, a sealed outcome for domain failures, exceptions for bugs Step 4
“When is a Sequence faster?” Large inputs, long chains, early exit; for small collections the list wins, and a sequence reruns on every terminal call Step 5
“fold or reduce?” fold: it takes a seed, survives an empty input, and can change type Step 6
“Is recursion safe on the JVM?” There is no tail-call optimization: use tailrec, an explicit stack, or DeepRecursiveFunction Step 7
“Where does it stop being pragmatic?” Purity is a property of the interface: mutate locals, and inline higher-order functions on hot paths Step 8

The Traps, by Symptom

The Gotchas page lists the seventy Kotlin gotchas by post. Here they are sorted by what goes wrong, which is how you meet them in an interview.

Symptom The traps behind it
Does not compile on the whiteboard a ^ b and << (bit operators are named: xor, shl, ushr) · a local lambda that calls itself · a smart cast on a mutable property · switching between Kotlin’s and Java’s ArrayDeque methods
Compiles and gives a wrong answer .. where until belongs · -1 % 5 is -1 · var sum = 0 infers Int and overflows · == where identity matters · storing the live backtracking path · one row shared across a grid · shr on a negative number · mixing zero-based and one-based DP indexes · decoding binarySearch without the - 1 · nested it shadowing · split is literal in Kotlin and a regex in Java · a shallow copy() · else on a sealed when
Throws at runtime removeLast() against JDK 21 (NoSuchMethodError) · max() on an empty collection since 1.7 · a null from poll() or peek() through a platform type · reduce on an empty list · recursion deep enough to overflow the stack · an object initializer that fails, then NoClassDefFoundError on every later access
Correct but slow Array<Int> for numbers · Pair in hot loops · + on strings in a loop · sortedBy copies when sortBy would do · chained collection operations on large inputs · function types and non-inline lambdas that box and allocate · the default lock in by lazy · blocking calls on Dispatchers.Default
Wrong under concurrency catch (e: Exception) or runCatching swallowing CancellationException · GlobalScope · runBlocking in a handler · async { }.await() in a map · suspending in finally after cancellation · SupervisorJob() passed to launch · @Volatile on a counter

The Kotlin You Type in Every Round

One function containing the idioms these posts use most often. Type it from memory before a coding screen; if any line needs a second attempt, the matching problem above is the one to practice. It compiles with Kotlin 2.0, and every value it produces was checked by running it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.util.PriorityQueue

fun toolkit() {
    // Primitive arrays. A grid allocates one row per index.
    val counts = IntArray(26)
    for (c in "banana") counts[c - 'a']++              // c - 'a' is an Int on every compiler
    val grid = Array(3) { IntArray(4) }                 // not Array(3) { row }

    // Maps with a default
    val freq = HashMap<Int, Int>()
    for (n in intArrayOf(3, 1, 3)) freq[n] = (freq[n] ?: 0) + 1
    val groups = HashMap<String, MutableList<String>>()
    groups.getOrPut("aet") { mutableListOf() }.add("eat")

    // One ArrayDeque, its own API: addLast + removeLast is a stack, addLast + removeFirst a queue
    val deque = ArrayDeque<Int>()
    deque.addLast(1); deque.addLast(2); deque.addLast(3)
    val top = deque.removeLast()
    val front = deque.removeFirst()

    // Heaps are java.util and smallest-first; say which order you want
    val minHeap = PriorityQueue<Int>()
    val maxHeap = PriorityQueue<Int>(compareByDescending { it })
    val byEnd = PriorityQueue<IntArray>(compareBy { it[1] })

    // sortWith mutates the receiver; sortedWith returns a copy
    val intervals = arrayOf(intArrayOf(5, 6), intArrayOf(1, 3), intArrayOf(1, 2))
    intervals.sortWith(compareBy({ it[0] }, { it[1] }))

    // Numbers: Long accumulators, overflow-safe midpoints, non-negative modulus
    var sum = 0L
    for (n in intArrayOf(Int.MAX_VALUE, Int.MAX_VALUE)) sum += n
    val lo = 1; val hi = Int.MAX_VALUE
    val mid = lo + (hi - lo) / 2                         // (lo + hi) / 2 overflows here
    val slot = Math.floorMod(-1, 5)                      // 4, where -1 % 5 is -1

    // Bit operators are named functions
    val x = 5 xor 3
    val lowBitCleared = 12 and (12 - 1)
    val logicalShift = -8 ushr 28                        // shr would keep the sign
    val highMask = 1L shl 40                             // 1 shl 31 is already negative

    // binarySearch returns -(insertionPoint) - 1 when the key is absent
    val pos = intArrayOf(1, 3, 5).binarySearch(4)
    val insertAt = if (pos >= 0) pos else -(pos + 1)

    // Calls that mean the same thing on every compiler and JDK
    val biggest = emptyList<Int>().maxOrNull()           // null, not an exception
    val list = mutableListOf(1, 2, 3)
    list.removeAt(list.lastIndex)                        // not removeLast() on a MutableList

    // Recursion: a local fun, not a lambda; copy the path when you keep it
    val results = mutableListOf<List<Int>>()
    val path = mutableListOf<Int>()
    fun subsets(i: Int) {
        if (i == 3) { results.add(path.toList()); return }
        subsets(i + 1)
        path.add(i); subsets(i + 1); path.removeAt(path.lastIndex)
    }
    subsets(0)

    // Strings: a builder, not + in a loop
    val encoded = buildString { for (n in 1..3) append(n).append(',') }
}

Before the Interview

  • The week before: one pattern family per evening. Solve each problem without the post open, then compare your solution to the post’s.
  • Two days before: the find-the-bug table. Read each buggy function, find the bug before looking, and state the failing input out loud.
  • The night before: the conceptual question tables, answered aloud in one line each, and the Quiz filtered to what you have not marked as known.
  • The morning of: type the snippet above once, from memory.