I was working on kth largest element problem on leetcode
Question
Given an integer array nums and an integer k, return the kth largest element in the array.
Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: nums = [3,2,1,5,6,4], k = 2 Output: 5
Example 2:
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 Output: 4
My Solution
I'm basically setting every max element in array to Minimum possible integer and doing this k times.
Then i just calculate the maximum value in the array.
class Solution { public int findKthLargest(int[] nums, int k) { for(int i = 0; i < k-1; i++){ replaceLargestWithMin(nums); } return findLargest(nums); } //TC: O(N) public void replaceLargestWithMin(int[] nums){ // O(N) int currMax = findLargest(nums); // O(N) for(int i = nums.length - 1; i >= 0; i--){ if(nums[i] == currMax){ nums[i] = Integer.MIN_VALUE; break; } } } //TC: O(N) public int findLargest(int[] nums){ int max = nums[0]; for(int num : nums){ max = Math.max(max, num); } return max; } }
As per my understanding the time complexity of solution will be kO(n) ~ O(n)
which is same for heap solution.
However, the above solution is performing in the lower 5 percentile solutions in java.
Is this solution not in O(n)? Am I calculating the time complexity incorrectly?
EDIT:
Updated solution after doing changes suggested by vvotan
in comments:
class Solution { public int findKthLargest(int[] nums, int k) { for(int i = 0; i < k-1; i++){ replaceLargestWithMin(nums); } return nums[findLargest(nums)]; } public void replaceLargestWithMin(int[] nums){ nums[findLargest(nums)] = Integer.MIN_VALUE; } public int findLargest(int[] nums){ int maxIndex = 0; for(int i = 0; i < nums.length; i++){ if(nums[maxIndex] < nums[i]){ maxIndex = i; } } return maxIndex; } }
This increases the overall performance (only tested on leetcode) ~ 15%
k
is fixed (or small compared ton
). Only then the conclusionkO(n) ~ O(n)
holds. In the worst casek ~ n
the time complexity degrades to \$O(n^2)\$.\$\endgroup\$