Leetcode #259: 3Sum Smaller
In this guide, we solve Leetcode #259 3Sum Smaller in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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 1: Input: nums = [-2,0,1,3], target = 2 Output: 2 Explanation: Because there are two triplets which sums are less than 2: [-2,0,1] [-2,0,3] Example 2: Input: nums = [], target = 0 Output: 0 Example 3: Input: nums = [0], target = 0 Output: 0 Constraints: n == nums.length 0 <= n <= 3500 -100 <= nums[i] <= 100 -100 <= target <= 100 The input is generated such that the answer is less than or equal to 109.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Array, Two Pointers, Binary Search, Sorting
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Example
Input: nums = [-2,0,1,3], target = 2
Output: 2
Explanation: Because there are two triplets which sums are less than 2:
[-2,0,1]
[-2,0,3]
Python Solution
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
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.