Open
Description
The given solution in Python throws a TypeError
for the given example and IndexError
for other examples. A couple of suggested changes:
- Use integer division in line 13
- Adjust k only once
Something like this:
def kth_largest(l, k):
"""
Shorthand Quicksort
Runtime: O(n * log n)
"""
# kth largest element
# is k-1th element in output
def qsort(arr, pos):
middle = len(arr)//2
pivot = arr[middle]
smaller = [i for i in arr if i < pivot]
if pos < len(smaller):
return qsort(smaller, pos)
equal = [i for i in arr if i == pivot]
if pos < len(smaller) + len(equal):
return pivot
larger = [i for i in arr if i > pivot]
return qsort(larger, pos - len(smaller) - len(equal))
return qsort(l, k-1)