Count Pairs Whose Sum is Less than Target — LeetCode 2824 Python Solution
- Problem
- #2824
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(\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.