Arrays: Two Sum — Kotlin Solution
Arrays: Two Sum — Kotlin Solution
Problem Info
| LeetCode # | 1 — Two Sum |
| Difficulty | Easy |
| Topic | Arrays, HashMap |
Given an array of integers
numsand an integertarget, return the indices of the two numbers that add up totarget.
Example:
1
2
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1] // nums[0] + nums[1] = 2 + 7 = 9
Approach
The brute force way is O(n²) — check every pair. We can do better.
Key insight: For each number x, we need target - x. Instead of searching for it, store every number we’ve seen in a HashMap. Then for each new number, just check if its complement already exists.
One pass. O(n) time.
Kotlin Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fun twoSum(nums: IntArray, target: Int): IntArray {
val seen = HashMap<Int, Int>() // value -> index
for ((index, num) in nums.withIndex()) {
val complement = target - num
if (complement in seen) {
return intArrayOf(seen[complement]!!, index)
}
seen[num] = index
}
return intArrayOf() // no solution found
}
Why Kotlin Shines Here
withIndex() — clean destructuring of index and value, no manual i counter:
1
2
for ((index, num) in nums.withIndex())
// vs Java: for (int i = 0; i < nums.length; i++)
in operator — readable HashMap lookup:
1
2
if (complement in seen)
// vs Java: if (seen.containsKey(complement))
Complexity
| Time | O(n) — single pass |
| Space | O(n) — HashMap stores up to n elements |
Key Takeaway
Store what you’ve seen. Check if the complement exists. One pass beats two loops every time.
📚 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.