FastPrepKth Largest Array Element
Problems/Kth Largest Array Element

Kth Largest Array Element

Morgan Stanley logoMorgan Stanley● MediumINTERNONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The judged task matches the reported rank-selection tasks at about 90%. One author asks for the kth largest array element; another asks for the second largest and explicitly raises whether duplicates count, without reporting the interviewer’s answer. This practice chooses positional ranks, so duplicate occurrences count separately. The interface, bounds and nonmutation rule are practice assumptions.

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 value5under this positional convention, while its second distinct value would be4. Return the value, not its index. For this exercise, leave nums unchanged.

Function

kthLargest(nums: int[], k: int) → int

Examples

Example 1

nums = [5,5,4]k = 2return = 5

The descending occurrences are [5,5,4]. Position2contains5, so duplicates are not removed.

Example 2

nums = [3,2,1,5,6,4]k = 2return = 5

The descending occurrences are [6,5,4,3,2,1]. Position2contains5.

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 problems

  • Unique Grid PathsPHONE SCREEN · Seen Oct 2026
  • Unique Grid PathsPHONE SCREEN · Seen Oct 2026
  • Generate Strings of Length at Least ThreeONSITE INTERVIEW · Seen Sep 2026
All Morgan Stanley interview questionsSee Morgan Stanley hiring insights
Saved
public int kthLargest(int[] nums, int k) {
    // Write your code here.
}
Checking account…