Skip to content

Commit

Permalink
Todays leetcode problem solution
Browse files Browse the repository at this point in the history
  • Loading branch information
Ayush59699 authored Aug 14, 2024
1 parent c3fe95c commit 239bfdd
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions LC_TODAaY.py.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
list_size = len(nums)

# Find the maximum element in the list
max_element = max(nums)

# Initialize a bucket list to store counts of each distance
distance_bucket = [0] * (max_element + 1)

# Populate the bucket list with counts of each distance
for i in range(list_size):
for j in range(i + 1, list_size):
# Compute the distance between nums[i] and nums[j]
distance = abs(nums[i] - nums[j])

# Increment the count for this distance in the bucket
distance_bucket[distance] += 1

# Find the k-th smallest distance
for dist in range(max_element + 1):
# Reduce k by the number of pairs with the current distance
k -= distance_bucket[dist]

# If k is less than or equal to 0, return the current distance
if k <= 0:
return dist

return -1 # Return -1 if no distance found, should not reach here

0 comments on commit 239bfdd

Please sign in to comment.