Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Kth Smallest Pair Distance

Medium Acceptance 65.00% Points 30.00

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.

Hints
Hint 1
N/A
Constraints
  • 2 = nums.length = 104
  • 0 = nums[i] = 106
  • 1 = k = nums.length × (nums.length - 1) / 2
Companies
Apple
Topics
Binary Search
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions