Skip to content

Instantly share code, notes, and snippets.

@RaviH
Created August 24, 2022 13:03
Show Gist options
  • Save RaviH/d559206d52e3932cb40055192f736076 to your computer and use it in GitHub Desktop.
Save RaviH/d559206d52e3932cb40055192f736076 to your computer and use it in GitHub Desktop.
class Solution {
fun twoSum(nums: IntArray, target: Int): IntArray {
val numberToIndexesMap = createNumberToIndexesMap(nums, target)
// Iterate through each entry
for (currEntry in numberToIndexesMap.entries) {
// Subtract it from the target
val nextValues = numberToIndexesMap[target - currEntry.key]
if (nextValues == null || nextValues.isEmpty()) {
continue
}
// And check if the subtracted value exists as key in the map
if (nextValues.size > 1 || nextValues != currEntry.value) {
val indexesForRemainingValue = numberToIndexesMap[target - currEntry.key]!!
// If the subtracted value exists multiple times then choose 2nd element
// Else choose first element
return if (indexesForRemainingValue.size > 1) {
intArrayOf(currEntry.value[0], indexesForRemainingValue[1])
} else {
intArrayOf(currEntry.value[0], indexesForRemainingValue[0])
}
}
}
return intArrayOf()
}
private fun createNumberToIndexesMap(
arr: IntArray,
expectedSum: Int
): MutableMap<Int, MutableList<Int>> {
val numberToIndexesMap = mutableMapOf<Int, MutableList<Int>>()
arr.withIndex().forEach {
val num = it.value
// Found another number with the same value as one of previous numbers
if (numberToIndexesMap.containsKey(num)) {
numberToIndexesMap[num]!!.add(it.index)
} else {
// First occurrence of number
numberToIndexesMap[num] = mutableListOf(it.index)
}
}
return numberToIndexesMap
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment