FastPrepFourth Largest Element in an Array

Fourth Largest Element in an Array

Bank of America logoBank of America● EasyNEW GRADONSITE INTERVIEW

Updated

Problem statement

Given an integer array nums with at least four elements, return the fourth largest element.

The fourth largest element is the value in fourth place when nums is sorted from largest to smallest. Equal values count as separate elements, so the answer can equal a larger-ranked value.

Function

fourthLargest(nums: int[]) → int

Examples

Example 1

nums = [7,2,9,4,1,8]return = 4

From largest to smallest the values are 9, 8, 7, 4, 2, 1. The fourth one is 4.

Example 2

nums = [3,10,10,6,10]return = 6

From largest to smallest the values are 10, 10, 10, 6, 3. The three copies of 10 take the first three places, so the fourth is 6.

Example 3

nums = [-5,-1,-9,-3]return = -9

From largest to smallest the values are -1, -3, -5, -9. With exactly four elements, the fourth largest is the smallest one, -9.

Constraints

  • 4 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9

More Bank of America Onsite Interview questions

Similar questions at other companies

Bank of America interview experiences

All Bank of America interview questionsSee Bank of America hiring insights
Saved
class Solution {
    public int fourthLargest(int[] nums) {
        // write your code here
    }
}
Checking account…