Two Sum

This is one of the easiest problem on LC as this has the highest acceptance rate as of now.

class Solution {
    fun twoSum(nums: IntArray, target: Int): IntArray {
        var map = HashMap<Int, Int>()
        
        nums.forEachIndexed { index, i ->
            if(map.containsKey(target-i)) return intArrayOf(map[target-i] ?: 0, index)
            else map[i] = index
        }

        return intArrayOf()
    }
}
Runtime: 176 ms, faster than 92.98% of Kotlin online submissions for Two Sum.
Memory Usage: 37.2 MB, less than 81.82% of Kotlin online submissions for Two Sum.

The idea is to iterate through the array and check if the target minus the item exists in the map already. If it exists, then it means the combination of the map entry the current item is the answer. If it doesn’t exist, we store the current value as the key and the current index as the value in the map.

This solution is O(N) because we only accessed each element in the array once.

comments powered by Disqus