Skip to content

Instantly share code, notes, and snippets.

@jeremiq
Created April 4, 2019 23:12
Show Gist options
  • Save jeremiq/4038d8c16fb890d35e4c1cf9186dd024 to your computer and use it in GitHub Desktop.
Save jeremiq/4038d8c16fb890d35e4c1cf9186dd024 to your computer and use it in GitHub Desktop.
import heapq
from typing import List
def kthsmallest1(l: List[int], k: int) -> int: # nlogk
if k > len(l):
return min(l)
l = [-1 * elt for elt in l]
h: List[int] = []
# O(log k)
for elt in l[:k]:
heapq.heappush(h, elt)
for elt in l[k:]:
if elt in h:
pass
else:
# O(n log k) worst case
heapq.heappushpop(h, elt)
return -1*heapq.heappop(h)
def test_kth_smallest1():
assert 3 == kthsmallest1(range(10), 4)
test_kth_smallest1()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment