© Interview RuntimeThis content is copyright. Copying is disabled; you may quote a short excerpt with a link to the page.

Android coding interview, 3 Kotlin tasks to practise under time pressure

3 timed Kotlin exercises that separate algorithm correctness from lifecycle integration, with latest-intent search, page merging and optimistic saving.

Engraving of a stopwatch beside a small soldering iron in its stand.

In short

  • Keep the algorithm check and the lifecycle check apart, because a solution can pass one and fail the other.
  • A debounce delays work, while a revision check decides whether its result may still reach the screen.
  • Merging a page is a question of identity, order and payload, and each needs its own assertion.
  • An acknowledgement for an earlier save must never change the latest user choice.
  • Repeat each exercise with its follow-up and keep both attempts for comparison.

The search screen shows the right result. Then an older request fails and replaces it with an error.

The reading list shows the latest choice. Then an acknowledgement for an earlier tap changes it back.

Both bugs are easy to miss when you run the feature once, in order, on a fast connection. An Android coding interview can expose them with a small change to the test.

These 3 Kotlin exercises train application-oriented coding in search, paginated list merging and optimistic updates. Each has a contract, reference implementation, runnable check and follow-up. They are original practice exercises, not a list of questions claimed to come from named employers.

Confirm your actual round with the recruiter. Companies assess algorithms, Android features or both. Use these tasks for the app-oriented part. For the task types and how they are graded, read the Android coding interview guide.

Set a contract before starting the timer

Choose 1 task per session. Attempt it before reading the implementation.

TaskSuggested timeboxWhat you need to demonstrate
Debounced search30 minutesObsolete work cannot publish current state
Pagination merge30 minutesIdentity, ordering and payload replacement follow a defined rule, and a refresh cancels stale appends
Optimistic save30 minutesOlder acknowledgements cannot undo newer intent

The examples isolate behaviour from Android UI classes, so they include no Compose screen, Room database or network stack.

Each task ends with a check you can run. The 3 check blocks share 1 file, Checks.kt, and each reference block is its own file. Compile them with kotlinx-coroutines-core and kotlinx-coroutines-test, then run ChecksKt. They were checked with Kotlin 2.4.21 and kotlinx-coroutines 1.10.2.

Keep 2 checks apart. Algorithm correctness asks whether the logic returns the right result for a sequence of inputs. Lifecycle integration asks whether it still behaves correctly when the screen, its scope or the process changes. Verify them separately.

Task 1, debounced search that respects the latest intent

Candidate brief

A user types a query. Wait 300 milliseconds before searching. Empty input clears the screen. The latest query owns results, loading and errors. Cancellation must not be shown as a normal search failure.

Define what happens to old content. Here, a new query clears it. The injected service returns strings and uses IOException for expected operational failures. Unexpected programming errors are not converted into a generic retry message.

All calls to this controller and all coroutines in its scope must run on the same dispatcher, normally the main dispatcher in a screen. It is a single-owner example, not a thread-safe service.

Reference implementation

import java.io.IOException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class SearchState(
    val results: List<String> = emptyList(),
    val loading: Boolean = false,
    val error: String? = null
)

class SearchController(
    private val scope: CoroutineScope,
    private val debounceMillis: Long = 300,
    private val fetch: suspend (String) -> List<String>
) {
    private var revision = 0L
    private var job: Job? = null
    private val mutableState = MutableStateFlow(SearchState())
    val state = mutableState.asStateFlow()

    fun submit(rawQuery: String) {
        val mine = ++revision
        job?.cancel()
        job = null
        val query = rawQuery.trim()
        mutableState.value = SearchState(loading = query.isNotEmpty())
        if (query.isEmpty()) return

        job = scope.launch {
            try {
                delay(debounceMillis)
                val results = fetch(query)
                currentCoroutineContext().ensureActive()
                if (mine == revision) {
                    mutableState.value = SearchState(results = results)
                }
            } catch (cancelled: CancellationException) {
                throw cancelled
            } catch (failure: IOException) {
                currentCoroutineContext().ensureActive()
                if (mine == revision) {
                    mutableState.value = SearchState(error = "Search failed")
                }
            } finally {
                if (mine == revision) {
                    mutableState.value = mutableState.value.copy(loading = false)
                }
            }
        }
    }
}

The controller invalidates the old intent before cancelling work. Clearing the text also increments the revision, even though it starts no replacement request. The finally block belongs to a revision too; an old completion must not clear a newer operation's loading state.

Cancellation is propagated. The check after the fetch also protects against a dependency that returns successfully after its caller has been cancelled. Android's coroutine guidance covers cancellation and ownership, and the latest-intent policy is an additional application rule.[1]

The injected scope determines the lifetime, so do not give a screen controller an application-wide scope to avoid thinking about cancellation.

Verify the order you are worried about

Use controlled requests and a coroutine test scheduler.[2] The check below covers a newer success followed by an older success. Also try an older failure and a cleared query.

For debounce, advance virtual time to just before the boundary and verify that no service call has started. Advance through the boundary and run the queued work.

