Given a list of integers and a target sum, count the number of unique pairs (i, j) where i < j and nums[i] + nums[j] equals the target. Return 0 for null or empty input.
A pair (i, j) is valid when the indices are distinct and the two values at those positions add up to the target. Because the constraint requires i < j, each pair is counted only once regardless of element order.
Examples:
Input: nums = [1, 5, 3, 2, 4], target = 6
Output: 2
Explanation: Pairs [1, 5] at indices (0,1) and [2, 4] at indices (3,4) each sum to 6.
Input: nums = [3, 3, 3], target = 6
Output: 3
Explanation: All three pairs (0,1), (0,2), and (1,2) sum to 6 because every element is 3.
Input: nums = [1, 2, 3], target = 10
Output: 0
Explanation: No pair of elements in this list sums to 10.
Input: nums = [3, 3], target = 6
Output: 1
Explanation: There is only one pair: indices (0,1).
Input: nums = null, target = 5
Output: 0
Explanation: Null input returns 0.
Apex Code Editor
Welcome to Lightning Challenge!
How It Works
- • Write your solution in the code editor
- • Connect your Salesforce org to test
- • Submit to check if your solution passes
- • Use hints if you get stuck
Contest Alert
🏆 #CodeEveryDay July 2026
Contest runs July 1 - 31. Complete challenges to climb the leaderboard!
Only the 31 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.