Introduction
- This series is going to be about me going in through common leetcode solutions in Kotlin
Video version
GitHub code
Two Sum on Leetcode
Difficulty
- EASY
Solution Time Complexity
- O(N)
Kotlin Solution
fun twoSum(nums: IntArray, target: Int): IntArray {
val map = HashMap<Int,Int>()
for(item in nums.indices){
val partner = target - nums[item]
if(map.containsKey(partner)){
val returnedArray = intArrayOf(map[partner]!!,item)
return returnedArray
}else{
map[nums[item]] = item
}
}
throw IllegalArgumentException("NOTHING FOUND")
}
}
Explanation
-
So Kotlin code can be a little funky at times, so lets walk through it line by line. First lets start with
IntArray
, this is called aprimitive array
. Kotlin has special classes which represent arrays of primitive types, which save us some lines of code(Thanks Kotlin).- The
HashMap
is actually just the Java HashMap, if we look at Kotlin's source code HERE we can see it using the standardjava.util.HashMap
to implement hash maps. If you are wondering what a hash map is, that is really another topic unto itself. But just know it is a data structure which allows us to store items in key value pairs and we can access it in constant time. You can think of it like a fancy array. - Next we loop through the
nums
array and we can do that withfor(item in nums.indices)
which gives us anIntRange
and allows us to iterate like a basic Java for loop. Read more about ranges HERE - Next we get,
val partner = target - nums[item]
, partner is what we are actually looking for. It is the extra number that will add up to give us our target. - Next we check our map contains the partner:
if(map.containsKey(partner))
. If our map does contain the partner that means we have what we want, so we can return a new int array with the needed indexes like so,intArrayOf(map[partner]!!,item)
.item
is the current index of the nums array. - If
if(map.containsKey(partner))
is false then we add the current value to the array of our map,map[nums[item]] = item
. This code might look weird because its similar to indexing, however, we are not indexing.map[nums[item]] = item
is the exact same asmap.set(nums[item],item)
- Lastly if we find nothing we just throw an exception
throw IllegalArgumentException("NOTHING FOUND")
- The
Conclusion
- Thank you for taking the time out of your day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on Twitter.
Top comments (1)
Really cool breakdown!