BackeasyTwo Pointers TCS

Count Pairs with Sum Less Than Target Solution

Problem Statement

Given a 0-indexed sorted integer array nums and an integer target, determine the number of pairs (i, j) such that 0 <= i < j < nums.length and nums[i] + nums[j] < target.

Example 1
Input
nums = [1, 2, 3, 4, 5], target = 6
Output
4

Explanation: The valid index pairs are: (0, 1) with sum 1+2=3, (0, 2) with sum 1+3=4, (0, 3) with sum 1+4=5, and (1, 2) with sum 2+3=5.

Example 2
Input
nums = [-2, 0, 1, 3], target = 2
Output
3

Explanation: The valid index pairs are: (0, 1) with sum -2+0=-2, (0, 2) with sum -2+1=-1, and (0, 3) with sum -2+3=1.

Constraints

  • 2 <= nums.length <= 5 * 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • nums is sorted in non-decreasing order.
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free