src.three_sum¶
Classes
|
- class src.three_sum.Solution[source][source]¶
- threeSum(nums: list[int]) list[list[int]][source]¶
Thought process¶
Broad idea: We sort our array, then take a value
aand consider the values to thelandr. Since the array is sorted movingrcloser tolwill decrease the sum and movinglcloser torwill increase the sum.We can skip positive integers, since it is impossible to sum to 0 (e.g. [1, 2, 3])
We can skip duplicates to avoid duplicates in our result
Basic two pointer setup so 1. init pointers 2. loop while they havent crossed over
Check the 3 cases of the sum being too large, too small, or just right
If the sum is just right then append the result, move the pointers and skip duplicates
Notes¶
time complexity: \(O(n\log n + n^2)\) -> \(O(n^2)\)
space complexity: \(O(1)\) / \(O(n)\) depending on the implementation of sort