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