HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Is it possible to solve 3SUM in $O(n^2)$ time?

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
possible3sumsolvetime

Problem

Problem: 3SUM

Input: Three lists A, B and C of integers and an integer k. Each list contain $n$ numbers.
Task: Decide whether there exists a tuple (a, b, c) ∈ A × B × C such that a + b + c = k.

Question : Is it possible to solve 3SUM in $O(n^2)$ time using constant space ? Prove or disprove it

Solution

A $O(n^2)$ algorithm (with $O(1)$ space) is as follows:

  • Sort $A$, $B$, and $C$ individually in $O(n \log n)$.



  • For each $a \in A$:



  • Search a pair of $b \in B$ and $c \in C$ such that $b + c = k - a$. This can be done in $O(n)$ by traversing $B$ from the smallest to the largest and $C$ from the largest to the smallest. (Tip: Comparing $b + c$ with $k-a$ each time.)

Context

StackExchange Computer Science Q#85715, answer score: 5

Revisions (0)

No revisions yet.