KatInterview

215. Kth Largest Element in an Array

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the k-th largest element in an unsorted array. It's important to note that this is the k-th largest element in the sorted order, not the k-th distinct element. For example, in [3, 2, 3, 1], the 1st largest is 3, the 2nd largest is also 3, and the 3rd largest is 2.

Solution

Kth Largest Element in an Array in Python

import random

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        """
        Uses the Quickselect algorithm.
        The k-th largest element is the (n-k)-th smallest element.
        We want to find the element that would be at index (n-k) if the array were sorted.
        """
        n = len(nums)
        target_index = n - k
        
        left, right = 0, n - 1

        while left <= right:
            # Lomuto partition scheme with a random pivot
            # to avoid worst-case O(N^2) performance.
            pivot_index = random.randint(left, right)
            
            # Move pivot to the end of the current partition range
            pivot_value = nums[pivot_index]
            nums[pivot_index], nums[right] = nums[right], nums[pivot_index]
            
            # `store_index` will be the final position of the pivot
            store_index = left
            for i in range(left, right):
                if nums[i] < pivot_value:
                    nums[store_index], nums[i] = nums[i], nums[store_index]
                    store_index += 1
            
            # Move the pivot to its final sorted position
            nums[right], nums[store_index] = nums[store_index], nums[right]
            
            # Check if we found the target element
            if store_index == target_index:
                return nums[store_index]
            elif store_index < target_index:
                # The target is in the right part of the array
                left = store_index + 1
            else: # store_index > target_index
                # The target is in the left part of the array
                right = store_index - 1
        
        return -1 # Should not be reached

Kth Largest Element in an Array in Java

import java.util.Random;

class Solution {
    private int[] nums;
    private Random rand = new Random();

    public int findKthLargest(int[] nums, int k) {
        this.nums = nums;
        int n = nums.length;
        // The k-th largest element is at index n-k in a sorted array (0-indexed).
        int targetIndex = n - k;
        int left = 0, right = n - 1;

        while (left <= right) {
            // Choose a random pivot index
            int pivotIndex = left + rand.nextInt(right - left + 1);
            
            // Partition the array around the pivot and get the pivot's final sorted position
            int finalPivotIndex = partition(left, right, pivotIndex);

            if (finalPivotIndex == targetIndex) {
                return this.nums[finalPivotIndex];
            } else if (finalPivotIndex < targetIndex) {
                // The target is in the right subarray
                left = finalPivotIndex + 1;
            } else {
                // The target is in the left subarray
                right = finalPivotIndex - 1;
            }
        }
        return -1; // Should not be reached
    }

    private int partition(int left, int right, int pivotIndex) {
        int pivotValue = this.nums[pivotIndex];
        // 1. Move pivot to end
        swap(pivotIndex, right);
        int storeIndex = left;

        // 2. Move all smaller elements to the left
        for (int i = left; i < right; i++) {
            if (this.nums[i] < pivotValue) {
                swap(storeIndex, i);
                storeIndex++;
            }
        }

        // 3. Move pivot to its final place
        swap(storeIndex, right);

        return storeIndex;
    }

    private void swap(int a, int b) {
        int temp = this.nums[a];
        this.nums[a] = this.nums[b];
        this.nums[b] = temp;
    }
}

Kth Largest Element in an Array in C++

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        int n = nums.size();
        int target_index = n - k;
        int left = 0, right = n - 1;

        // Seed for random number generation
        srand(time(0));

        while (left <= right) {
            // Choose a random pivot and move it to the end
            int pivot_idx = left + rand() % (right - left + 1);
            int pivot_val = nums[pivot_idx];
            swap(nums[pivot_idx], nums[right]);

            // Partition the array using Lomuto partition scheme
            int store_idx = left;
            for (int i = left; i < right; ++i) {
                if (nums[i] < pivot_val) {
                    swap(nums[store_idx], nums[i]);
                    store_idx++;
                }
            }
            swap(nums[store_idx], nums[right]); // Move pivot to its final place

            // Check if the pivot is the k-th largest element
            if (store_idx == target_index) {
                return nums[store_idx];
            } else if (store_idx < target_index) {
                // The element is in the right subarray
                left = store_idx + 1;
            } else {
                // The element is in the left subarray
                right = store_idx - 1;
            }
        }

        return -1; // Should not be reached given the constraints
    }
};

Kth Largest Element in an Array in TypeScript

function findKthLargest(nums: number[], k: number): number {
    const n = nums.length;
    // The k-th largest element is at index n-k in a sorted array (0-indexed).
    const targetIndex = n - k;
    let left = 0;
    let right = n - 1;

    const swap = (i: number, j: number) => {
        [nums[i], nums[j]] = [nums[j], nums[i]];
    };

    const partition = (left: number, right: number, pivotIndex: number): number => {
        const pivotValue = nums[pivotIndex];
        // 1. Move pivot to end
        swap(pivotIndex, right);
        let storeIndex = left;

        // 2. Move all smaller elements to the left
        for (let i = left; i < right; i++) {
            if (nums[i] < pivotValue) {
                swap(storeIndex, i);
                storeIndex++;
            }
        }

        // 3. Move pivot to its final place
        swap(storeIndex, right);
        return storeIndex;
    };

    while (left <= right) {
        // Choose a random pivot to avoid worst-case performance
        const pivotIndex = Math.floor(Math.random() * (right - left + 1)) + left;

        const finalPivotIndex = partition(left, right, pivotIndex);

        if (finalPivotIndex === targetIndex) {
            return nums[finalPivotIndex];
        } else if (finalPivotIndex < targetIndex) {
            // Target is in the right subarray
            left = finalPivotIndex + 1;
        } else {
            // Target is in the left subarray
            right = finalPivotIndex - 1;
        }
    }

    return -1; // Should not be reached given the constraints
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.