From da42ef6637b63c5bd0748ab33484a330ec34507f Mon Sep 17 00:00:00 2001 From: sumanas27 Date: Thu, 15 May 2025 12:40:50 +0200 Subject: [PATCH] Two Sum Problem --- src/main/kotlin/Main.kt | 15 +++++++++++ src/main/kotlin/ds-algo-leetcode/TwoSum.kt | 31 ++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 src/main/kotlin/Main.kt create mode 100644 src/main/kotlin/ds-algo-leetcode/TwoSum.kt diff --git a/src/main/kotlin/Main.kt b/src/main/kotlin/Main.kt new file mode 100644 index 0000000..f702081 --- /dev/null +++ b/src/main/kotlin/Main.kt @@ -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(",")}") +} \ No newline at end of file diff --git a/src/main/kotlin/ds-algo-leetcode/TwoSum.kt b/src/main/kotlin/ds-algo-leetcode/TwoSum.kt new file mode 100644 index 0000000..cc46efe --- /dev/null +++ b/src/main/kotlin/ds-algo-leetcode/TwoSum.kt @@ -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() + + // 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() + } +} \ No newline at end of file