Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

kth-largest-element-in-array throws Exceptions for edge cases #269

Open
shermanflan opened this issue Dec 2, 2019 · 0 comments
Open

kth-largest-element-in-array throws Exceptions for edge cases #269

shermanflan opened this issue Dec 2, 2019 · 0 comments

Comments

@shermanflan
Copy link

The given solution in Python throws a TypeError for the given example and IndexError for other examples. A couple of suggested changes:

  1. Use integer division in line 13
  2. 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants