<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>largest element in the array</em>.</p>

<p>Note that it is the <code>k<sup>th</sup></code> largest element in the sorted order, not the <code>k<sup>th</sup></code> distinct element.</p>

<p>Can you solve it without sorting?</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [3,2,1,5,6,4], k = 2
<strong>Output:</strong> 5
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [3,2,3,1,2,4,5,5,6], k = 4
<strong>Output:</strong> 4
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
</ul>

import heapq
class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        return heapq.nlargest(k, nums)[-1]
        

        #"""
# min heap by default
# time complexity: O(nlog(k))
class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        hq_min = []
        for i in range(len(nums)): 
            if k > 0: 
                heapq.heappush(hq_min, nums[i])
            else: 
                heapq.heappushpop(hq_min, nums[i])

            k -= 1
            
        #return heapq.heappop(hq_min) # should not return hq_min.pop() which return the last one the list only. 
        return hq_min[0] # 
#"""
    
    
#"""
# quick select
# Time complexity:  O(N) in the average case, O(N^2) in the worst case.
# Space complexity: O(1)
# top k: 

class Solution:
    def findKthLargest(self, nums, k):
        if not nums: return
        
        pivot = random.choice(nums)        
        # left = right = mid = [] # this causes issues, it is wrong
        left, right, mid = [], [], []
        
        for x in nums:  # O(N)
            if x < pivot: left.append(x)
            elif x == pivot: mid.append(x)
            else: right.append(x)
            
        r_size, m_size = len(right), len(mid)
        
        if k <= r_size: # right side has all the k largest elemets
            return self.findKthLargest(right, k)
        elif k > r_size + m_size: # the kth largest elements in the left side
            return self.findKthLargest(left, k - r_size - m_size)
        else: # the kth largest element in the mid
            return mid[0]
#"""
30812