Kth Largest Array Element
Updated
Problem statement
Given an unsorted integer array nums and a one-based rank k, return its kth largest value. For this exercise, count every array occurrence, including duplicates. Equivalently, sort all occurrences in nonincreasing order and select position k.
The second-largest task is the case k=2. For example, [5,5,4] has second-largest value 5 under this positional convention, while its second distinct value would be 4. Return the value, not its index. For this exercise, leave nums unchanged.
Function
kthLargest(nums: int[], k: int) → intExamples
Example 1
nums = [5,5,4]k = 2return = 5The descending occurrences are [5,5,4]. Position 2 contains 5, so duplicates are not removed.
Example 2
nums = [3,2,1,5,6,4]k = 2return = 5The descending occurrences are [6,5,4,3,2,1]. Position 2 contains 5.
Constraints
- For this exercise, assume 1 <= nums.length <= 2000.
- For this exercise, assume -1000000 <= nums[i] <= 1000000.
- For this exercise, assume 1 <= k <= nums.length.
More Morgan Stanley Onsite Interview questions
- Generate Strings of Length at Least ThreeONSITE INTERVIEW · Seen Sep 2026
- Maximum Concurrent ProcessesOA · ONSITE INTERVIEW · Seen Sep 2026
- Run-Length Encode Consecutive Letter RunsONSITE INTERVIEW · Seen Jul 2026
- Maximum Edge Removals for Two TravelersONSITE INTERVIEW · Seen Oct 2025
- Remove K DigitsONSITE INTERVIEW · Seen Oct 2025
- Count Ideal ArraysONSITE INTERVIEW · Seen Aug 2023
- Distinct Palindrome PartitionsONSITE INTERVIEW · Seen Aug 2023
- LFU Cache OperationsONSITE INTERVIEW · Seen Aug 2023
- All-Pairs Shortest PathsOA · ONSITE INTERVIEW · Seen Feb 2022
- Fibonacci with Input ValidationONSITE INTERVIEW · Seen Feb 2022
Similar questions at other companies
- Tennis Court SchedulingAtlassian · PHONE SCREEN · ONSITE INTERVIEWAtlassian interview questions
- Retrieve Vectors by Cosine SimilarityHarvey · ONSITE INTERVIEWHarvey interview questions
- Minimize Total Weight After HalvingAmazon · ONSITE INTERVIEW
- Top K Largest Values from a StreamThe D.E. Shaw Group · ONSITE INTERVIEWThe D.E. Shaw Group interview questions
- Generate Complete Inputs for a Supplied ClassifierGeneral Motors · ONSITE INTERVIEW
- Minimum Meeting Rooms Without a Sweep LineGoldman Sachs · ONSITE INTERVIEWGoldman Sachs interview questions
- Dominant Index with Strict Doubling GapsGoogle · ONSITE INTERVIEWGoogle interview questions
- Top K Largest Values with a HeapMeta · ONSITE INTERVIEWMeta interview questions
- Top K Frequent ElementsCapgemini · ONSITE INTERVIEWCapgemini interview questions
- Kth Largest Element in an ArrayOneTrust · ONSITE INTERVIEW