Skip to content

Instantly share code, notes, and snippets.

@wilfreddesert
Created January 26, 2021 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilfreddesert/377d05ba647c495978e4669b890b163a to your computer and use it in GitHub Desktop.
Save wilfreddesert/377d05ba647c495978e4669b890b163a to your computer and use it in GitHub Desktop.
def nth_element(array: List[Real], k: Real) -> Real:
"""
Time Complexity: O(n)
Space Complexity: O(1)
>>> nth_element([1, 2, 3], 3)
3
>>> nth_element([-1, -2, 3], 2)
-1
>>> nth_element([-1, -2, 3, 10], 1)
-2
>>> nth_element([-1, -2, 3, 10], 3)
3
>>> nth_element([-1, -2, 3, 10], 4)
10
"""
return quick_select(array, 0, len(array) - 1, len(array) - k + 1)
def quick_select(nums, start, n, k):
position = partition(nums, start, n)
if position == k - 1:
return nums[position]
elif position >= k:
return quick_select(nums, start, position - 1, k)
return quick_select(nums, position + 1, n, k)
def partition(nums, left, right):
pivot = nums[right]
i = left
for j in range(left, right):
if nums[j] > pivot:
nums[j], nums[i] = nums[i], nums[j]
i += 1
nums[right], nums[i] = nums[i], nums[right]
return i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment