Count Index Pairs with a Target Sum
Updated
Problem statement
Given an integer array nums and integer k, return the number of index pairs (i,j) with i<j and nums[i]+nums[j]=k.
For this exercise, equal values at different indices are distinct choices. Count every qualifying pair of indices once, do not reuse an index as both endpoints, and do not return an existence Boolean. Empty and singleton arrays return 0. Leave nums unchanged.
Function
countTargetPairs(nums: int[], k: int) → intExamples
Example 1
nums = [1,5,7,-1,5]k = 6return = 3The matching index pairs are (0,1),(0,4),(2,3). The two occurrences of value 5 form different pairs with index 0, giving 3 total.
Example 2
nums = [1,1,1,1]k = 2return = 6Any two distinct indices qualify. There are 4*3/2=6 pairs, even though every pair has the same values 1 and 1.
Constraints
- For this exercise, assume 0 <= nums.length <= 2000.
- Every array value is between -1000000 and 1000000, inclusive.
- For this exercise, assume -2000000 <= k <= 2000000.
More Morgan Stanley Online Assessment questions
- Three-Resource 0/1 KnapsackOA · Seen Sep 2026
- Maximum Concurrent ProcessesOA · ONSITE INTERVIEW · Seen Sep 2026
- Maximum Total of Nonadjacent RatingsOA · Seen Jul 2026
- Count Shipment SchedulesOA · Seen Apr 2026
- Delete and EarnOA · Seen Apr 2026
- Interleave Array HalvesOA · Seen Apr 2026
- Get Patch SequenceOA · Seen Feb 2025
- String Subsequences 🐳OA · Seen Mar 2024
- Binary Tree Level OrderOA · Seen Feb 2024
- Merge IntervalsOA · Seen Feb 2024
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
Interview reports that mention this question
Morgan Stanley interview experiences
- Morgan Stanley New Grad Technology Analyst: 2 Experiences
- Morgan Stanley Intern Oldest Loops: 5 Experiences (Part 5 of 5)
- Morgan Stanley Intern OOP Loops: 5 Experiences (Part 4 of 5)
- Morgan Stanley Intern Earlier Loops: 5 Experiences (Part 3 of 5)
- Morgan Stanley Intern Tech Rounds: 5 Experiences (Part 2 of 5)