diff --git a/src/main/kotlin/math/TwoSum.kt b/src/main/kotlin/math/TwoSum.kt index 9ca0657..77e324a 100644 --- a/src/main/kotlin/math/TwoSum.kt +++ b/src/main/kotlin/math/TwoSum.kt @@ -24,3 +24,37 @@ fun twoSum(nums: IntArray, target: Int): IntArray{ return intArrayOf(0,1) } + +/** + * Approach 2: Using HashMap + * + * Complexity Analysis: + * + * Time complexity: O(n) + * Space complexity: O(n) + * + * Create an empty mutableMap and for every num in nums + * if map contains target-num, return num and target-num, + * otherwise add num, this approach returns all distinct pairs + * of such pairs. + * @param nums Array of integers. + * @param target Integer target. + * @return the two numbers such that they add up to target. + */ +fun twoSumOptimised(nums: IntArray, target: Int): Array>{ + + val array: MutableList> = mutableListOf() + val map: MutableMap = HashMap() + for(num in nums) { + val targetDiff = target - num; + if(map[targetDiff] == null) + map[num] = 1 + else { + array.add(Pair(targetDiff, num)) + } + } + + return array.toTypedArray() + + +} diff --git a/src/test/kotlin/math/TwoSum.kt b/src/test/kotlin/math/TwoSum.kt index 7e5e00f..e38d247 100644 --- a/src/test/kotlin/math/TwoSum.kt +++ b/src/test/kotlin/math/TwoSum.kt @@ -12,4 +12,14 @@ class TwoSumTest { val result = intArrayOf(0,1) assert(twoSum(array,target).contentEquals(result)) } + + @Test + fun testTwoSumOptimised(){ + val array = intArrayOf(1, 0, -1, 2, 4, 5, 3, 2) + val target: Int = 4 + val result = twoSumOptimised(array, target).apply { + this.all { it.first + it.second == target } + } + assert(result.isNotEmpty()) + } } \ No newline at end of file