π Solving 'Two Sum' with HashMap in Kotlin
tl;dr: An elegant approach to finding two numbers that add up to a target value

π Problem Statement
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
π‘ My Initial Thought Process
When I first approached this problem, I thought about using a HashMap to efficiently find the solution:
- Iterate through each number in the array
- For each number, calculate the difference between the target and the current number
- Check if this difference exists in our HashMap
- If it does, weβve found our pair! Return the indices
- If not, add the current number and its index to the HashMap and continue
This approach ensures we only need to go through the array once, giving us an O(N) time complexity.
π My Initial Solution
This solution works correctly and efficiently, but I felt there was room for improvement in terms of readability and Kotlin idioms.
π Improved Solution with Kotlin Idioms
π₯ What I Learned
Through this process, I picked up some valuable Kotlin idioms and best practices:
-
Meaningful Variable Names: Using
seen
instead ofhm
makes the code more readable and self-documenting. -
Safe Call with Let: The
?.let
operator is a concise way to handle nullable values. Instead of:if(hm.contains(rem)){ return intArrayOf(hm[rem]!!,index) }
We can use:
seen[target - num]?.let { return intArrayOf(i, it) }
This eliminates the need for the null assertion operator (
!!
) and makes the code more elegant. -
Direct Map Access: Instead of using
contains()
followed by a lookup, we can directly access the map with the safe call operator.
β³ Time Complexity Analysis
- Building and searching the HashMap β O(N)
- Overall Complexity: O(N) π (Fast & Efficient!)
π§ Key Insights
- The HashMap approach allows us to find the complement in O(1) time
- By storing each number as we go, weβre essentially βrememberingβ what weβve seen before
- This problem demonstrates how data structures can dramatically improve algorithm efficiency
Letβs continue exploring elegant solutions to classic problems! If you have any questions or want to discuss other approaches to this problem, feel free to reach out.