BackhardBinary SearchMorgan StanleySwiggy

Segment Horizon Partition Engine 2 Solution

Problem Statement

You are given an integer array nums of length N and a positive integer K. Consider every unordered pair of distinct indices (i, j) with i < j and compute the sum S = nums[i] + nums[j]. This generates N·(N‑1)/2 pair sums. Your task is to determine the K‑th smallest value among these sums. The required solution must run in O(N log M) time, where M is the range of possible sums, by applying binary search on the answer space (often called "binary search on answer matrix").

Input: The first line contains two integers N and K (1 ≤ N ≤ 10^5, 1 ≤ K ≤ N·(N‑1)/2). The second line contains N integers nums[i] (‑10^9 ≤ nums[i] ≤ 10^9). The array is not guaranteed to be sorted.

Output: Output a single integer – the K‑th smallest pair sum.

Explanation of the required approach: After sorting nums, the smallest possible sum is nums[0] + nums[1] and the largest is nums[N‑2] + nums[N‑1]. Perform a binary search on this interval. For a candidate value X, count how many pairs have sum ≤ X using a two‑pointer scan (for each left index, move the right pointer leftwards until the sum exceeds X). If the count is at least K, X is a feasible answer and the search continues on the lower half; otherwise, search the upper half. The final low bound after the search terminates is the desired K‑th smallest sum.

Example 1
Input
4 5 2 7 11 15
Output
22

Explanation: All unordered pair sums are: 2+7=9, 2+11=13, 2+15=17, 7+11=18, 7+15=22, 11+15=26. Sorted sums: [9,13,17,18,22,26]. The 5th smallest sum is 22.

Example 2
Input
5 7 -5 -2 0 3 8
Output
3

Explanation: Pair sums: (-5,-2)=-7, (-5,0)=-5, (-5,3)=-2, (-5,8)=3, (-2,0)=-2, (-2,3)=1, (-2,8)=6, (0,3)=3, (0,8)=8, (3,8)=11. Sorted: [-7,-5,-2,-2,1,3,3,6,8,11]. The 7th smallest value is the second occurrence of 3, so the answer is 3.

Example 3
Input
3 3 1000000000 1000000000 1000000000
Output
2000000000

Explanation: All three possible pairs sum to 1,000,000,000 + 1,000,000,000 = 2,000,000,000. Hence the 3rd smallest (and any) sum equals 2,000,000,000.

Constraints

  • 1 <= N <= 100000
  • 1 <= K <= N*(N-1)/2
  • -10^9 <= nums[i] <= 10^9
  • All calculations fit within 64‑bit signed integer range
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Segment Horizon Partition Engine 2 — Problem Statement & Solution Guide

Binary SearchHardBinary Search on Answer Matrix
TimeO(N log M)
|
SpaceO(N)

Problem Description

You are given an integer array nums of length N and a positive integer K. Consider every unordered pair of distinct indices (i, j) with i < j and compute the sum S = nums[i] + nums[j]. This generates N·(N‑1)/2 pair sums. Your task is to determine the K‑th smallest value among these sums. The required solution must run in O(N log M) time, where M is the range of possible sums, by applying binary search on the answer space (often called "binary search on answer matrix").

Input: The first line contains two integers N and K (1 ≤ N ≤ 10^5, 1 ≤ K ≤ N·(N‑1)/2). The second line contains N integers nums[i] (‑10^9 ≤ nums[i] ≤ 10^9). The array is not guaranteed to be sorted.

Output: Output a single integer – the K‑th smallest pair sum.

Explanation of the required approach: After sorting nums, the smallest possible sum is nums[0] + nums[1] and the largest is nums[N‑2] + nums[N‑1]. Perform a binary search on this interval. For a candidate value X, count how many pairs have sum ≤ X using a two‑pointer scan (for each left index, move the right pointer leftwards until the sum exceeds X). If the count is at least K, X is a feasible answer and the search continues on the lower half; otherwise, search the upper half. The final low bound after the search terminates is the desired K‑th smallest sum.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Segment Horizon Partition Engine 2"

hard

WHY DOES IT MATTER?

The pattern combines binary search on a monotonic predicate with the two‑pointer technique on a sorted array, a powerful paradigm for order‑statistics problems where direct enumeration is infeasible.

OPTIMIZATION CHALLENGE

The key insight is recognizing that the count of pairs ≤ X is a non‑decreasing function of X, allowing us to replace the O(N²) enumeration with a logarithmic search over the value domain and a linear scan per step.

