class Solution { public int[] getSubarrayBeauty(int[] nums, int k, int x) { TreeMap<Integer,Integer> map = new TreeMap<>(); int n = nums.length; //adding first k numbers for(int i = 0 ;i < k ;i++) map.put(nums[i] , map.getOrDefault(nums[i] , 0) + 1); //finding ans for first k ints int ans[]= new int[n - (k-1)]; ans[0] = solve(map , x); for(int j= k , i = 0 ; j < n ; j++ , i++){ //removing last and adding next elem; map.put(nums[i] , map.get(nums[i]) - 1); map.put(nums[j] ,map.getOrDefault(nums[j],0) + 1); if(map.get(nums[i]) == 0) map.remove(nums[i]); ans[j - k + 1] = solve(map , x); } return ans; } public int solve(TreeMap<Integer,Integer> map ,int x){ //finding xth smallest element through treemap int count = 0; for(int val : map.keySet()){ count += map.get(val); if(count >= x){ return val < 0 ? val : 0; } } return 0; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter