LeetCode #15 3Sum
I happened to encounter this classic problem during my interview at JingChi. It was asked by Eric in the second round. I had not done this problem before, but I had done the related 2Sum problem, after all it is the first LeetCode problem and probably many people have done it. Also, when Algorithms, Fourth Edition discusses algorithm complexity, it uses the same kind of problem, though the details may differ, such as requiring no duplicate triplets in the result. I still had some impression of it at the time. I smoothly wrote an O(n^2) time-complexity solution, although afterward I found small bugs, such as list sort being in-place. But it did not really matter.
Today I organized the solution from the interview, submitted it, and unexpectedly got Time Limit Exceeded.
Description: https://leetcode.com/problems/3sum/description/
Solution: None
Difficulty: Medium
Solution During the Interview
1 | class Solution: |
Solving the Timeout Problem
reference[https://fizzbuzzed.com/top-interview-questions-1/]
The overall idea is that O(n^2) time complexity cannot be lowered further. The work is more about trying small techniques to reduce the constants in the time complexity.
Sort First
1 | class Solution: |
Adding sorting and checks inside the two loops reduces the number of duplicate triplets, meaning result.add(tuple(a)) is executed fewer times.
Looking at the previous TLE test case, LeetCode was clearly targeting duplicate triplets. Python set.add has O(1) time complexity, but it still got blocked by constants.
Two Pointer, Space Complexity Reduced to O(1)
1 | class Solution: |
The first submission still timed out, but without changing anything, I submitted again and it was Accepted. It seems LeetCode also depends on luck.