Question Bank
/

JavaScript Top-N Numbers (Preserving Order): Two Approaches Quiz

JavaScript Top-N Numbers (Preserving Order): Two Approaches Quiz

Return the N largest numbers from an array while keeping their original order, two ways (sort-and-filter-back and threshold partition), plus two companions on ties and a heap-style streaming variant.

Question Bank
Hard
JavaScript
quiz
arrays
sorting
array-manipulation-patterns

613 views

8

Implement topMax(arr, n) using a SORT-AND-FILTER-BACK approach: sort a copy to find the top-N values, then walk the original array and keep only elements that appear in that top-N set, preserving original order.

Examples

Example 1:

Input: arr = [3, 5, 1, 8, 6, 2, 4], n = 2
Output: [8, 6]
Explanation: The top two values are 8 and 6; in the original array, 8 appears before 6.

Example 2:

Input: arr = [3, 5, 1, 8, 6, 2, 4], n = 3
Output: [5, 8, 6]
Explanation: The top three values are {5, 6, 8}; iterating in original order yields 5, 8, 6.

3 more questions, with full solutions and explanations, are available for premium members.

Upgrade to Premium