π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 = 2
Output:
[787, 23]
Explanation:
The 1st largest element is 787.
The 2nd largest element is 23.
Example 2:
Input:
arr = [1, 23, 12, 9, 30, 2, 50]
k = 3
Output:
[50, 30, 23]
Explanation:
The 3 largest elements in descending order are 50, 30, and 23.
Example 3:
Input:
arr = [12, 23]
k = 1
Output:
[23]
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 thek
largest elements inO(N)
.Use
partial_sort()
to sort the topk
elements inO(K log K)
.Extract and return the
k
largest 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
k
elements 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++)
class Solution {
public:
vector<int> kLargest(vector<int>& arr, int k) {
nth_element(arr.begin(), arr.end() - k, arr.end());
partial_sort(arr.end() - k, arr.end(), arr.end(), greater<int>());
return vector<int>(arr.end() - k, arr.end());
}
};
Code (Java)
class Solution {
public ArrayList<Integer> kLargest(int[] arr, int k) {
Arrays.sort(arr);
ArrayList<Integer> res = new ArrayList<>();
for (int i = arr.length - 1; i >= arr.length - k; i--) res.add(arr[i]);
return res;
}
}
Code (Python)
class Solution:
def kLargest(self, arr, k):
return sorted(arr, reverse=True)[:k]
π― 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