Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added optimised twoSum solution #103

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/main/kotlin/math/TwoSum.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<Pair<Int, Int>>{

val array: MutableList<Pair<Int, Int>> = mutableListOf()
val map: MutableMap<Int, Int> = 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()


}
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 = 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())
}
}