Created
August 24, 2022 13:03
-
-
Save RaviH/d559206d52e3932cb40055192f736076 to your computer and use it in GitHub Desktop.
Solution for https://leetcode.com/problems/two-sum/submissions/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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