The fake below ignores cancellation on purpose, so a cancelled request can still return late. That is useful for verifying the publication boundary, not a pattern to put into a production service.

@file:OptIn(ExperimentalCoroutinesApi::class)

import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext

class Gates<K, V> {
    val byKey = mutableMapOf<K, CompletableDeferred<V>>()

    suspend fun await(key: K): V {
        val gate = CompletableDeferred<V>().also { byKey[key] = it }
        return withContext(NonCancellable) { gate.await() }
    }

    fun complete(key: K, value: V) = byKey.getValue(key).complete(value)
}

fun searchCheck() = runTest {
    val gates = Gates<String, List<String>>()
    val controller = SearchController(backgroundScope, debounceMillis = 0, fetch = gates::await)
    controller.submit("camera"); runCurrent()
    controller.submit("camera bag"); runCurrent()
    gates.complete("camera bag", listOf("bag")); runCurrent()
    gates.complete("camera", listOf("camera")); runCurrent()
    check(controller.state.value.results == listOf("bag")) { "late success replaced newer results" }
}

Delete both the ensureActive() call after the fetch and the revision comparison and this check fails. Either alone still passes, because each guards the same late result.

Follow-up, results should remain visible while refreshing

The reference implementation clears results. Change the product rule so previous results remain on screen while a new request is pending.

Which fields distinguish stale content from current results, and what does a failed refresh look like? Keep the revision rule while changing the presentation.

If you want to repeat this exercise with a guided loop and a changed constraint, Android Interview Training includes Guided Practice, with realistic prompts, weaknesses to inspect, revised answers and changed constraints.

Task 2, merge a page without duplicating items

Candidate brief

Merge an incoming page into an existing product list. IDs identify products. Existing items keep their positions, new IDs are appended in incoming order, and incoming payloads replace older payloads for matching IDs. A refresh replaces the list and invalidates any append still in flight. An append that belongs to an older refresh must never change the list.

Decide what repeated IDs inside the incoming page mean. For this exercise, the last payload wins while the position comes from the first appearance of that ID in the combined sequence.

Reference implementation

data class Product(val id: String, val title: String)

fun mergeProducts(
    existing: List<Product>,
    incoming: List<Product>
): List<Product> {
    val byId = linkedMapOf<String, Product>()
    for (product in existing) byId[product.id] = product
    for (product in incoming) byId[product.id] = product
    return byId.values.toList()
}

The insertion-ordered map makes the policy visible. Replacing the value for a key updates its payload without moving that key to the end. Expected work is linear in the total input size.

If the server sends a new ranking, preserving the old positions may be incorrect. The data structure cannot choose the product semantics for you.

The state around the merge

Page loading adds state the merge cannot hold. Each refresh starts a new generation, an append commits only if its generation is current, and a refresh resets the cursor and the end marker.

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class Page(val items: List<Product>, val next: String?)

class FeedController(
    private val scope: CoroutineScope,
    private val fetchPage: suspend (cursor: String?) -> Page
) {
    private var generation = 0L
    private var cursor: String? = null
    private var endReached = false
    private var job: Job? = null
    private val mutableItems = MutableStateFlow<List<Product>>(emptyList())
    val items = mutableItems.asStateFlow()

    fun refresh() {
        generation++
        cursor = null
        endReached = false
        load(replace = true)
    }

    fun loadMore() {
        if (endReached || job?.isActive == true) return
        load(replace = false)
    }

    private fun load(replace: Boolean) {
        job?.cancel()
        val mine = generation
        val from = cursor
        job = scope.launch {
            val page = fetchPage(from)
            ensureActive()
            if (mine != generation) return@launch
            mutableItems.value =
                if (replace) page.items else mergeProducts(mutableItems.value, page.items)
            cursor = page.next
            endReached = page.next == null
        }
    }
}

Cancelling the old job stops cooperative work, and the generation comparison covers a fetch that ignores cancellation. Task 1 shows error handling.

Verify replacement, ordering and the stale append

Start with A-old and B. Merge B-new, C-first and C-latest. Expect IDs A, B, C, with B-new and C-latest as payloads.

Also check an empty page, an empty existing list and a page containing only known IDs. A test that only asserts the final count can miss both wrong payloads and wrong order.

Then start an append, refresh before it returns, and complete the append last. The list must keep the refreshed rows.

fun feedCheck() = runTest {
    val merged = mergeProducts(
        listOf(Product("a", "A-old"), Product("b", "B")),
        listOf(Product("b", "B-new"), Product("c", "C-first"), Product("c", "C-latest"))
    )
    check(merged.map { it.title } == listOf("A-old", "B-new", "C-latest")) { "merge rule" }

    val gates = Gates<String?, Page>()
    val feed = FeedController(backgroundScope, gates::await)
    feed.refresh(); runCurrent()
    gates.complete(null, Page(listOf(Product("a", "A")), next = "p2")); runCurrent()
    feed.loadMore(); runCurrent()   // append for "p2" is now in flight
    feed.refresh(); runCurrent()    // refresh invalidates it
    gates.complete(null, Page(listOf(Product("x", "X")), next = "q2")); runCurrent()
    gates.complete("p2", Page(listOf(Product("b", "B")), next = null)); runCurrent()
    check(feed.items.value == listOf(Product("x", "X"))) { "old append reached the refreshed list" }
}

