Skip to content

Commit

Permalink
added optimised twoSum solution
Browse files Browse the repository at this point in the history
  • Loading branch information
joltedThought committed Jan 5, 2024
1 parent e57a888 commit da50b10
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/main/kotlin/math/TwoSum.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,34 @@ 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 Indices of the two numbers such that they add up to target.
*/
fun twoSumOptimised(nums: IntArray, target: Int): IntArray{

val map: MutableMap<Int, Int> = HashMap()
for(num in nums) {
val targetDiff = target - num;
if(map[targetDiff] == null)
map[num] = 1
else return intArrayOf(num, targetDiff)
}

return intArrayOf(0,1)


}
10 changes: 10 additions & 0 deletions src/test/kotlin/math/TwoSum.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,14 @@ class TwoSumTest {
val result = intArrayOf(0,1)
assert(twoSum(array,target).contentEquals(result))
}

@Test
fun testTwoSumOptimised(){
val array = IntArray(2)
array[0] = 3
array[1] = 3
val target = 6
val result = intArrayOf(0,1)
assert(twoSum(array,target).contentEquals(result))
}
}

0 comments on commit da50b10

Please sign in to comment.