πDay 1. K Largest Elements π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given an array arr[] of positive integers and an integer k, your task is to return the k largest elements in decreasing order.
π Example Walkthrough:
Example 1:
Input:
arr = [12, 5, 787, 1, 23]
k = 2Output:
[787, 23]Explanation:
The 1st largest element is 787.
The 2nd largest element is 23.
Example 2:
Input:
Output:
Explanation:
The 3 largest elements in descending order are 50, 30, and 23.
Example 3:
Input:
Output:
Explanation:
The 1st largest element is 23.
Constraints:
$(1 \leq k \leq arr.size() \leq 10^6)$
$(1 \leq arr[i] \leq 10^6)$
π― My Approach:
Optimized Partial Sort (O(N + K log K) Time, O(1) Space)
Use
nth_element()to partition theklargest elements inO(N).Use
partial_sort()to sort the topkelements inO(K log K).Extract and return the
klargest elements in descending order.
Algorithm Steps:
Use
nth_element()to place the k-th largest element atarr.end() - k.Use
partial_sort()to sort only the k largest elements in descending order.Return the last
kelements inarr.
π Time and Auxiliary Space Complexity
Expected Time Complexity:
O(N + K log K), due to partitioning and sorting.Expected Auxiliary Space Complexity:
O(1), since sorting is done in-place.
π Solution Code
Code (C++)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated