FastPrepTop K Closest Pairs in a Sorted Array

Top K Closest Pairs in a Sorted Array

Apple logoApple● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given a nondecreasing integer array nums and an integer k, return the selected value pairs in priority order. Duplicate values and duplicate value pairs are retained when they come from different index pairs.

Function

topKClosestPairs(nums: int[], k: int) → int[][]

Examples

Example 1

nums = [1,2,4]k = 2return = [[1,2],[2,4]]

The differences are 1, 2, and 3.

Example 2

nums = [1,1,2]k = 3return = [[1,1],[1,2],[1,2]]

Index-distinct duplicate pairs are retained.

Constraints

  • 1 <= nums.length <= 500
  • 0 <= k <= 10000
  • nums is sorted in nondecreasing order.

More Apple problems

See Apple hiring insights
public int[][] topKClosestPairs(int[] nums, int k) {
  // Write your code here.
}
nums[1,2,4]
k2
expected[[1,2],[2,4]]
Checking account…