Count Pairs with Sum K
Updated
Problem statement
Given an integer array arr and an integer k, return the number of pairs of positions (i, j) with i < j such that arr[i] + arr[j] = k.
Pairs are counted by position, not by value: if the same value appears at several positions, each position can form its own pair.
Function
countPairs(arr: int[], k: int) → intExamples
Example 1
arr = [3,4,2,5,4,3]k = 7return = 5The pairs of positions that add up to 7 are (0, 1), (0, 4), (1, 5) and (4, 5), each a 3 with a 4, and (2, 3), which is 2 + 5. That makes 5 pairs.
Example 2
arr = [2,2,2,2]k = 4return = 6Any two of the four positions add up to 2 + 2 = 4. There are 4 * 3 / 2 = 6 ways to choose two positions out of four.
Example 3
arr = [-3,9,6,-3,0]k = 6return = 3Each -3 pairs with the 9: positions (0, 1) and (1, 3). The 6 pairs with the 0: positions (2, 4). No other pair adds up to 6, so the answer is 3.
Constraints
1 <= arr.length <= 10^4-10^6 <= arr[i] <= 10^6-2 * 10^6 <= k <= 2 * 10^6
More Bank of America Online Assessment questions
- Return Exact Cash Register ChangeOA · Seen Aug 2026
- Sum Skipping Multiples of 7OA · Seen Nov 2025
- Wildcard Substring MatchOA · Seen Nov 2025
- Maximum String BeautyOA · Seen Sep 2024
- Merge Point of Two Linked ListsOA · Seen Oct 2023
- Remove Duplicates from a ListOA · Seen Oct 2023
- Pairs with Target Sum in a Sorted ArrayOA · Seen Oct 2023
- Count Level-Order Traversals of a TreeOA · Seen Sep 2023
- Count Set BitsOA · Seen Sep 2023
- Letter Pattern SumOA · Seen Sep 2022
Similar questions at other companies
- Count User Mentions in Chat MessagesRamp · OARamp interview questions
- Count Valid Square PairsAuxoAI · OA
- Two SumAmazon · OA · PHONE SCREEN
- Find Words That Can Be Formed by CharactersTabaPay · OA
- Basic Item DiscountsPalantir · OAPalantir interview questions
- Word Frequency Counts in Alphabetical OrderAbridge · OAAbridge interview questions
- Customer Signer ScreeningState Farm · OA
- Minimum Magic Stones After MergesElevenLabs · OAElevenLabs interview questions
- K Most Recent Unique Request IDsMicrosoft · OAMicrosoft interview questions
- Distinct Products After Removing One ElementHSBC · OAHSBC interview questions