Find M Largest Numbers

MEDIUM

Given a long list of unsorted numbers (potentially millions of items) and an integer m, write a function to find the m largest numbers in the list. The order of the m largest numbers in the output does not matter.

Examples:

Example 1:

Input: nums = [3, 2, 1, 5, 6, 4], m = 2
Output: [5, 6] (or [6, 5])

Example 2:

Input: nums = [1, 23, 12, 9, 30, 2, 50], m = 3
Output: [23, 30, 50] (any order)

Example 3:

Input: nums = [1, 1, 1, 1, 1], m = 3
Output: [1, 1, 1]

Constraints:

  • 1 <= m <= nums.length <= 106
  • -109 <= nums[i] <= 109
  • The problem implies finding m numbers; if there are duplicates among the largest, they should be included if they qualify.

Function Signature (Python):

from typing import List

class Solution:
    def findMLargest(self, nums: List[int], m: int) -> List[int]:
        # Your code here
        pass

 

Nerchuko Academy · Free DS Interview Prep