Remove ensureActive() and the generation comparison from FeedController and the last check fails.

Follow-up, the process dies mid-refresh

The generation lives in memory. Say what the user sees after process death between a refresh and the next append, and where the rows and the cursor must be stored so they belong to the same generation.

In an offline-backed Android implementation, Paging's RemoteMediator can coordinate network loads into a database-backed list.[3] It does not define your custom refresh semantics or server ordering contract for you.

Task 3, optimistic saving without stale rollback

Candidate brief

A user saves an article, then unsaves it before the first request completes. The UI should immediately reflect the latest choice. A response for the earlier choice must not change the current state.

Separate local intent from server acknowledgement. Use a monotonically increasing local revision to associate responses with an intent, and a stable operation ID for retrying that particular command.

This is an in-memory reducer without durable storage, a worker or server-side deduplication.

Reference implementation

data class SaveCommand(
    val articleId: String,
    val desired: Boolean,
    val revision: Long,
    val operationId: String
)

data class SavedState(
    val desired: Boolean,
    val revision: Long = 0,
    val acknowledgedRevision: Long = 0,
    val error: String? = null
) {
    val pending: Boolean get() = revision != acknowledgedRevision
}

class SaveReducer(
    private val articleId: String,
    initiallySaved: Boolean
) {
    var state = SavedState(desired = initiallySaved)
        private set

    fun change(desired: Boolean): SaveCommand {
        val next = state.revision + 1
        state = state.copy(desired = desired, revision = next, error = null)
        return SaveCommand(
            articleId, desired, next,
            java.util.UUID.randomUUID().toString()
        )
    }

    fun acknowledge(command: SaveCommand) {
        if (command.articleId != articleId || command.revision != state.revision) return
        state = state.copy(acknowledgedRevision = command.revision, error = null)
    }

    fun fail(command: SaveCommand) {
        if (command.articleId != articleId || command.revision != state.revision || !state.pending) return
        state = state.copy(error = "Could not sync. Retry available.")
    }
}

As with the search controller, 1 owner serialises access. A current failed command stays pending and the latest desired state stays visible. That is an offline-friendly policy, and another product might reject the change instead.

Only pass this reducer commands it created, because durable operation identity needs real storage.

Verify acknowledgements cannot time-travel

Generate save command A and unsave command B. Acknowledge A, then verify that the UI is still unsaved and pending. Acknowledge B and verify that pending becomes false. Deliver A's failure afterwards and verify that no error appears.

fun saveCheck() {
    val reducer = SaveReducer("article-1", initiallySaved = false)
    val save = reducer.change(true)
    val unsave = reducer.change(false)
    reducer.acknowledge(save)
    check(!reducer.state.desired && reducer.state.pending) { "old acknowledgement changed the choice" }
    reducer.acknowledge(unsave)
    check(!reducer.state.pending) { "latest acknowledgement was ignored" }
    reducer.acknowledge(save)
    check(!reducer.state.pending) { "late acknowledgement made the item pending again" }
    reducer.fail(save)
    check(reducer.state.error == null) { "late failure showed an error" }
}

fun main() {
    searchCheck()
    feedCheck()
    saveCheck()
    println("all checks passed")
}

Delete the revision comparison from acknowledge and the third check fails.

Retry a failed command with its existing operation ID, because a new ID per retry changes the identity the server is meant to recognise.

Follow-up, the server processes B before A

The reducer protects the local screen. It cannot prevent an older request from changing server state after the newer one if the backend accepts both without an ordering rule.

Discuss serialising writes for an item, conditional revisions or an explicit server operation-ordering contract. A local revision check is not a distributed consistency protocol.

For process-death recovery, persist the latest local state and the pending command together. Practise the recovery questions out loud, then read the offline sync guide, which goes deeper into the design.

What to explain while you code

State the rule you are protecting, the next small step and the check that could disprove your implementation. If time ends, name the remaining limitation precisely. “The reducer prevents stale local acknowledgement; server-side write ordering is still an assumption” is useful evidence. “It should be scalable” leaves the reviewer guessing.

Continue with Android interview training

Android Interview Training combines the book and companion code with 90 days of Guided Practice. Read the free sample to see how the practice format works.

Use 1 exercise here as your baseline, then repeat with the follow-up and keep both attempts. For an oral check on coroutines, read the Kotlin coroutines interview questions.

Sources

  1. Android, Coroutine best practices.
  2. Android, Testing Kotlin coroutines.
  3. Android, Paging from network and database.

Questions readers ask

© 2026 Mike Salari, Interview Runtime. All rights reserved. Quoting a short excerpt with a link to this page is welcome; republishing the article, in full or in part, is not.

Practice the follow-up, not the first answer.

Interview Runtime is the interview book plus 90 days of Guided Practice: you answer first, see the one gap that would cost the point, then answer again when one fact changes.