Count Pairs Whose Sum is Less than Target — LeetCode 2824 Python Solution

EasyArrayTwo PointersBinary SearchSorting
Problem
#2824
Reading time
2 min

The problem

Given a 0-indexed integer array nums of length n and an integer target, return the number of pairs (i, j) where 0 <= i < j < n and nums[i] + nums[j] < target.

Example

Input
nums = [-1,1,2,3,1], target = 2
Output
3
Explanation
There are 3 pairs of indices that satisfy the conditions in the statement:

Python solution

Python
class Solution:
    def countPairs(self, nums: List[int], target: int) -> int:
        nums.sort()
        ans = 0
        for j, x in enumerate(nums):
            i = bisect_left(nums, target - x, hi=j)
            ans += i
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2824. Count Pairs Whose Sum is Less than Target 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 2824. Count Pairs Whose Sum is Less than Target?
LeetCode 2824. Count Pairs Whose Sum is Less than Target is rated Easy on LeetCode.
What is the time complexity of LeetCode 2824. Count Pairs Whose Sum is Less than Target?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2824. Count Pairs Whose Sum is Less than Target?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 2824. Count Pairs Whose Sum is Less than Target cover?
LeetCode 2824. Count Pairs Whose Sum is Less than Target is tagged Array, Two Pointers, Binary Search and Sorting on LeetCode.

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