Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Sliding subarray beauty

This is a fixed sizeSlidingWindow Problem

Problem

TC: O(n*100) = O(n)
SC:O(n) for using HashMap for storing the frequency of nums[i]

classSolution{publicint[]getSubarrayBeauty(int[]nums,intk,intx){Map<Integer,Integer>map=newHashMap<>();intleft=0,right=0;intindex=0;intarr[]=newint[nums.length-k+1];while(right<nums.length){// keep frequency count of each no. in the numsmap.put(nums[right],map.getOrDefault(nums[right],0)+1);if(right-left+1>k){//if any time window size become more than k, remove decrease frequency of nums[left] from the map and increment left pointerintc=map.get(nums[left]);if(c==1)map.remove(nums[left]);// if c ==1 then c-- = 0, remove that no. from the mapelse{map.put(nums[left],c-1);// else decrease the frequency by 1}left++;}if(right-left+1==k){// if we have reached the window size find the xth smallest negative no. else put 0 for this windowintcount=0;for(inti=-50;i<=50;i++){// since the values in the nums are between -50 to + 50if(map.containsKey(i)){// -50,-49,-48,-47.......+50 ( we are checking till we find the xth smallest)count+=map.get(i);// if the a number say -N comes 2 times then we increment the counter by 2if(count>=x){// at any point if count is = x or greater than x then we have found the xth smallest value in the array//if the xth smallest number is non negative consider 0 in this case else i(as i is the xth smallest the window of size k)if(i<0){arr[index++]=i;}elsearr[index++]=0;break;}}}}right++;}returnarr;}}
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

There is always a price for those who persevere.
  • Location
    India
  • Education
    Computer Science
  • Work
    Software Engineer @JPMorganChase&Co.
  • Joined

More fromPrashant Mishra

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp