Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d6f6181

Browse files
Merge pull request #1 from sumanas27/ss-local
Two Sum Problem
2 parents 8f7ab8f + da42ef6 commit d6f6181

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

‎src/main/kotlin/Main.kt

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package main.kotlin
2+
3+
import TwoSum
4+
5+
fun main() {
6+
println("What's your name?")
7+
val name = readln()
8+
println("Hello, $name!")
9+
10+
// Calling Two Sum class
11+
val obj = TwoSum()
12+
val result = obj.twoSum(nums = intArrayOf(1,2,3,4,5), target = 9)
13+
14+
println("Indices: ${result.joinToString(",")}")
15+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class TwoSum {
2+
3+
/*
4+
* Time Complexity O(n)
5+
* Space Complexity O(n)
6+
*
7+
* Step 1 : Declare a Map of Integers which will be used for comparison
8+
* Step 2 : Run through the array with index
9+
* Step 3 : Substract the current element from target sum and store it
10+
* Step 4 : Check if the complement present in the map
11+
* Step 5 : If present then create and return an array of Integers with the index
12+
* of the current element and fetched value from map with the complement key
13+
* Step 6 : Otherwise set the map with current element as key and current index
14+
* as value
15+
* Step 7 : Return an empty array by default
16+
* */
17+
18+
fun twoSum(nums: IntArray, target: Int): IntArray {
19+
val seen = mutableMapOf<Int, Int>()
20+
21+
// using array with index as index and value both are required for computation
22+
for((index, element) in nums.withIndex()){
23+
val complement = target - element
24+
if( complement in seen )
25+
return intArrayOf(seen.get(complement)!!, index)
26+
// setting the map with the current index
27+
seen[element] = index
28+
}
29+
return intArrayOf()
30+
}
31+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /