Skip to content

Two Sum Problem #1

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

Merged
merged 1 commit into from
May 15, 2025
Merged
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
15 changes: 15 additions & 0 deletions src/main/kotlin/Main.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package main.kotlin

import TwoSum

fun main() {
println("What's your name?")
val name = readln()
println("Hello, $name!")

// Calling Two Sum class
val obj = TwoSum()
val result = obj.twoSum(nums = intArrayOf(1,2,3,4,5), target = 9)

println("Indices: ${result.joinToString(",")}")
}
31 changes: 31 additions & 0 deletions src/main/kotlin/ds-algo-leetcode/TwoSum.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class TwoSum {

/*
* Time Complexity O(n)
* Space Complexity O(n)
*
* Step 1 : Declare a Map of Integers which will be used for comparison
* Step 2 : Run through the array with index
* Step 3 : Substract the current element from target sum and store it
* Step 4 : Check if the complement present in the map
* Step 5 : If present then create and return an array of Integers with the index
* of the current element and fetched value from map with the complement key
* Step 6 : Otherwise set the map with current element as key and current index
* as value
* Step 7 : Return an empty array by default
* */

fun twoSum(nums: IntArray, target: Int): IntArray {
val seen = mutableMapOf<Int, Int>()

// using array with index as index and value both are required for computation
for((index, element) in nums.withIndex()){
val complement = target - element
if( complement in seen )
return intArrayOf(seen.get(complement)!!, index)
// setting the map with the current index
seen[element] = index
}
return intArrayOf()
}
}