3Sum Smaller — LeetCode 259 Python Solution

MediumLeetCode PremiumArrayTwo PointersBinary SearchSorting
Problem
#259
Reading time
3 min

The problem

Given an array of n integers nums and an integer target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.

Example

Input
nums = [-2,0,1,3], target = 2
Output
2
Explanation
Because there are two triplets which sums are less than 2:

Python solution

Python
class Solution:
    def threeSumSmaller(self, nums: List[int], target: int) -> int:
        nums.sort()
        ans, n = 0, len(nums)
        for i in range(n - 2):
            j, k = i + 1, n - 1
            while j < k:
                x = nums[i] + nums[j] + nums[k]
                if x < target:
                    ans += k - j
                    j += 1
                else:
                    k -= 1
        return ans

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(\log n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 259. 3Sum Smaller is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 259. 3Sum Smaller?
LeetCode 259. 3Sum Smaller is rated Medium on LeetCode.
What is the time complexity of LeetCode 259. 3Sum Smaller?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 259. 3Sum Smaller?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 259. 3Sum Smaller cover?
LeetCode 259. 3Sum Smaller is tagged Array, Two Pointers, Binary Search and Sorting on LeetCode.
Is LeetCode 259. 3Sum Smaller a premium problem?
Yes. LeetCode 259. 3Sum Smaller is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview