Kth largest element in an array
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given[3,2,1,5,6,4]
and k = 2, return 5.
Note: You may assume k is always valid, 1 ≤ k ≤ array's length.
Idea: First sorting and then finding is an easier solution. But time complexity would be O(n logn) Idea: Use the partition method of quickSort and then determine the position of the pivotElement. Based on that calculate the new k and either the right or the left side of the array. Keep recursing. In this case time complexity is O(n)
T(n) = O(n) + T(n/2)
n + n/2 + n/4 + =~O(n)
Last updated
Was this helpful?