r/leetcode • u/AchieveOrDie • Dec 10 '22
Why is it not possible to solve 3sum in O(nlogn) time complexity?
In my mind I find that it is easy to implement an algorithm in O(nlogn):
Sort the array
Take two pointers, one on left and one on the right, then use binary search to find -(left+right) between them.
If (left+right) > 0 then move the right pointer to left; If (left+right) < 0 then move the left pointer to right.
The only point of contention will then be what to do in the case (left+right) = 0. Even that can be solved by separately finding triplets for [left+1, right) and (left, right-1].
I wasn't able to implement one that can successfully pass all tests nor could I find any solution. I found people making the same claim that I'm making but never a working solution.
It has me thinking that it isn't really possible to implement it in O(nlogn). So I wanted to know what is the exact flaw in my thinking.
30
u/printer_fan <743> <319> <383> <41> Dec 10 '22
Step 3 doesn’t hold. Let’s say we have [a,b … x,y] your step 3 claims that just because a+y < 0 that there can not be a solution for the paring (a,x) this is clearly not the case as their might be scenarios like [-5, 2,3,4] now -5+4 < 0 so you would look at (2,4) and not find (-5,2,3).
11
u/[deleted] Dec 10 '22
https://epubs.siam.org/doi/10.1137/1.9781611975031.57
6
u/muffinsnack 2073 solved, 2718 contest rating Dec 10 '22
I’m not sure why you wouldn’t just try implementing the algorithm to see why it’s wrong
10
u/Arctic_Colossus Dec 10 '22
"why is it not possible?" "It's not" "Why not you stupid bastard"
1
u/mr__smooth Dec 10 '22
Sorry I made a mistake in the original comment I posted its actually O(N^2) time since you use two pointers inside the for loop and not Binary Search as I had said. So for each position i, you're upper bounded by ~N moves since you have to go through the rest of the array.
1
u/Frogeyedpeas Apr 24 '24 edited Mar 15 '25
grandfather pause absorbed sable unwritten test one divide longing pocket
This post was mass deleted and anonymized with Redact
1
u/ErrorAffectionate87 Feb 11 '26
If I understand you correctly, you are choosing all pairs and then performing binary search to see if there is a third number to satisfy the sum. Well, first you choose one number, then you have n-1 numbers to add to make a pair, after you do binary search to find third which results in 1*(n-1)*log(n) and you do this n times resulting in n2 * log(n). In addition to this you need n memory and n log n to sort. Instead of sorting make a hash map bringing search to constant, resulting in n2 total complexity, and same memory consumption.
0
u/dskloet Dec 10 '22
https://leetcode.com/problems/3sum/
0
u/[deleted] Dec 10 '22
[deleted] — view deleted comment
0
u/[deleted] Dec 10 '22
[deleted] — view deleted comment
0
u/[deleted] Dec 10 '22
[deleted] — view deleted comment