#2824

Count Pairs Whose Sum is Less than Target

Easy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

By sorting the array first, we can use a two-pointer technique to efficiently count pairs. This reduces the number of comparisons needed.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the array nums.
  2. 2Step 2: Initialize two pointers, one at the start (left) and one at the end (right) of the array.
  3. 3Step 3: While left < right, check if nums[left] + nums[right] < target. If true, all pairs from left to right are valid, so add (right - left) to the count and move left pointer up. Otherwise, move the right pointer down.
solution.py14 lines
1# Full working Python code
2
3def countPairs(nums, target):
4    nums.sort()
5    count = 0
6    left, right = 0, len(nums) - 1
7    while left < right:
8        if nums[left] + nums[right] < target:
9            count += (right - left)
10            left += 1
11        else:
12            right -= 1
13    return count
14

Complexity note: The sorting step takes O(n log n), and the two-pointer traversal takes O(n), making the overall complexity O(n log n).

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.