DEV Community

Ruairí O'Brien
Ruairí O'Brien

Posted on

Day 16 - Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Enter fullscreen mode Exit fullscreen mode

Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.

My Tests

Link to code

import pytest
from .Day16_KthLargestElementInAnArray import Solution

s = Solution()


@pytest.mark.parametrize(
    "nums,k,expected",
    [
        ([3,2,1,5,6,4], 2, 5),
        ([3,2,3,1,2,4,5,5,6], 4, 4),

    ],
)
def test_get_maximum_generated(nums, k, expected):
    assert s.findKthLargest(nums, k) == expected
Enter fullscreen mode Exit fullscreen mode

My Solution

Link to code

from typing import List


class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        return sorted(nums)[len(nums) - k]
Enter fullscreen mode Exit fullscreen mode

Analysis

Alt Text

Alt Text

My Commentary

Sorting the array and finding the kth from the end is clearly not the best solution but it's the simplest and it's Saturday.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay