Part 17 / Stage 4
Data structures and algorithms in Kotlin
Goal: Reason about time/space complexity before writing a line of code, then work through the data structures and algorithms that come up in nearly every interview and nearly every real system — hashing, two pointers, stacks/queues, recursion, sorting, binary search, linked lists, trees, heaps, graphs and dynamic programming — implementing each one by hand before reaching for the library version. Three small, real builds are woven in along the way: an undo button, a trending-posts feed, and a delivery route planner. Time: ~25–30 hours across this one large part, plus ongoing daily practice
What you will learn
- Big-O: measuring how work grows with input size, not with a stopwatch
- Hashing: turning an O(n²) brute-force scan into an O(n) one with
HashMap/HashSet - Two pointers and sliding window: one pass instead of a nested loop
ArrayDequeas a stack (LIFO) and as a queue (FIFO) — one class, two ends- Recursion (base case + recursive case) and backtracking (choose, explore, un-choose) with pruning, and where
tailrechonestly applies - Sorting by hand (bubble, insertion, merge, quicksort) and what
sorted()/sortedBy()actually run under the hood - Binary search by hand, then
binarySearch()on arrays and lists — and the one precondition that breaks everything if you skip it - Building a singly linked list by hand: nodes, head/tail pointers, reversal, cycle detection
- Building a binary search tree by hand: insert, search, the four traversal orders, why a skewed tree degrades to O(n)
java.util.PriorityQueueas a heap: min-heap, max-heap, bounded top-k- Representing a graph with an adjacency list, and BFS vs. DFS
- Dynamic programming: memoization (top-down) and tabulation (bottom-up), and where it beats plain backtracking
About "kotlinc 2.4.21 / Corretto 21.0.11": every command and output below was run on the exact toolchain pinned in
../../TOOLING.md. None of this part's algorithms depend on JVM internals, so the logic is portable to any recent Kotlin version — only exact nanosecond/millisecond timings are tagged(varies), because they depend on the machine running them, not on Kotlin.
How this part is organised
One examples/ subfolder per topic, plus the three real-world builds living next to the topic they demonstrate:
part-17-dsa-in-kotlin/
├── README.md
├── examples/
│ ├── big-o/BigODemo.kt
│ ├── hashing/HashingDemo.kt
│ ├── two-pointers/TwoPointersDemo.kt
│ ├── stacks-queues/DequeDemo.kt, UndoButtonDemo.kt (real-world build 1)
│ ├── recursion-backtracking/RecursionBacktrackingDemo.kt
│ ├── sorting/SortingDemo.kt
│ ├── binary-search/BinarySearchDemo.kt
│ ├── linked-lists/LinkedListDemo.kt
│ ├── trees/TreeDemo.kt
│ ├── heaps/HeapDemo.kt, TrendingPostsDemo.kt (real-world build 2)
│ ├── graphs/GraphDemo.kt, DeliveryRouteDemo.kt (real-world build 3)
│ └── dynamic-programming/DynamicProgrammingDemo.kt
├── exercises.md
└── solutions/
Every example is a single-file, no-package program — compile and run it exactly like Stage 1 did, from inside its own folder:
kotlinc SomeDemo.kt -include-runtime -d demo.jar
java -jar demo.jar
Topics in this part
Practice
Each exercise is its own file with a main function, exactly like the examples. Where timing is involved, the exercise prints a comparison (true/false) instead of a raw millisecond number, so your output can match exactly.
Exercise 1: Counting operations (Big-O)
Scenario: Before fixing a slow IRCTC seat-search, you want to prove the shape of the current code, not guess at it. What to do:
- Write
linearScanSteps(seats: IntArray, target: Int): Intthat counts how many array accesses it takes to findtargetwith a plain loop (return the array's size as the step count if not found, but still count every access attempted). - Write
countAllPairsSteps(n: Int): Longthat counts how many pair-comparisons a nested loop overnelements performs (same shape asBigODemo.countPairComparisons). - In
main, callcountAllPairsStepsforn = 500, 1000, 2000and print each count plus the ratio to the previous one, formatted to 1 decimal place. - Print whether the ratio from 1000 to 2000 is between
3.9and4.1.
Sample output:
n=500 -> 124750 comparisons
n=1000 -> 499500 comparisons (4.0x)
n=2000 -> 1999000 comparisons (4.0x)
ratio confirms O(n^2): true
Exercise 2: Two-sum with hashing
Scenario: A Swiggy cart has item prices; find two items whose prices add up exactly to a coupon value, without comparing every pair.
What to do: Write twoSum(prices: IntArray, target: Int): Pair<Int, Int>? using one HashMap<Int, Int> pass (price → index). Call it on intArrayOf(249, 99, 149, 399, 599) with target 498, and print the indices and the two prices they point to. Then call it with a target that has no valid pair and print "no pair found".
Sample output:
indices: (1, 3) (99 + 399)
no pair found
Exercise 3: Sliding window maximum average
Scenario: A fitness app wants the best 7-day rolling average of daily step counts.
What to do: Write bestWindowAverage(dailySteps: IntArray, windowSize: Int): Double using the fixed-size sliding-window technique (running sum, add new/drop oldest), returning the highest average rounded to 1 decimal place. Run it on a 10-day array of your choosing with windowSize = 7 and print the result alongside the brute-force answer (recompute every window's sum from scratch) to prove they match.
Sample output:
steps: [4200, 6100, 3900, 8800, 5200, 7000, 6600, 4100, 9300, 5500]
sliding window best 7-day average: 6642.9
brute force best 7-day average: 6642.9
match: true
Exercise 4: Balanced brackets with an ArrayDeque
Scenario: A config-file linter needs to catch unbalanced brackets before a deploy, including brackets mixed with other characters.
What to do: Write isBalanced(text: String): Boolean using an ArrayDeque<Char> as a stack, ignoring every character that isn't (, ), [, ], { or }. Test it on """{ "routes": [ (1,2), (3,4) ] }""" (balanced) and the same string with the final ] removed (one bracket missing), printing both results.
Sample output:
{ "routes": [ (1,2), (3,4) ] } -> balanced: true
{ "routes": [ (1,2), (3,4) } -> balanced: false
Exercise 5: A fixed-capacity undo history
Scenario: A drawing app's undo button should only remember the last 20 strokes — older ones are simply forgotten, to keep memory bounded.
What to do: Write a class BoundedUndo<T>(val capacity: Int) backed by an ArrayDeque<T>. record(action: T) pushes an action onto one end; if the deque would exceed capacity, remove the oldest one first (from the opposite end record pushes onto). undo(): T? removes and returns the most recent action, or null if empty. In main, record 25 numbered "stroke-N" actions into a BoundedUndo<String>(capacity = 20), then undo 3 times and print what comes back, plus the deque's final size.
Sample output:
undo 1: stroke-25
undo 2: stroke-24
undo 3: stroke-23
remaining history size: 17
Exercise 6: Backtracking with pruning — exam seat groups
Scenario: An exam hall needs every way to split n students into groups of exactly 3, where no two students who share the same roll-number prefix (first letter) can be in the same group — a simplified seating-conflict rule.
What to do: Write validGroupings(rollNumbers: List<String>): List<List<List<String>>> that backtracks through all ways to partition the list into groups of 3 (assume the list length is divisible by 3), pruning any partial group the moment it would contain two roll numbers with the same first letter. Run it on listOf("A101", "B204", "A305", "C110", "B220", "C330") and print the count of valid groupings and the first one found.
Sample output:
roll numbers: [A101, B204, A305, C110, B220, C330]
valid groupings found: 4
first grouping: [[A101, B204, C110], [A305, B220, C330]]
💡 Hint: this is the same "choose, explore, un-choose" shape as RecursionBacktrackingDemo's subset pruning — prune as soon as a partial group of size < 3 already has a repeated first letter, not only once a group of 3 is complete.
Exercise 7: Merge sort vs. sortedArray(), proven equal
Scenario: Before trusting a hand-written merge sort in a billing report, prove it agrees with the stdlib's own sort on several inputs, including edge cases.
What to do: Write mergeSort(values: IntArray): IntArray (by hand, as in SortingDemo). In main, test it against sortedArray() on: an empty array, a single-element array, an already-sorted array, a reverse-sorted array, and an array with duplicate values. Print each case's input, your result, and whether it matches values.sortedArray().
Sample output:
[] -> [] matches: true
[7] -> [7] matches: true
[1, 2, 3, 4] -> [1, 2, 3, 4] matches: true
[9, 7, 5, 3, 1] -> [1, 3, 5, 7, 9] matches: true
[4, 1, 4, 2, 1] -> [1, 1, 2, 4, 4] matches: true
Exercise 8: Binary search for the insertion point
Scenario: A leaderboard needs to insert a new score into a sorted array of scores, keeping it sorted, without a full re-sort.
What to do: Write insertionIndex(sortedScores: IntArray, newScore: Int): Int using binary search (adapt BinarySearchDemo.binarySearchSteps: when the loop ends without finding an exact match, low is the correct insertion index). Then write insertSorted(sortedScores: IntArray, newScore: Int): IntArray that builds a new, larger array with newScore placed at that index. Test on intArrayOf(10, 25, 40, 40, 70) inserting 35, and separately inserting 40 (a duplicate — insert it adjacent to the existing ones, either side is fine, but say which side your code picks).
Sample output:
scores: [10, 25, 40, 40, 70]
insert 35 -> index 2 -> [10, 25, 35, 40, 40, 70]
insert 40 -> index 2 -> [10, 25, 40, 40, 40, 70] (inserted before the existing 40s)
Exercise 9: A doubly linked list for an LRU-ish history
Scenario: A browser's "recently visited" list needs fast add-to-front AND fast remove-from-anywhere (revisiting a page should move it to the front, not duplicate it).
What to do: Extend the singly linked list idea to a doubly linked list: each Node has both prev and next. Implement moveToFront(value: T) (remove the node holding value from wherever it is — O(1) once found, since you have prev directly, no scanning for a "previous" pointer like the singly linked version needed — then re-insert it at the head) and toList(): List<T> returning the current order head to tail. Visit "home", "search", "product-42", "cart", then revisit "search", and print the list after every step.
Sample output:
visit home: [home]
visit search: [search, home]
visit product-42: [product-42, search, home]
visit cart: [cart, product-42, search, home]
revisit search: [search, cart, product-42, home]
Exercise 10: Binary search tree with delete
Scenario: TreeDemo's BST never removes a node. An employee-ID lookup tree needs delete, including the three real cases: a leaf, a node with one child, and a node with two children.
What to do: Add delete(value: Int) to a BST like TreeDemo's. For a two-children case, replace the node's value with its in-order successor (the smallest value in its right subtree), then delete that successor node from the right subtree instead. Build a tree from listOf(50, 30, 70, 20, 40, 60, 80), print the in-order traversal, delete 30 (two children), print again, delete 80 (leaf), print again, delete 70 (one child after 80 is gone), print a final time.
Sample output:
initial in-order: [20, 30, 40, 50, 60, 70, 80]
after delete(30): [20, 40, 50, 60, 70, 80]
after delete(80): [20, 40, 50, 60, 70]
after delete(70): [20, 40, 50, 60]
Exercise 11: Top-k frequent words with a bounded heap
Scenario: A customer-support dashboard needs the 3 most frequent words across a batch of complaint tickets, without sorting the entire vocabulary.
What to do: Write topKFrequent(words: List<String>, k: Int): List<Pair<String, Int>> that counts frequencies with a HashMap (hashing part), then keeps the top k with a correctly-bounded PriorityQueue (say out loud which kind, min or max, the way section 10 recommends) instead of sorting every distinct word. Break ties by alphabetical order. Run it on a list where "refund" appears 5 times, "delay" 3 times, "damaged" 3 times, and 4 other words appear once each, with k = 3.
Sample output:
top 3: [refund(5), damaged(3), delay(3)]
Exercise 12: BFS vs. Dijkstra on the same graph
Scenario: Prove, on one concrete graph, that BFS's "shortest path" and Dijkstra's "cheapest path" can disagree once edges have weights — the exact trap DeliveryRouteDemo's README section warns about.
What to do: Build one weighted graph (reuse or adapt GraphDemo's adjacency list plus edge weights, or DeliveryRouteDemo's RoadNetwork) with at least 5 nodes, where the fewest-hops path between two chosen nodes is NOT the cheapest-weight path. Run plain BFS to get the fewest-hops path and Dijkstra to get the cheapest-weight path between the same two nodes, print both paths with their hop count and total weight, and print whether the two paths differ.
Sample output:
BFS path (fewest hops): [Warehouse, Aundh] (1 hop, 20 min)
Dijkstra path (cheapest): [Warehouse, Baner, Aundh] (2 hops, 15 min)
paths differ: true
Exercise 13: Topological sort for a build pipeline
Scenario: A CI pipeline has build steps that depend on other steps finishing first; running them in the wrong order breaks the build. Figure out a valid run order, or detect that one is impossible.
What to do: Write topologicalOrder(dependsOn: Map<String, List<String>>): List<String> (each key depends on everything in its list) using DFS with a visiting/visited marker (the same three-state idea GraphDemo.hasCycle uses for undirected cycle detection, adapted to a directed graph: a node currently "on the DFS path" that gets visited again means a cycle, i.e. an impossible build). Return a valid order if one exists, or throw an IllegalStateException naming the cycle if not. Test it on a valid pipeline of 5 steps, then on the same pipeline with one extra dependency added that creates a cycle, catching and printing the exception's message.
Sample output:
valid order: [compile, lint, test, package, deploy]
Cycle detected involving: compile
Exercise 14: Longest increasing subsequence, memoization vs. tabulation
Scenario: A stock-watch tool wants the longest run of days (not necessarily consecutive) where the price strictly increased, to show "best growth streak" on a chart.
What to do: Write longestIncreasingSubsequenceMemo(prices: IntArray): Int (top-down: recursion with a cache, trying "start a new subsequence here" against every later, larger price) and longestIncreasingSubsequenceTabulation(prices: IntArray): Int (bottom-up: table[i] = the longest increasing subsequence ending exactly at index i, filled left to right). Run both on intArrayOf(200, 450, 130, 780, 320, 900, 1100) and print both results plus whether they agree, and the actual subsequence (not just its length) from the tabulation version.
Sample output:
prices: [200, 450, 130, 780, 320, 900, 1100]
memoization length: 5
tabulation length: 5
same length: true
subsequence: [200, 450, 780, 900, 1100]
Show the solutions for Part 17 (14 files)
solutions/ex01.kt
fun linearScanSteps(seats: IntArray, target: Int): Int {
for (i in seats.indices) {
if (seats[i] == target) return i + 1
}
return seats.size
}
fun countAllPairsSteps(n: Int): Long {
var comparisons = 0L
for (i in 0 until n) {
for (j in i + 1 until n) {
comparisons++
}
}
return comparisons
}
fun main() {
var previous = 0L
for (n in listOf(500, 1000, 2000)) {
val comparisons = countAllPairsSteps(n)
if (previous == 0L) {
println("n=$n -> $comparisons comparisons")
} else {
val ratio = comparisons.toDouble() / previous.toDouble()
println("n=$n -> $comparisons comparisons (${"%.1f".format(ratio)}x)")
}
previous = comparisons
}
val ratio1000to2000 = countAllPairsSteps(2000).toDouble() / countAllPairsSteps(1000).toDouble()
println("ratio confirms O(n^2): ${ratio1000to2000 in 3.9..4.1}")
}
solutions/ex02.kt
fun twoSum(prices: IntArray, target: Int): Pair<Int, Int>? {
val seenAt = HashMap<Int, Int>()
for (i in prices.indices) {
val complement = target - prices[i]
seenAt[complement]?.let { return it to i }
seenAt[prices[i]] = i
}
return null
}
fun main() {
val prices = intArrayOf(249, 99, 149, 399, 599)
val result = twoSum(prices, 498)
if (result != null) {
val (i, j) = result
println("indices: $result (${prices[i]} + ${prices[j]})")
}
val noPair = twoSum(prices, 10_000)
println(if (noPair == null) "no pair found" else "indices: $noPair")
}
solutions/ex03.kt
fun bestWindowAverage(dailySteps: IntArray, windowSize: Int): Double {
var windowSum = 0
for (i in 0 until windowSize) windowSum += dailySteps[i]
var best = windowSum
for (end in windowSize until dailySteps.size) {
windowSum += dailySteps[end] - dailySteps[end - windowSize]
best = maxOf(best, windowSum)
}
return Math.round(best.toDouble() / windowSize * 10) / 10.0
}
fun bruteForceWindowAverage(dailySteps: IntArray, windowSize: Int): Double {
var best = Int.MIN_VALUE
for (start in 0..dailySteps.size - windowSize) {
var sum = 0
for (i in start until start + windowSize) sum += dailySteps[i]
best = maxOf(best, sum)
}
return Math.round(best.toDouble() / windowSize * 10) / 10.0
}
fun main() {
val steps = intArrayOf(4200, 6100, 3900, 8800, 5200, 7000, 6600, 4100, 9300, 5500)
println("steps: ${steps.toList()}")
val slidingResult = bestWindowAverage(steps, 7)
val bruteResult = bruteForceWindowAverage(steps, 7)
println("sliding window best 7-day average: $slidingResult")
println("brute force best 7-day average: $bruteResult")
println("match: ${slidingResult == bruteResult}")
}
solutions/ex04.kt
fun isBalanced(text: String): Boolean {
val pairs = mapOf(')' to '(', ']' to '[', '}' to '{')
val stack = ArrayDeque<Char>()
for (c in text) {
when (c) {
'(', '[', '{' -> stack.addLast(c)
')', ']', '}' -> {
if (stack.isEmpty() || stack.removeLast() != pairs[c]) return false
}
}
}
return stack.isEmpty()
}
fun main() {
val balancedLine = """{ "routes": [ (1,2), (3,4) ] }"""
val brokenLine = """{ "routes": [ (1,2), (3,4) }"""
println("$balancedLine -> balanced: ${isBalanced(balancedLine)}")
println("$brokenLine -> balanced: ${isBalanced(brokenLine)}")
}
solutions/ex05.kt
class BoundedUndo<T>(private val capacity: Int) {
private val history = ArrayDeque<T>()
fun record(action: T) {
history.addLast(action)
if (history.size > capacity) history.removeFirst() // forget the oldest
}
fun undo(): T? = if (history.isEmpty()) null else history.removeLast()
fun size(): Int = history.size
}
fun main() {
val undo = BoundedUndo<String>(capacity = 20)
for (i in 1..25) undo.record("stroke-$i")
for (attempt in 1..3) {
println("undo $attempt: ${undo.undo()}")
}
println("remaining history size: ${undo.size()}")
}
solutions/ex06.kt
// Processes students in FIXED order (not "pick any remaining"), so each partition into
// groups is counted once, not once per order the group happened to be filled in.
fun validGroupings(rollNumbers: List<String>): List<List<List<String>>> {
val results = mutableListOf<List<List<String>>>()
val groups = mutableListOf<MutableList<String>>()
fun hasConflict(group: List<String>, candidate: String): Boolean =
group.any { it.first() == candidate.first() }
fun backtrack(index: Int) {
if (index == rollNumbers.size) {
if (groups.all { it.size == 3 }) results.add(groups.map { it.toList() })
return
}
val student = rollNumbers[index]
// choice 1: drop this student into any existing group with room and no conflict
// (snapshot with toList() -- choice 2 below adds to `groups` during this same recursion)
for (group in groups.toList()) {
if (group.size < 3 && !hasConflict(group, student)) {
group.add(student) // choose
backtrack(index + 1) // explore
group.removeAt(group.lastIndex) // un-choose
}
}
// choice 2: start a brand new group with this student
val newGroup = mutableListOf(student)
groups.add(newGroup) // choose
backtrack(index + 1) // explore
groups.removeAt(groups.lastIndex) // un-choose
}
backtrack(0)
return results
}
fun main() {
val rollNumbers = listOf("A101", "B204", "A305", "C110", "B220", "C330")
println("roll numbers: $rollNumbers")
val groupings = validGroupings(rollNumbers)
println("valid groupings found: ${groupings.size}")
println("first grouping: ${groupings.first()}")
}
solutions/ex07.kt
fun mergeSort(values: IntArray): IntArray {
if (values.size <= 1) return values
val mid = values.size / 2
val left = mergeSort(values.copyOfRange(0, mid))
val right = mergeSort(values.copyOfRange(mid, values.size))
return merge(left, right)
}
private fun merge(left: IntArray, right: IntArray): IntArray {
val merged = IntArray(left.size + right.size)
var i = 0; var j = 0; var k = 0
while (i < left.size && j < right.size) {
if (left[i] <= right[j]) merged[k++] = left[i++] else merged[k++] = right[j++]
}
while (i < left.size) merged[k++] = left[i++]
while (j < right.size) merged[k++] = right[j++]
return merged
}
fun main() {
val cases = listOf(
intArrayOf(),
intArrayOf(7),
intArrayOf(1, 2, 3, 4),
intArrayOf(9, 7, 5, 3, 1),
intArrayOf(4, 1, 4, 2, 1),
)
for (case in cases) {
val expected = case.sortedArray()
val actual = mergeSort(case)
println("${case.toList()} -> ${actual.toList()} matches: ${actual.toList() == expected.toList()}")
}
}
solutions/ex08.kt
fun insertionIndex(sortedScores: IntArray, newScore: Int): Int {
var low = 0
var high = sortedScores.size - 1
while (low <= high) {
val mid = low + (high - low) / 2
when {
sortedScores[mid] == newScore -> return mid
sortedScores[mid] < newScore -> low = mid + 1
else -> high = mid - 1
}
}
return low
}
fun insertSorted(sortedScores: IntArray, newScore: Int): IntArray {
val index = insertionIndex(sortedScores, newScore)
val result = IntArray(sortedScores.size + 1)
sortedScores.copyInto(result, 0, 0, index)
result[index] = newScore
sortedScores.copyInto(result, index + 1, index, sortedScores.size)
return result
}
fun main() {
val scores = intArrayOf(10, 25, 40, 40, 70)
println("scores: ${scores.toList()}")
val index35 = insertionIndex(scores, 35)
println("insert 35 -> index $index35 -> ${insertSorted(scores, 35).toList()}")
val index40 = insertionIndex(scores, 40)
println("insert 40 -> index $index40 -> ${insertSorted(scores, 40).toList()} (inserted before the existing 40s)")
}
solutions/ex09.kt
class DNode<T>(val value: T) {
var prev: DNode<T>? = null
var next: DNode<T>? = null
}
class RecentHistory<T> {
private var head: DNode<T>? = null
private var tail: DNode<T>? = null
private val nodesByValue = HashMap<T, DNode<T>>()
fun moveToFront(value: T) {
val existing = nodesByValue[value]
if (existing != null) {
unlink(existing)
linkAtHead(existing)
} else {
val node = DNode(value)
nodesByValue[value] = node
linkAtHead(node)
}
}
private fun unlink(node: DNode<T>) {
val previous = node.prev
val nextNode = node.next
if (previous != null) previous.next = nextNode else head = nextNode
if (nextNode != null) nextNode.prev = previous else tail = previous
node.prev = null
node.next = null
}
private fun linkAtHead(node: DNode<T>) {
node.next = head
node.prev = null
head?.prev = node
head = node
if (tail == null) tail = node
}
fun toList(): List<T> {
val values = mutableListOf<T>()
var current = head
while (current != null) {
values.add(current.value)
current = current.next
}
return values
}
}
fun main() {
val history = RecentHistory<String>()
history.moveToFront("home")
println("visit home: ${history.toList()}")
history.moveToFront("search")
println("visit search: ${history.toList()}")
history.moveToFront("product-42")
println("visit product-42: ${history.toList()}")
history.moveToFront("cart")
println("visit cart: ${history.toList()}")
history.moveToFront("search")
println("revisit search: ${history.toList()}")
}
solutions/ex10.kt
class BstNode(var value: Int) {
var left: BstNode? = null
var right: BstNode? = null
}
class DeletableBst {
private var root: BstNode? = null
fun insert(value: Int) {
root = insert(root, value)
}
private fun insert(node: BstNode?, value: Int): BstNode {
if (node == null) return BstNode(value)
when {
value < node.value -> node.left = insert(node.left, value)
value > node.value -> node.right = insert(node.right, value)
}
return node
}
fun delete(value: Int) {
root = delete(root, value)
}
private fun delete(node: BstNode?, value: Int): BstNode? {
if (node == null) return null
when {
value < node.value -> node.left = delete(node.left, value)
value > node.value -> node.right = delete(node.right, value)
else -> {
// this is the node to remove
if (node.left == null) return node.right // leaf, or only a right child
if (node.right == null) return node.left // only a left child
// two children: replace this node's value with its in-order successor
// (the smallest value in the right subtree), then delete that successor
// from the right subtree instead.
var successor = node.right!!
while (successor.left != null) successor = successor.left!!
node.value = successor.value
node.right = delete(node.right, successor.value)
}
}
return node
}
fun inOrder(): List<Int> {
val result = mutableListOf<Int>()
fun visit(node: BstNode?) {
if (node == null) return
visit(node.left); result.add(node.value); visit(node.right)
}
visit(root)
return result
}
}
fun main() {
val tree = DeletableBst()
for (value in listOf(50, 30, 70, 20, 40, 60, 80)) tree.insert(value)
println("initial in-order: ${tree.inOrder()}")
tree.delete(30) // two children (20 and 40)
println("after delete(30): ${tree.inOrder()}")
tree.delete(80) // leaf
println("after delete(80): ${tree.inOrder()}")
tree.delete(70) // one child, after 80 is gone
println("after delete(70): ${tree.inOrder()}")
}
solutions/ex11.kt
import java.util.PriorityQueue
fun topKFrequent(words: List<String>, k: Int): List<Pair<String, Int>> {
val counts = HashMap<String, Int>()
for (word in words) counts[word] = (counts[word] ?: 0) + 1
// Bounded MIN-heap: to keep the k LARGEST counts, evict the current smallest.
// Tie-break by alphabetical order so equal counts come out in a stable order --
// but order WITHIN the heap when counts tie doesn't matter for who stays; only the
// final sort needs the tie-break.
val minHeap = PriorityQueue<Pair<String, Int>>(compareBy { it.second })
for (entry in counts) {
minHeap.offer(entry.key to entry.value)
if (minHeap.size > k) minHeap.poll()
}
return minHeap.sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first })
}
fun main() {
val words = buildList {
repeat(5) { add("refund") }
repeat(3) { add("delay") }
repeat(3) { add("damaged") }
for (word in listOf("packaging", "courier", "support", "address")) add(word)
}
val top3 = topKFrequent(words, 3)
println("top 3: ${top3.joinToString(", ") { "${it.first}(${it.second})" }.let { "[$it]" }}")
}
solutions/ex12.kt
import java.util.PriorityQueue
class Road(val to: String, val minutes: Int)
class RoadNetwork {
private val adjacency = LinkedHashMap<String, MutableList<Road>>()
fun addRoad(from: String, to: String, minutes: Int) {
adjacency.getOrPut(from) { mutableListOf() }.add(Road(to, minutes))
adjacency.getOrPut(to) { mutableListOf() }.add(Road(from, minutes))
}
private fun roadsFrom(node: String): List<Road> = adjacency[node] ?: emptyList()
fun bfsPath(start: String, end: String): List<String> {
val cameFrom = HashMap<String, String>()
val visited = hashSetOf(start)
val queue = ArrayDeque<String>()
queue.addLast(start)
while (queue.isNotEmpty()) {
val node = queue.removeFirst()
if (node == end) break
for (road in roadsFrom(node)) {
if (visited.add(road.to)) {
cameFrom[road.to] = node
queue.addLast(road.to)
}
}
}
return reconstruct(cameFrom, start, end)
}
fun dijkstraPath(start: String, end: String): List<String> {
val best = HashMap<String, Int>()
val cameFrom = HashMap<String, String>()
val frontier = PriorityQueue<Road>(compareBy { it.minutes })
best[start] = 0
frontier.offer(Road(start, 0))
while (frontier.isNotEmpty()) {
val current = frontier.poll()
val knownTime = best.getValue(current.to)
if (current.minutes > knownTime) continue
for (road in roadsFrom(current.to)) {
val candidate = knownTime + road.minutes
if (candidate < (best[road.to] ?: Int.MAX_VALUE)) {
best[road.to] = candidate
cameFrom[road.to] = current.to
frontier.offer(Road(road.to, candidate))
}
}
}
return reconstruct(cameFrom, start, end)
}
fun totalMinutes(path: List<String>): Int {
var total = 0
for (i in 0 until path.size - 1) {
val road = roadsFrom(path[i]).first { it.to == path[i + 1] }
total += road.minutes
}
return total
}
private fun reconstruct(cameFrom: Map<String, String>, start: String, end: String): List<String> {
val path = mutableListOf(end)
var current = end
while (current != start) {
current = cameFrom[current] ?: return emptyList()
path.add(current)
}
return path.reversed()
}
}
fun main() {
val roads = RoadNetwork()
roads.addRoad("Warehouse", "Kothrud", 12)
roads.addRoad("Warehouse", "Baner", 9)
roads.addRoad("Baner", "Aundh", 6)
roads.addRoad("Warehouse", "Aundh", 20) // slow, congested direct road: 1 hop
roads.addRoad("Aundh", "Shivaji Nagar", 2)
roads.addRoad("Shivaji Nagar", "Camp", 2)
val bfsPath = roads.bfsPath("Warehouse", "Aundh")
val dijkstraPath = roads.dijkstraPath("Warehouse", "Aundh")
println("BFS path (fewest hops): $bfsPath (${bfsPath.size - 1} hop, ${roads.totalMinutes(bfsPath)} min)")
println("Dijkstra path (cheapest): $dijkstraPath (${dijkstraPath.size - 1} hops, ${roads.totalMinutes(dijkstraPath)} min)")
println("paths differ: ${bfsPath != dijkstraPath}")
}
solutions/ex13.kt
// Topological sort for "X depends on Y" via DFS with a visiting/visited marker.
// VISITING = currently on the DFS path (seeing it again means a cycle).
// VISITED = fully processed, safe to revisit.
enum class Mark { VISITING, VISITED }
fun topologicalOrder(dependsOn: Map<String, List<String>>): List<String> {
val marks = HashMap<String, Mark>()
val order = mutableListOf<String>()
fun visit(node: String) {
when (marks[node]) {
Mark.VISITED -> return
Mark.VISITING -> throw IllegalStateException("Cycle detected involving: $node")
null -> {
marks[node] = Mark.VISITING
for (dependency in dependsOn[node] ?: emptyList()) visit(dependency)
marks[node] = Mark.VISITED
order.add(node)
}
}
}
for (node in dependsOn.keys) visit(node)
return order
}
fun main() {
val validPipeline = linkedMapOf(
"compile" to listOf<String>(),
"lint" to listOf("compile"),
"test" to listOf("compile"),
"package" to listOf("lint", "test"),
"deploy" to listOf("package"),
)
println("valid order: ${topologicalOrder(validPipeline)}")
val cyclicPipeline = validPipeline + ("compile" to listOf("deploy")) // compile now depends on deploy
try {
topologicalOrder(cyclicPipeline)
} catch (e: IllegalStateException) {
println(e.message)
}
}
solutions/ex14.kt
fun longestIncreasingSubsequenceMemo(prices: IntArray): Int {
val memo = HashMap<Int, Int>()
fun lengthFrom(index: Int): Int {
memo[index]?.let { return it }
var best = 1 // the subsequence that is just prices[index] on its own
for (next in index + 1 until prices.size) {
if (prices[next] > prices[index]) {
best = maxOf(best, 1 + lengthFrom(next))
}
}
memo[index] = best
return best
}
var longest = 0
for (index in prices.indices) longest = maxOf(longest, lengthFrom(index))
return longest
}
fun longestIncreasingSubsequenceTabulation(prices: IntArray): Pair<Int, List<Int>> {
val table = IntArray(prices.size) { 1 } // table[i] = LIS ending exactly at index i
val previousIndex = IntArray(prices.size) { -1 }
for (i in prices.indices) {
for (j in 0 until i) {
if (prices[j] < prices[i] && table[j] + 1 > table[i]) {
table[i] = table[j] + 1
previousIndex[i] = j
}
}
}
var bestIndex = 0
for (i in prices.indices) if (table[i] > table[bestIndex]) bestIndex = i
val subsequence = mutableListOf<Int>()
var current = bestIndex
while (current != -1) {
subsequence.add(prices[current])
current = previousIndex[current]
}
subsequence.reverse()
return table[bestIndex] to subsequence
}
fun main() {
val prices = intArrayOf(200, 450, 130, 780, 320, 900, 1100)
println("prices: ${prices.toList()}")
val memoLength = longestIncreasingSubsequenceMemo(prices)
val (tabulationLength, subsequence) = longestIncreasingSubsequenceTabulation(prices)
println("memoization length: $memoLength")
println("tabulation length: $tabulationLength")
println("same length: ${memoLength == tabulationLength}")
println("subsequence: $subsequence")
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| Timing with a stopwatch instead of counting operations | Timings depend on the machine and JVM warm-up, not the algorithm | Reason in Big-O; use timings only to confirm the shape (section 1) |
Reaching for a nested loop before trying a HashMap/HashSet |
Turns an O(n) problem into O(n²) by habit | Ask "have I seen this?" or "what pairs with this?" — that's almost always hashing |
| Two pointers from both ends on unsorted data | The "move left in, sum goes up" assumption only holds when sorted | Sort first, or use hashing instead (section 2 vs. section 3) |
Reaching for java.util.LinkedList as a stack or queue in new code |
Extra indirection and allocation versus the array-backed ArrayDeque |
Kotlin's own ArrayDeque, used as a stack or a queue (section 4) |
| A redo stack that doesn't clear on a new action | Redo "resurrects" a future that no longer exists after a fresh edit | Clear the redo stack the moment any new action is taken (the undo build) |
Marking a function tailrec when it combines results after the recursive calls return |
Compiles anyway with a warning, as ordinary recursion — the StackOverflowError risk tailrec was supposed to remove is still there |
Only mark tailrec when the recursive call is genuinely the last action (section 5) |
| A recursive case that never shrinks toward the base case | StackOverflowError, not an infinite loop you can interrupt as easily |
Double-check every recursive call passes a strictly smaller sub-problem |
Assuming sortedArray()/sortedBy() are always the same algorithm |
Primitive arrays go through Dual-Pivot Quicksort (unstable); object collections go through a stable sort | Know which one you're calling when stability matters (section 6) |
| Binary search on data that might not be sorted | Returns a wrong, confident-looking "not found" or a wrong index | Sort first — binary search never checks the precondition for you (section 7) |
| Deleting from a singly linked list without tracking the previous node | Can't relink previous.next if you don't have previous |
Walk with a previous pointer alongside current (section 8) |
| Inserting already-sorted data into a plain BST | Degrades to a linked list: O(n) height instead of O(log n) | Know the caveat; reach for a self-balancing tree (java.util.TreeMap/TreeSet) when it matters (section 9) |
| Bounding the wrong kind of heap for top-k | Keeping the k smallest needs a MAX-heap to evict from (and vice versa) |
Say out loud which end you're evicting from before writing the comparator (section 10) |
| Using BFS when edges have different weights | Finds fewest hops, not fastest/cheapest route | Dijkstra: a priority queue ordered by accumulated cost, not a plain queue (section 11) |
| Reaching for DP when sub-problems don't actually overlap | Extra bookkeeping for no benefit | Confirm the same sub-problem gets asked for more than once before adding a cache or a table (section 12) |
Quick recap
- Big-O measures how work grows with input size; compare ratios as
ngrows, not raw timings. - Hashing (
HashMap/HashSet) turns "have I seen this?" from O(n²) into O(n);groupBy/associateWithare hashing wearing stdlib clothes. - Two pointers and sliding windows replace a nested loop with one coordinated pass; two pointers from both ends needs sorted data.
- Kotlin's own
ArrayDequeis both a stack and a queue — array-backed, nojava.utilborrow needed here (unlike heaps, section 10). - Recursion needs a base case and a shrinking recursive case; backtracking adds choose/explore/un-choose, often with pruning;
tailreconly applies when the recursive call is the function's last action. - Four classic sorts build the intuition
sortedArray()/sortedBy()rely on: quicksort for primitive arrays, a stable sort for object collections. - Binary search is O(log n) but requires sorted data — it never checks that precondition for you.
- A singly linked list gives O(1) insert-at-head but needs a
previouspointer to delete anything else; Kotlin's stdlib has no built-in one. - A BST gives O(log n) operations only while balanced; sorted-order inserts skew it to O(n).
java.util.PriorityQueueis the heap a Kotlin developer reaches for; bound it to sizek(the right end, min or max) for top-k without a full sort.- An adjacency list represents a graph; BFS (queue) finds fewest hops, DFS (stack/recursion) explores depth-first, Dijkstra (priority queue) finds the cheapest weighted path.
- Dynamic programming reuses overlapping sub-problem answers, top-down (memoization) or bottom-up (tabulation); it needs both optimal substructure and actual overlap to be worth it.
Checklist
- I can explain Big-O by counting operations, not by timing code, and I know why
n²means "doubling n roughly quadruples the work." - I replaced an O(n²) brute force with an O(n) hashing solution myself.
- I solved a two-pointer problem on sorted data and a sliding-window problem (fixed and variable size).
- I used
ArrayDequeas both a stack and a queue, and built the undo-button example end to end. - I wrote a recursive function with a base case, a
tailrecfunction where it honestly applied, and a backtracking function with pruning. - I implemented bubble, insertion, merge and quicksort by hand, and can say which sort
sortedArray()/sortedBy()actually runs for primitive arrays vs. objects. - I implemented binary search by hand, then used
binarySearch()on an array and a list, and reproduced the wrong-answer-on-unsorted-data bug myself. - I built a singly linked list by hand: insert, delete, reverse, and Floyd's cycle detection.
- I built a binary search tree by hand: insert, search, all four traversal orders, and I can explain why a skewed tree degrades to O(n).
- I used
PriorityQueueas a min-heap and a max-heap, and solved a bounded top-k problem — and built the trending-posts example. - I represented a graph with an adjacency list, ran BFS and DFS, and built the Dijkstra-based delivery-route example.
- I solved one problem with memoization and the same problem with tabulation, and got the same answer both ways.