LeetCode 15. 3Sum

LeetCode Notes [37]

John Lu
1 min readFeb 25, 2023

Problem

Intuition

The idea is to reduce the 3Sum problem into a Two Sum problem. Given the sum of two numbers, the third number must be the negative of the given sum. Therefore, the target for each two sum is the negative number of each array elements.

Implementation

class Solution {
private lateinit var map: MutableMap<Int, Int>

fun threeSum(nums: IntArray): List<List<Int>> {
map = mutableMapOf()
nums.forEachIndexed { index, num ->
map[num] = index
}
val result = mutableSetOf<List<Int>>()
for (i in nums.indices) {
val target = -nums[i]
for (j in i + 1 until nums.size) {
val num = nums[j]
val remains = target - num
val k = map[remains]
k?.let {
if (k != i && k > j) {
result.add(listOf(-target, num, remains).sorted())
}
}
}
}
return result.toList()
}
}

Complexity Analysis

  • Time Complexity: O(n²)
  • Space Complexity: O(n)

--

--

John Lu

Android Developer. Deeply motivated by challenges and tends to be excited by breaking conventional ways of thinking and doing. He builds fun and creative apps.