Post

Arrays: Contains Duplicate — Kotlin Solution

Arrays: Contains Duplicate — Kotlin Solution

Problem Info

  
LeetCode #217 — Contains Duplicate
DifficultyEasy
TopicArrays, HashSet

Given an integer array nums, return true if any value appears at least twice.

Example:

1
2
3
4
5
Input:  nums = [1, 2, 3, 1]
Output: true

Input:  nums = [1, 2, 3, 4]
Output: false

Approach

Use a HashSet. For each number, check if it’s already in the set. If yes — duplicate found. If no — add it and continue.


Kotlin Solution

1
2
3
4
5
6
7
8
9
fun containsDuplicate(nums: IntArray): Boolean {
    val seen = HashSet<Int>()

    for (num in nums) {
        if (!seen.add(num)) return true
    }

    return false
}

One-liner version (idiomatic Kotlin)

1
2
3
fun containsDuplicate(nums: IntArray): Boolean {
    return nums.size != nums.toHashSet().size
}

Why Kotlin Shines Here

seen.add() returns BooleanHashSet.add() returns false if the element already exists. We use that directly:

1
2
if (!seen.add(num)) return true
// No separate contains() check needed

toHashSet() — Kotlin’s collection extension makes the one-liner possible:

1
nums.toHashSet() // converts IntArray to HashSet<Int> in one call

Two Approaches Compared

ApproachTimeSpaceNotes
HashSet with early exitO(n)O(n)Stops as soon as duplicate found
One-liner toHashSet()O(n)O(n)Clean but no early exit

Use the first approach in interviews — shows you understand early termination.


Complexity

  
TimeO(n)
SpaceO(n)

Key Takeaway

HashSet add() returns false on duplicates — use that return value directly instead of a separate contains() check.

🔗 Solve it on LeetCode →


📚 Kotlin DSA Series

This post is part of the Kotlin DSA series — solving LeetCode problems using idiomatic Kotlin.

← View Full Series Index
This post is licensed under CC BY 4.0 by the author.