Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Count the Number of Fair Pairs

XPChallenge Points: 20
levelLevel: Medium

You are given a 0-indexed array of integers nums with n elements, along with two integers lower and upper.

We define a pair of indices (i, j) as valid when:

  • i < j

  • The sum nums[i] + nums[j] lies between lower and upper, inclusive.

Your task is to compute how many such valid index pairs exist.

Example 1:

Input: nums = [8, 2, 9, 1], lower = 10, upper = 12

Output: 3

Explanation:

Valid pairs: (0,1) → 8+2 = 10 (0,2) → 8+9 = 17 (not valid) (1,2) → 2+9 = 11 (2,3) → 9+1 = 10 Total = 2.

Example 2:

Input: nums = [2, 3, 1, 6, 4], lower = 5, upper = 7

Output: 0

Explanation:

Valid pairs are: (0,1) → 2+3 = 5 (0,3) → 2+6 = 8 (not valid) (1,2) → 3+1 = 4 (not valid) (1,4) → 3+4 = 7 (2,4) → 1+4 = 5 (3,4) → 6+4 = 10 (not valid) Total = 4 valid pairs.

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result