Kth Largest Element in an Array - Complete Solution Guide
Kth Largest Element in an Array is LeetCode problem 215, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
Given an integer array nums and an integer k , return the k th largest element in the array . Note that it is the k th largest element in the sorted order, not the k th 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 <= 10 5 -10 4 <= nums[i] <= 10 4
Detailed Explanation
The problem asks us to find the k-th largest element in an unsorted integer array. Importantly, it's the k-th largest element in the *sorted* order, not the k-th *distinct* element. For example, in `[3, 2, 1, 5, 6, 4]` if `k=2`, the sorted array is `[1, 2, 3, 4, 5, 6]`, and the 2nd largest element is 5. The constraints state that `1 <= k <= nums.length <= 10^5` and `-10^4 <= nums[i] <= 10^4`.
Solution Approach
The provided solution uses the Quickselect algorithm, a variation of Quicksort, to find the k-th largest element without fully sorting the array. The algorithm works by repeatedly partitioning the array around a pivot element. The goal is to place the pivot element in its correct sorted position. After partitioning, if the pivot's index is equal to `n - k` (where `n` is the length of the array), then the pivot element is the k-th largest element, and we return it. If the pivot's index is less than `n - k`, it means the k-th largest element is in the right partition, so we recursively search in the right partition. Otherwise, the k-th largest element is in the left partition, and we search there.
Step-by-Step Algorithm
- Step 1: Calculate the target index: `target_index = n - k`, where `n` is the length of the input array `nums`. This index represents the position of the k-th largest element in the sorted array.
- Step 2: Initialize `left` and `right` pointers to the start and end of the array, respectively. These pointers define the search space within the array.
- Step 3: While `left` is less than or equal to `right`, perform the following steps (the core Quickselect logic):
- Step 4: Choose a random pivot index `pivot_idx` within the current search space (`left` to `right`). This helps to avoid worst-case scenarios for skewed arrays.
- Step 5: Move the pivot element to the end of the current search space by swapping `nums[pivot_idx]` and `nums[right]`.
- Step 6: Initialize `store_idx` to `left`. This index will keep track of the boundary between elements smaller than the pivot and elements greater than or equal to the pivot.
- Step 7: Iterate through the current search space from `left` to `right - 1`. For each element `nums[i]`, if it's less than the `pivot_val`, swap it with the element at `nums[store_idx]` and increment `store_idx`.
- Step 8: After the loop, swap the pivot element (currently at `nums[right]`) with the element at `nums[store_idx]`. This places the pivot element in its final sorted position within the current search space.
- Step 9: Check if `store_idx` is equal to `target_index`. If so, the k-th largest element is `nums[store_idx]`, and we return it.
- Step 10: If `store_idx` is less than `target_index`, the k-th largest element is in the right partition, so update `left = store_idx + 1` and continue the loop.
- Step 11: If `store_idx` is greater than `target_index`, the k-th largest element is in the left partition, so update `right = store_idx - 1` and continue the loop.
Key Insights
- Insight 1: The problem can be solved without fully sorting the array, leading to a more efficient solution than using standard sorting algorithms.
- Insight 2: Quickselect algorithm provides an efficient way to find the k-th largest element by partitioning the array around a pivot, similar to Quicksort.
- Insight 3: Randomly choosing the pivot helps to avoid worst-case time complexity scenarios, especially for potentially skewed input arrays.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Array, Divide and Conquer, Sorting, Heap (Priority Queue), Quickselect.
Companies
Asked at: AMD, Accenture, Avito, ByteDance, Coupang, Deloitte, Deutsche Bank, EPAM Systems, Flipkart, Goldman Sachs, Guidewire, Infosys, Intuit, J.P. Morgan, LinkedIn, Morgan Stanley, Nvidia, Oracle, PayPal, Pocket Gems, Qualcomm, SAP, SIG, Salesforce, Samsung, ServiceNow, Spotify, Turing, Verily, Walmart Labs, Wipro, Yandex, eBay.