Skip to content

Commit ae5b737

Browse files
committed
Add Pair Sum Unsorted
1 parent 625ed0c commit ae5b737

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
fun pairSumUnsortedTwoPass(nums: List<Int>, target: Int): List<Int> {
2+
val numMap = mutableMapOf<Int, Int>()
3+
// First pass: Populate the hash map with each number and its
4+
// index.
5+
for ((i, num) in nums.withIndex()) {
6+
numMap[num] = i
7+
}
8+
// Second pass: Check for each number's complement in the hash map.
9+
for ((i, num) in nums.withIndex()) {
10+
val complement = target - num
11+
if (complement in numMap && numMap[complement] != i) {
12+
return listOf(i, numMap[complement]!!)
13+
}
14+
}
15+
return emptyList()
16+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
fun pairSumUnsorted(nums: List<Int>, target: Int): List<Int> {
2+
val hashmap = mutableMapOf<Int, Int>()
3+
for ((i, x) in nums.withIndex()) {
4+
if (target - x in hashmap) {
5+
return listOf(hashmap[target - x]!!, i)
6+
}
7+
hashmap[x] = i
8+
}
9+
return emptyList()
10+
}

0 commit comments

Comments
 (0)