androidengineers.Book a session

Algorithm Foundations & Complexity

Practice: Analyze and Compare Algorithms

exercise45 minEasy

Compare two duplicate detectors

One approach compares every pair; another stores seen values in a hash set. Both must agree on the result, but they make different time/space tradeoffs.

fun hasDuplicate(values: IntArray): Boolean {
    val seen = HashSet<Int>()
    for (value in values) {
        if (!seen.add(value)) return true
    }
    return false
}

Under ordinary hash-distribution assumptions, the set version has expected O(n) time and O(n) auxiliary space. Hash operations are not an unconditional worst-case constant-time guarantee. Pairwise comparison has O(n²) worst-case time but constant auxiliary space. Sorting then scanning provides another option, with mutation or copy costs to document.

Acceptance checks

Implement the pairwise baseline and compare outputs on empty, singleton, all-distinct, and repeated-value inputs. Count comparisons or insertions rather than relying only on elapsed time. Generate small arrays and use the baseline as an oracle.

Extension: choose an approach when memory is constrained, input must remain unchanged, or many repeated queries are needed.

Check: include preprocessing and copying costs in your comparison instead of timing only the final scan.

Further reading: Algorithm analysis

YOUR LEARNING JOURNEY

0 of 55 available lessons completed

Progress saved in this browser. No account needed.
Practice: Analyze and Compare Algorithms | Algorithms | Android Engineers