Count Pairs Whose Sum is Less than Target

The function countPairs returns the number of pairs (i, j) where 0 <= i < j < n and nums[i] + nums[j] < target.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    def countPairs(self, nums: List[int], target: int) -> int:
        count = 0
        n = len(nums)

        # Iterate through all pairs of elements (i, j) where i < j
        for i in range(n):
            for j in range(i + 1, n):
                # If the sum of the pair is less than the target, increment the count
                if nums[i] + nums[j] < target:
                    count += 1

        return count

Explanation

  • We iterate through all possible pairs of elements (i, j) where i < j.
  • We check if the sum of the current pair is less than the given target.
  • If the condition is met, we increment the count of such pairs.
  • The function returns the final count, representing the number of pairs that meet the given condition.