androidengineers.Book a session

Control Flow and Functions

Practice: Control Flow Exercises

exercise40 minEasy

Build a deterministic lesson selector

Write a pure function that selects the first incomplete topic from an ordered list. A parallel list of completion flags must have the same size; reject mismatches rather than guessing which flag belongs to which topic.

fun nextTopic(topics: List<String>, completed: List<Boolean>): String? {
    require(topics.size == completed.size)
    for (index in topics.indices) {
        if (!completed[index]) return topics[index]
    }
    return null
}

fun main() {
    check(nextTopic(listOf("Kotlin", "Compose"), listOf(true, false)) == "Compose")
    check(nextTopic(emptyList(), emptyList()) == null)
}

Returning null communicates that no next topic exists. A text sentinel such as "none" could collide with a real topic title. The early return makes the selection rule clear and stops scanning as soon as the answer is known.

Extend the exercise

Add a maximum title length filter without changing the order of candidates. Separate invalid input from the legitimate all-complete result. For each test, predict the return value before running it.

Acceptance checks: first incomplete, last incomplete, all complete, empty input, and size mismatch. Complexity should be linear in the number of topics in the worst case, with no sorting required.

Reference: Control flow

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Practice: Control Flow Exercises | Kotlin Core Programming | Android Engineers