Arrays: Contains Duplicate — Kotlin Solution
Arrays: Contains Duplicate — Kotlin Solution
Problem Info
| LeetCode # | 217 — Contains Duplicate |
| Difficulty | Easy |
| Topic | Arrays, HashSet |
Given an integer array
nums, returntrueif 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 Boolean — HashSet.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
| Approach | Time | Space | Notes |
|---|---|---|---|
| HashSet with early exit | O(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
| Time | O(n) |
| Space | O(n) |
Key Takeaway
HashSet
add()returns false on duplicates — use that return value directly instead of a separatecontains()check.
📚 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 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.