Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Kth Smallest Pair Distance

Medium Acceptance 65% Points 30

You are given an integer array nums[]. The distance between a pair of elements is defined as the absolute difference between their values. Your task is to find the kth smallest distance among all possible pairs in the array.

Examples
Example 1

Example 1

Input: nums = [1,3,1], k = 1

Output: 0

Explanation: All possible pairs are (1,3), (1,1), and (3,1). Their distances are 2, 0, and 2. The sorted distances are [0,2,2]. The 1st smallest distance is 0.

Example 2

Example 2

Input: nums = [1,6,1], k = 3

Output: 5

Explanation: All possible pairs are (1,6), (1,1), and (6,1). Their distances are 5, 0, and 5. The sorted distances are [0,5,5]. The 3rd smallest distance is 5.

Example 3

Example 3

Input: nums = [1,2,3,4], k = 4

Output: 2

Explanation: All possible pairs are (1,2), (1,3), (1,4), (2,3), (2,4), (3,4). Their distances are 1, 2, 3, 1, 2, and 1. The sorted distances are [1,1,1,2,2,3]. The 4th smallest distance is 2.

Constraints
  • 2 = nums.length = 104
  • 0 = nums[i] = 106
  • 1 = k = nums.length × (nums.length - 1) / 2
Topics
Binary Search
Companies
Apple
Added 25 Jul 2026 65% acceptance
Ln 1, Col 1Sign in to save your code
1 3 1
1
1