← Pointer Manipulation

Micro-Drill #125 — 3Sum skip duplicates

Pointer Manipulation Target: 15s

Sort + fix first + two-pointer on remainder. Skip duplicates at all three levels.

a.sort()
for i in range(len(a)-2):
    if i and a[i] == a[i-1]: continue
    l, r = i+1, len(a)-1
    while l < r:
        s = a[i] + a[l] + a[r]
        if s < 0: l += 1
        elif s > 0: r -= 1
        else:
            res.append([a[i], a[l], a[r]])
            l += 1
            while l < r and a[l] == a[l-1]: l += 1

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #124 Micro #126 →