C++ 0215.cpp
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
auto n = nums.size() - k;
nth_element(nums.begin(), nums.begin() + n, nums.end());
return nums[n];
}
};
Difficulty
and has an acceptance rate of about 69% (5+ million submissions).
Typical patterns to solve this problem:
- Array
- Divide And Conquer
- Heap (Priority Queue)
- Quickselect
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single public method findKthLargest. The method receives a mutable reference to a vector of integers and an integer k, and returns the k-th largest element in the collection. The core of the algorithm relies on the standard library function nth_element, which partially sorts the container such that the element at a specified position is the same as it would be in a fully sorted array, while all elements before it are less than or equal to it and all elements after it are greater than or equal to it. By selecting the appropriate index, the method extracts the desired order statistic directly.
Key Steps
The method consists of three distinct operations:
- Compute the target index that corresponds to the k-th largest value when the vector is considered in ascending order.
auto n = nums.size() - k; - Invoke
nth_elementto rearrange the vector so that the element at positionnis the element that would appear there in a fully sorted sequence.nth_element(nums.begin(), nums.begin() + n, nums.end()); - Return the element now residing at index
n, which is the required k-th largest value.return nums[n];
Each step is expressed concisely, leveraging the expressive power of the C++ standard library.
Edge Cases
The algorithm implicitly handles several boundary conditions:
- When
kequals 1, the target index becomesnums.size() - 1, positioning the call tonth_elementsuch that the largest element is placed at the end of the vector. The final return yields the maximum value. - When
kequals the size of the vector, the target index becomes0. In this scenario,nth_elementensures that the smallest element occupies the first position, and the method returns the minimum value, which is the k-th largest whenkequals the total count. - An empty vector is not a valid input for this method because
kmust be a positive integer less than or equal to the vector size. The code assumes that the caller respects this contract, and the calculation ofnwould otherwise produce an underflow, which is avoided by proper usage. - Duplicate values are naturally accommodated because
nth_elementonly guarantees partitioning relative to the pivot; equal elements may appear on either side of the pivot without affecting the correctness of the returned order statistic.
Performance Optimizations
The primary optimization stems from the use of nth_element instead of a full sort. nth_element operates in linear average time, rearranging only the necessary portion of the data to locate the desired element. This avoids the O(n log n) cost of a complete sort when only a single order statistic is required.
By computing the index as nums.size() - k, the method directly targets the position that corresponds to the k-th largest element in ascending order, eliminating any need for additional transformations or reverse traversals.
The algorithm works in-place, requiring no auxiliary containers. This reduces memory overhead and improves cache locality, as the vector is rearranged directly without copying elements to temporary storage.
Overall, the implementation delivers an efficient solution for retrieving the k-th largest element with minimal computational and memory resources.
ELI5 - Simplified Explanation
Imagine you have a big messy pile of numbered blocks scattered across the floor. You want to pick out a specific one, like the third biggest block in the whole bunch.
The code starts by figuring out exactly where that special block should sit if you were to line everything up from smallest to largest. It uses a clever trick to rearrange the blocks so that the one you are looking for moves into its correct home. Instead of sorting the entire pile perfectly, it just makes sure the blocks smaller than your target are on one side and the blocks larger than your target are on the other side. Once the code finishes moving things around, the block sitting at that specific spot is exactly the one you wanted to find. It is like a magical game of musical chairs where the right block just lands right in front of you.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||||
| WalkCCC | C++ | Python | Java | ||||||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | |||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | AdelDaniel | Dart | |||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++ | ||||||||||||
| bujosa | Python | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| fsq | Python | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| gouthampradhan | Java | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| MacJim | C++ | ||||||||||||
| qiyuangong | Java | ||||||||||||
| ruoru | Rust | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| AdelDaniel | Dart | ||||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| bujosa | Python | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| fsq | Python | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| gouthampradhan | Java | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| MacJim | C++ | ||||||||||||
| qiyuangong | Java | ||||||||||||
| ruoru | Rust | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 347: Top K Frequent Elements
- problem 414: Third Maximum Number
- problem 703: Kth Largest Element in a Stream
- problem 1985: Find the Kth Largest Integer in the Array
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality