Taro Logo

Kth Largest Element in an Array

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+32
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
2K views
Topics:
ArraysTwo Pointers

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Can you solve it without sorting?

Example 1:

Input: nums = [3,2,1,5,6,4], k = 2
Output: 5

Example 2:

Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4

Constraints:

  • 1 <= k <= nums.length <= 105
  • -104 <= nums[i] <= 104

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of values inside the nums array, and what are the possible values for k relative to the array's length?
  2. Can the input array contain duplicates, and if so, how should they affect the count when finding the kth largest element?
  3. Can the array contain negative numbers, zeros, or be exceptionally large, and do I need to worry about integer overflow?
  4. Should the solution modify the original input array (in-place), or is it expected that I leave the original array unmodified?
  5. Are there any memory or space complexity constraints I should keep in mind, such as operating within O(1) extra space?

Brute Force Solution

Approach

Imagine you have a big pile of unsorted numbers and you want to find a specific favorite, such as the third largest number. The brute force approach involves looking at every possible way of organizing or comparing the numbers until you are completely sure you have found the exact one you are looking for.

Here's how the algorithm would work step-by-step:

  1. Start by taking the entire collection of numbers and laying them out in order from smallest to largest.
  2. Look at the sorted collection and count backwards from the biggest number to find the one that matches your target position.
  3. Double check your count to ensure you have skipped the correct number of larger items.
  4. Select that specific number as your answer.

Code Implementation

def find_kth_largest(numbers_list, target_rank):
    # Sort the entire collection from smallest to largest to establish a clear ordering
    sorted_numbers = sorted(numbers_list)

    # Count backwards from the largest element to locate the target rank position
    target_index = len(sorted_numbers) - target_rank

    # Select the specific number at the calculated index as our final answer
    return sorted_numbers[target_index]

Big(O) Analysis

Time Complexity
O(n log n) – The strategy begins by taking the entire collection of n numbers and laying them out in order from smallest to largest using a sorting algorithm. Sorting an array of size n inherently drives the cost by requiring n log n comparison operations. Once the collection is fully sorted, accessing the kth largest element takes constant time by counting backwards from the end. Therefore, the total operations approximate n log n due to the sorting step, which simplifies to O(n log n).
Space Complexity
O(n) – The plain English steps describe laying out the entire collection of numbers in order, which implies creating a sorted copy or temporary structure holding all input elements. When you sort or store all elements from the pile of size N, the extra memory required scales directly with that input size. Specifically, auxiliary structures or sorting algorithms allocate memory proportional to the number of items being organized. Therefore, the total extra memory approximates N, resulting in a linear space complexity of O(N).

Optimal Solution

Approach

Instead of sorting the entire collection of items, the optimal strategy uses a clever shrinking technique inspired by sorting to narrow down the search. By making strategic guesses and throwing away half of the possibilities that we know cannot be the answer, we quickly hone in on the target item with remarkable speed.

Here's how the algorithm would work step-by-step:

  1. Pick a random item from the group to serve as your testing point.
  2. Divide the rest of the items into two groups: those that are larger than your testing point, and those that are smaller.
  3. Count how many items ended up in the group of larger items to understand where your testing point ranks overall.
  4. Compare that rank directly against the target position you are trying to find.
  5. If the larger group happens to contain the exact position you are looking for, completely ignore the testing point and the smaller group, and repeat the process focusing only on that larger group.
  6. If your target position is past the larger group, ignore the larger group and the testing point, and focus only on the smaller group.
  7. Stop the process immediately once the random testing point lands right on your target position, meaning you have successfully found your answer without wasting time organizing the rest of the items.

Code Implementation

import random

class Solution:
    def findKthLargest(self, input_numbers: list[int], target_rank: int) -> int:
        target_index = target_rank - 1
        left_boundary = 0
        right_boundary = len(input_numbers) - 1

        while left_boundary <= right_boundary:
            pivot_index = random.randint(left_boundary, right_boundary)
            pivot_value = input_numbers[pivot_index]

            input_numbers[pivot_index], input_numbers[right_boundary] = input_numbers[right_boundary], input_numbers[pivot_index]

            store_index = left_boundary
            for current_index in range(left_boundary, right_boundary):
                if input_numbers[current_index] > pivot_value:
                    input_numbers[store_index], input_numbers[current_index] = input_numbers[current_index], input_numbers[store_index]
                    store_index += 1

            input_numbers[right_boundary], input_numbers[store_index] = input_numbers[store_index], input_numbers[right_boundary]

            # Stop when the pivot lands directly on the target position to avoid unnecessary searching.
            if store_index == target_index:
                return input_numbers[store_index]

            # Narrow the search space to the left partition if the target index is smaller than the pivot.
            elif store_index > target_index:
                right_boundary = store_index - 1

            # Narrow the search space to the right partition if the target index is larger than the pivot.
            else:
                left_boundary = store_index + 1

Big(O) Analysis

Time Complexity
O(n) – In each step of the quickselect algorithm, we partition the array around a randomly chosen pivot, which requires visiting roughly n elements in the current search space. Because we strategically discard half of the elements and only recurse into one side, the problem size shrinks by half each time on average. This leads to a geometric series of work represented as n + n/2 + n/4 + ... + 1 operations. Summing this convergent series results in approximately 2n total operations, which simplifies to an optimal linear time complexity of O(n) on average.
Space Complexity
O(log N) – The space complexity is driven entirely by the recursion stack used during the shrinking search process. In the average case, randomly partitioning the items divides the search space in half repeatedly, leading to a maximum recursion depth proportional to the logarithm of the input size N. In the worst-case scenario with poor random pivot choices, the depth can stretch to N, but randomized Quickselect achieves an expected auxiliary space complexity of O(log N). No extra arrays or hash maps are created, as all partitioning operations happen in place within the original input collection.

Edge Cases

Array with a single element where k equals 1
How to Handle:
Quickselect or heap approach instantly returns that single element without further iteration.
Array containing many duplicate elements and k falling within the duplicate range
How to Handle:
Algorithms like Quickselect handle duplicates efficiently through three-way partitioning around the pivot.
Array containing negative numbers and mixed signs
How to Handle:
Comparison logic correctly evaluates values below zero since the relative ordering of integers remains intact.
Extremely large inputs approaching memory limits
How to Handle:
An in-place Quickselect approach avoids extra memory allocation while a Min-Heap keeps space complexity bounded by k.
k equals the length of the array
How to Handle:
The algorithm correctly identifies the minimum element in the array as the kth largest element.
Sorted or reverse-sorted input arrays causing worst-case pivot selection
How to Handle:
Using a randomized pivot selection prevents worst-case quadratic time complexity in Quickselect.
Arrays with all identical values
How to Handle:
Partitioning schemes handle identical elements gracefully by grouping them together to terminate early.
0/75 completed