REAL-WORLD CONNECTION

Think of a distributed load‑balancer that needs to decide a latency threshold such that at least K request pairs finish within that time; binary searching the threshold while counting qualifying pairs mirrors the same decision‑making process.

Always sort once and reuse the sorted order; the two‑pointer scan is O(N) and cache‑friendly, so the overall bottleneck is the binary search loop, not the counting itself.

COMPLEXITY AT A GLANCE

⏱ Time:O(N log M)
💾 Space:O(N)

Core Theory — Why This Approach?

The K‑th smallest pair sum problem can be reduced to a decision problem: given a candidate sum X, can we count how many unordered pairs have a sum ≤ X? If we can answer this in O(N) after an O(N log N) sort, we can binary‑search over the value space [minSum, maxSum] to locate the smallest X for which the count ≥ K. This transforms the original O(N²) enumeration into O(N log M), where M = max(nums)‑min(nums) plus the range of sums, because each binary‑search step performs a linear two‑pointer scan on the sorted array. Naïve enumeration fails for N up to 10⁵ or higher due to quadratic blow‑up, while the binary‑search‑plus‑two‑pointer technique leverages monotonicity of the count function and the sorted order to achieve near‑optimal performance.

Interview Questions on This Problem

Q1How would you modify the algorithm if the array could contain duplicate values and you needed the K‑th distinct pair sum?

After sorting, during the two‑pointer count you must skip over duplicate pairs by advancing pointers past equal values and maintain a set or count of distinct sums; alternatively, binary search on sum values still works, but the count function must only increment when a new sum value is encountered, which can be done by tracking the previous sum during the scan.

Q2Explain how you could adapt this solution to find the K‑th smallest sum of three distinct elements.

For triples, you can fix the first element and apply a two‑pointer count on the remaining subarray to count pairs whose sum with the fixed element ≤ X, yielding O(N²) per binary‑search step; to meet O(N² log M) you pre‑sort and use the same monotonic count, but the problem’s complexity inherently rises because each count now requires O(N) for each of the N choices of the first element.

Q3Why is binary search on the answer space preferable to using a min‑heap of size K for this problem?

A min‑heap approach would need to generate O(N²) candidate sums or maintain a heap of size K while iterating over all pairs, leading to O(N² log K) time and excessive memory. Binary search leverages the sorted order to count pairs in linear time per iteration, achieving O(N log M) without storing any pair sums.

Examples

Example 1

Input

4 5
2 7 11 15

Output

22

Explanation: All unordered pair sums are: 2+7=9, 2+11=13, 2+15=17, 7+11=18, 7+15=22, 11+15=26. Sorted sums: [9,13,17,18,22,26]. The 5th smallest sum is 22.

Example 2

Input

5 7
-5 -2 0 3 8

Output

3

Explanation: Pair sums: (-5,-2)=-7, (-5,0)=-5, (-5,3)=-2, (-5,8)=3, (-2,0)=-2, (-2,3)=1, (-2,8)=6, (0,3)=3, (0,8)=8, (3,8)=11. Sorted: [-7,-5,-2,-2,1,3,3,6,8,11]. The 7th smallest value is the second occurrence of 3, so the answer is 3.

Example 3

Input

3 3
1000000000 1000000000 1000000000

Output

2000000000

Explanation: All three possible pairs sum to 1,000,000,000 + 1,000,000,000 = 2,000,000,000. Hence the 3rd smallest (and any) sum equals 2,000,000,000.

Constraints

  • 1 <= N <= 100000
  • 1 <= K <= N*(N-1)/2
  • -10^9 <= nums[i] <= 10^9
  • All calculations fit within 64‑bit signed integer range

Optimal Approach & Strategy

Sort the array, then binary‑search the possible sum range. For each candidate sum, count qualifying pairs with a linear two‑pointer scan; adjust the search bounds based on the count to locate the K‑th smallest sum.

Brute Force Approach

Generate every unordered pair, compute its sum, store all sums in a list, sort the list, and return the K‑th element. This requires O(N²) time and O(N²) extra space.

Verified Code Solutions

JavaScript Solution
Time: O(N log M)
function solution(nums) {
      let sum = 0;
      for (let num of nums) {
         sum += num;
      }
      return sum;
   }

Asked in Top Tech Interviews

Morgan StanleySwiggy

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.