Frequency of the Most Frequent Element - Sliding Window - Leetcode 1838

Поделиться
HTML-код
  • Опубликовано: 23 ноя 2024

Комментарии • 133

  • @misoren9645
    @misoren9645 3 года назад +54

    If someone wants help with the intuition behind the condition, its basically asking from the current sliding window e.g. [1, 2, 4], how much do you need to convert it in [4, ,4 ,4], you would need 4 (nums[r]) times the window length (r - l + 1) - the sum of the current window. So nums[r]*(r-l+1) - sum, if this is affordable with budget k (nums[r]*(r-l+1) - sum

  • @daianabilbao2771
    @daianabilbao2771 2 года назад +65

    I love these explanation videos but sometimes I'm like... how did you come up with this solution? I feel I cannot come up with these solutions on my own. :(

    • @rishujeetrai5780
      @rishujeetrai5780 9 месяцев назад +5

      Don't judge your capabilities till you've solved/tried at least a 100 moderate/hard questions

    • @ashantinyongo7632
      @ashantinyongo7632 8 месяцев назад +18

      I’ve come to realize the vast majority people don’t come up with these solutions on their own. It’s implausible, what is more plausible is reading other people’s solutions and developing pattern recognition that helps you solve new problems.

    • @rishujeetrai5780
      @rishujeetrai5780 8 месяцев назад

      @@ashantinyongo7632 exactly like when you solve subarray sum problems, you see the first solution then there are over a dozen variation. Same with binary search and other algorithms

  • @abhayzz03
    @abhayzz03 4 месяца назад +2

    Great Explanation Thanks!, For All the java users out there, make sure you use "long" for total and res, wherever you are doing right - left + 1, make sure to convert it to right - left + 1L, while returning the res, you can typecast it simply by (int) res. Good Luck.

  • @rommeltito123
    @rommeltito123 2 года назад +37

    Excellent. I never thought I would watch coding videos right after waking up in the morning.

    • @Eddie4k
      @Eddie4k Год назад +1

      I find myself in this same morning routine every day now 😆

    • @TacticalDoge101
      @TacticalDoge101 10 месяцев назад +1

      same here lmao
      @@Eddie4k

  • @ducthinh2412
    @ducthinh2412 2 года назад +10

    great video! I just want to mention that for sliding window problem, we (generally) always advance the right pointer, so it's better for the outer loop to be a for loop instead of a while loop. That way you won't have to remember to increment the right pointer at the end.

  • @marhawk6468
    @marhawk6468 3 года назад +113

    There used to be a time I was afraid of leetcode. But thanks to you I no longer am

    • @NeetCode
      @NeetCode  3 года назад +39

      Haha that's awesome.. I'm sometimes still afraid of LC Hards tho 😱

    • @husler7424
      @husler7424 2 года назад +2

      @@NeetCode really ??😨😨same here....

    • @prathambhardwaj6797
      @prathambhardwaj6797 Год назад

      I wish I could become like you bro, soon enough !!

    • @yourlinuxguy
      @yourlinuxguy 5 месяцев назад

      I gave you the 100th like . 💘

    • @marhawk6468
      @marhawk6468 5 месяцев назад +1

      @@yourlinuxguy are we soulmates 👉👈

  • @koubbe
    @koubbe 3 года назад +18

    Recently discovered your channel. Easy to follow explanation, time complexity analysis, code in Python included. What else can we ask for? Please keep doing these videos.

  • @glorious_purp_123
    @glorious_purp_123 4 месяца назад

    or to simplify the inequality, (num[r] * windowlen - total < k).The num[r] * windowlen - total gives number of increments needed to make all the elements in that window and we can keep expanding this window until num[r] * windowlen - total > k.

  • @TheElementFive
    @TheElementFive 2 года назад +77

    A little far fetched to expect someone to be able to come up with that formula in an interview

    • @minciNashu
      @minciNashu 2 года назад +8

      This one is a 'sliding window' problem, there a bunch of other patterns to practice. So you kinda know what patterns to expect.

    • @TejaaaaaaReddy
      @TejaaaaaaReddy 9 месяцев назад

      But one needs to first figure out that it is a sliding window type problem @@minciNashu

    • @ttrey743
      @ttrey743 7 месяцев назад +7

      @@minciNashu The sliding window approach isn't hard to come up with. It's the formula used for the window bound check. I feel like that conditional check is what most people consider the hard part of the problem.

  • @zachyang1041
    @zachyang1041 10 месяцев назад +1

    I really like how you explain your thinking process like why are we sorting, why are we using sliding window here.
    Some people just explain the solutions without explaining why we are doing in that way.
    Thank.

  • @mahesh_kok
    @mahesh_kok 2 года назад

    hey @neetcode
    I admit that after seeing 5 back to back sliding window problem
    i attempted this problem on my own
    I was able to find solution to that in my own terms but was unable to make through all the test cases on leetcode
    i got almost 50 percent right test cases
    def maxFrequency(self, nums: List[int], k: int) -> int:
    arr = sorted(nums, reverse=True)
    diff = [0]
    max_ele = arr[0]
    for ele in arr[1:]:
    diff.append(max_ele - ele)
    rep = 0
    res = 0
    for d in diff:
    if rep + d

  • @RajPatel-qg1mm
    @RajPatel-qg1mm Год назад +2

    I came accross so many solution videos for this problem but I didn't understand any of those explanations until it yours. You gave the crystal clear explanation.... thank you so much sir..🙏

  • @AmitSingh-dc2gz
    @AmitSingh-dc2gz Год назад +6

    how do u arrive at that formula? what was ur thought process?

  • @techwills4619
    @techwills4619 3 года назад +3

    I first though of doing it with Dynamic programming. Essentially we create a modified array by incrementing a value the original array (as long as k>0) then we get the greatest frequency and recall the function recursively on the modified array. We update the greatest frequency if the recursive call produced a better value. Which results in O(n^k) time and O(n) space

  • @Chirayu19
    @Chirayu19 Год назад +2

    We can also do this by creating a frequency map. The approach mentioned in the video can be used but I came up with another appraoch.
    Create a frequency map.
    Check the answer for last element (max).
    Now come to the second last element.
    New answer would be the old answer - freq of last element
    + Now we can move the left pointer by (freq of curr element*diff of last and curr element), basically new k

    • @ananyagouda8200
      @ananyagouda8200 Год назад

      hey can you provide a pseudo code/code for this

  • @rishabhmalviya331
    @rishabhmalviya331 3 месяца назад

    nums[r] x (windowLen) is basically a hypothetical maximum area you can have with length as nums[r] and breadth as size of the window. Total is the sum of actual areas(each num having breath 1 and length as value of num) in the window. Now we check if hypothetical area - total area is lesser than K(assume K as increasing area of each number by one). If true then we can increase the actual area to be equal to hypothetical one(can only do this by increasing length of each num so that length of each num is equal).

  • @antibarcelona2123
    @antibarcelona2123 2 года назад +12

    for java users, declare the total variable as long and you're good to go;

    • @MGtvMusic
      @MGtvMusic Год назад

      Thanks mate, The total sum exceeds int limit at some point right?

  • @lalitshah9297
    @lalitshah9297 2 года назад +28

    Nice explanation but I guess the main question is how to arrive at this intuition/formula in interview setup? I mean, if I am seeing this question first time in interview setup - I am not sure how will I arrive at this formula.

    • @ramansdf
      @ramansdf 2 года назад +3

      I've figured out this pattern in 15 mins, and I'm not genius. Solved only 150 problems
      If you practice more, it's easy to come up with during the interview

    • @victoriatfarrell
      @victoriatfarrell 2 месяца назад +1

      You build the intuition by practicing other sliding window problems

  • @ersinerdem7285
    @ersinerdem7285 2 года назад +3

    in Java, need to declare total as long type. Otherwise fails in the latter long test cases.

  • @adududuke3995
    @adududuke3995 Год назад +1

    What if we start the two pointers from the right after sorting. That way we have a max variable that gets updated. So we increase the value at p2 till equals p1 while K is still available.
    Given ----- 1,2,3,5,7,10 and K = 8, p1 and p2 = 10. p2 moves to 7 ( edge case - if p2 === p2+1, we move p2 again p2-1) and we increase it to 10. K is now left with 5 and Max value is 2. p2 moves to 5 and we can take it to 10. K is now 0 and Max is updated to 3.
    SInce K is used up, we can now reset p1,p2 to 7, reset K to 8 and repeat

  • @ZQutui
    @ZQutui 3 года назад +9

    please keep up doing these videos, it's extremely helpful.

  • @ManishR-ov2gz
    @ManishR-ov2gz 3 месяца назад +2

    I have one doubt the sliding window condition/formula how do you guys come up with it ? I dont think I can ever look at a problem and just figure out a formula like that

  • @jabedhasan21
    @jabedhasan21 Год назад +1

    For some test cases, the total sum will overflow if you are writing the code in Java Or CPP. So int that case use this logic
    while (nums[r] * (r - l + 1) - total > k)

    • @harshilsutariya1793
      @harshilsutariya1793 Год назад

      but why ?

    • @yashwanthsai762
      @yashwanthsai762 Год назад

      can u pls explain

    • @aniketv2370
      @aniketv2370 4 месяца назад

      @@yashwanthsai762 because total+k turns out to be a big value which overflows so either typecast it as a long or use this formula

  • @anandsardesai301
    @anandsardesai301 3 месяца назад

    not sure how its going to work on input in above example like 1,1,1,2... & k = 2. Its saying that max window size is 3 at index = 2. But not sure how k=2 can be distributed to get that frequency.

  • @priyanshumakwana5034
    @priyanshumakwana5034 2 месяца назад

    Guys please correct me if I am wrong, but if we increment both the values of 1s by 1 each, thus exhausting our budget, won't the answer for the greatest frequency come out as 4 ( [ 1, 2, 2, 2, 2, 4] ) ? Since there will be 4 number of 2s now? How is this logic correct then?

  • @jonaskhanwald566
    @jonaskhanwald566 3 года назад +3

    keep posting. never stop

  • @vaishnavidaber5976
    @vaishnavidaber5976 2 месяца назад

    Such a great explanation. Thank you!

  • @abishekbaiju1705
    @abishekbaiju1705 Год назад +1

    I was not able to come up with that equation. I found the bruteforce way which of course resulted in TLE. Anyway thanks.

  • @TejaaaaaaReddy
    @TejaaaaaaReddy 9 месяцев назад +1

    I guess it is not easy to get this idea in an actual interview.

  • @VarunSharma-xd8xd
    @VarunSharma-xd8xd 7 месяцев назад

    class Solution {
    public int maxFrequency(int[] nums, int k) {
    int total = 0;
    int L = 0;
    int R = 0;
    int res = 0;
    Arrays.sort(nums);
    while (R < nums.length) {
    total += nums[R];
    while (nums[R] * (R - L + 1) > total + k) { // Corrected condition
    total -= nums[L];
    L++;
    }
    res = Math.max(res, R - L + 1);
    R++;
    }
    return res;
    }
    } why this code failing at 71/73 test case

    • @prapti2385
      @prapti2385 6 месяцев назад

      consider the total variable as long

  • @ndas9970
    @ndas9970 4 месяца назад

    The answer of the example shown is wrong, the output should be 4 not 2 (frequency).but the code works fine.

  • @himanshurathore9816
    @himanshurathore9816 Год назад +1

    at last one testcase failed and only one is remaining bro
    help it out!!!!
    testcase no 70

  • @sahilnegi2789
    @sahilnegi2789 3 года назад +1

    I think this que is hard for someone who is doing that que first time .

  • @stith_pragya
    @stith_pragya 10 месяцев назад

    Thank You So Much for this wonderful video.........................🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @ajaymishra1511
    @ajaymishra1511 2 месяца назад

    how we can do it with brute force or nested loop + hashing?

  • @jonaskhanwald566
    @jonaskhanwald566 3 года назад +1

    nobody can explain it better than you. when was this problem posted? I think recently it was..

  • @jonaskhanwald566
    @jonaskhanwald566 3 года назад +3

    Frequency of the Most Frequent Element
    similar problems below. If you have time, explain them too.
    Longest Subarray of 1's After Deleting One Element
    Constrained Subsequence Sum
    Number of Substrings Containing All Three Characters
    Count Number of Nice Subarrays
    Replace the Substring for Balanced String
    Max Consecutive Ones III
    Binary Subarrays With Sum
    Subarrays with K Different Integers
    Fruit Into Baskets
    Shortest Subarray with Sum at Least K
    Minimum Size Subarray Sum

  • @jonasp4682
    @jonasp4682 Год назад

    I'm a noob and for some reason I feel like it'd be easier to start with the right pointer at index len - 1, does that make sense?

  • @Ynno2
    @Ynno2 Год назад

    Do you have any tips for when to stop looking for a solution with a better complexity? I dismissed a bunch of O(n log n) solutions thinking there's probably an O(n) solution, then gave up in frustration and looked at the solutions, only to find O(n log n) is optimal.

  • @manishparab4427
    @manishparab4427 Год назад

    best explanation... I tried to solve this problem but could not figure out its sliding window

  • @amandubey5287
    @amandubey5287 2 года назад

    Hi neetcode. I just wanted to say thank you for all these videos. However I have a leetcode hard problem in sliding window of constant length i guess. Question name " Substring with concatenation of all words". this question has been troubling me for a while now. Can you please make a video on this. Thanks

  • @saipramod41
    @saipramod41 3 года назад +2

    Awesome explanation. Can you please do text justification leetcode #68 ?

    • @ritwik121
      @ritwik121 2 года назад +1

      @neetcode can we have a video on text justification ?

  • @abhaypandey2668
    @abhaypandey2668 9 месяцев назад

    I solved it a bit different way that is without this sum trick (I was not aware of actual solution) but it actually worked for all the test cases in leet code. At test case 50 it throws time limit Exceeded error but I included the same case and run it alone it worked.🤣
    class Solution:
    def maxFrequency(self, nums, k):
    length = len(nums)
    count = 1
    max_frequency = None
    nums.sort()
    if length == 1:
    return 1
    while count k:
    break
    i = i + 1
    count = similarCount + i
    return count
    I know this is not a good solution at all. But is it ok to start the preparation for the google interview? @NeetCode

  • @abhishekkumargupta3605
    @abhishekkumargupta3605 3 года назад +1

    very good explanation , it's very useful..

  • @HarshYadav-xe4ff
    @HarshYadav-xe4ff 3 года назад +1

    Very nice explanation 😀

  • @irvinge4641
    @irvinge4641 Год назад

    oh, because r goes to every element being the most frequent candidate

  • @irvinge4641
    @irvinge4641 Год назад

    when you got in google, did you ace all questions in the interview with no mistakes?

  • @ravisaharan219
    @ravisaharan219 4 месяца назад

    Great Explanation Man!!

  • @misoren9645
    @misoren9645 3 года назад

    Nice video, by the way seeing the time execution distribution, theres a peak faster than the time this solution implemented in C++ took. Is it possible that there is a faster solution?

  • @adityakrishnajaiswal8663
    @adityakrishnajaiswal8663 5 месяцев назад

    res=max (res,r-l+1); why this required?

  • @billycheung7095
    @billycheung7095 Год назад

    Amazing discovery of this sliding window condition

  • @gyandeepdigra8461
    @gyandeepdigra8461 Год назад

    for [1,1,1] k = 2 , your solution will give answer 3 , but it should be 2 . Am i wrong somewhere >?

    • @roshninagendra1264
      @roshninagendra1264 Год назад +1

      uh yeah...they're all the same number...so max freq is 3

    • @samk64
      @samk64 Год назад

      the prompt says "at most k operations", i.e. up to k operations. that means you can choose to do no operations if that gives you the max possible frequency.

  • @rohit-ld6fc
    @rohit-ld6fc 2 года назад +1

    almost impossible to come up with a solution if you have not seen this problem before!

  • @AnandKumar-kz3ls
    @AnandKumar-kz3ls 2 года назад +1

    c++ solution if anyone stuck with integer overflow runtime error in test cases class Solution {
    public:
    int maxFrequency(vector& nums, int k) {

    sort(nums.begin(),nums.end());

    int l=0;
    int r=0;
    long long curr_sum=0;
    int max_elements=-1;

    while(r

    • @krish4659
      @krish4659 6 месяцев назад

      myan thank you

  • @chaitanyakumar8683
    @chaitanyakumar8683 2 года назад

    Heyy
    Can you please tell us how to come up with these kind of formulas

  • @ameynaik1755
    @ameynaik1755 3 года назад +1

    can you please solve this problem. Thanks!
    636. Exclusive Time of Functions

  • @vignesh9678
    @vignesh9678 2 года назад

    What a logic!!! Loved it.

  • @ranjankumarsingh4601
    @ranjankumarsingh4601 Месяц назад

    Good explanation

  • @mnekx
    @mnekx 2 года назад

    Amazing man. Keep up the good work

  • @AryanChaudhary-b3k
    @AryanChaudhary-b3k 5 дней назад

    I feel dumb. I could have never come up with this solution on my own.

  • @awalkingnosebleed
    @awalkingnosebleed 3 месяца назад

    how to solve this question using hashing?

  • @hanyo3629
    @hanyo3629 Год назад +1

    Does anyone know why I'm failing the 70th test case when I'm doing this in Java?

    • @diyangli9399
      @diyangli9399 Год назад

      same here

    • @shivangb237
      @shivangb237 Год назад +2

      just convert the total to "long" instead of "int"

  • @tanknandanijagdishbhai9272
    @tanknandanijagdishbhai9272 Год назад

    nice explanation..!

  • @sarthakyadav9950
    @sarthakyadav9950 2 года назад +1

    Dude you are just awesome 🔥🔥🔥

  • @shantanukumar4081
    @shantanukumar4081 2 года назад

    Thanks 👍👍👍
    Great explanation

  • @martinlabastie.p9940
    @martinlabastie.p9940 Год назад

    7:03 example

  • @rajsuriyang3427
    @rajsuriyang3427 Год назад

    I don't know why we are multiplying with window length?
    PS: I watched this video on repeat for an hour to understand it.

    • @roshninagendra1264
      @roshninagendra1264 Год назад +1

      because that would give us the total supposing all the elements of that window are that number. this has to be equal to sum + moves. thus expand, as long as product is greater than sum.

  • @shashankshekhar8186
    @shashankshekhar8186 2 года назад

    best explanation!!

  • @_GOUTHAM
    @_GOUTHAM 2 года назад

    excellent idea man

  • @hugenerretho9151
    @hugenerretho9151 2 года назад

    if u can come up w/ this on fly, u r the god even pope cant code like this

  • @kirtimanmishra8097
    @kirtimanmishra8097 3 года назад

    awesome solution...

  • @TIENTI0000
    @TIENTI0000 3 года назад +1

    thanks

  • @thesounds1676
    @thesounds1676 День назад

    how did the people actually come up with this solution :(

  • @yassineacherkouk
    @yassineacherkouk Год назад

    I came up whit all the algorithm except the sorting part.

  • @atharvakulkarni3007
    @atharvakulkarni3007 3 года назад

    Best Explanation No cap

  • @Cpp_For_Life
    @Cpp_For_Life 7 месяцев назад

    Thanks man ❤❤❤

  • @saipraneeth2395
    @saipraneeth2395 3 месяца назад

    thanks alot man

  • @verma_jay
    @verma_jay Год назад

    Thank you

  • @PalakKalsi
    @PalakKalsi 6 месяцев назад

    Superb!

  • @syedhabeebuddin101
    @syedhabeebuddin101 2 года назад

    Thanks!

  • @MrEdgoll
    @MrEdgoll 3 года назад

    many thanks!

  • @rohansodha9555
    @rohansodha9555 3 года назад

    Thanks a lot :)

  • @mitswadas
    @mitswadas 4 месяца назад

    Just amazing

  • @jatinbhatoya8420
    @jatinbhatoya8420 3 года назад

    you are too good

  • @parthbhatia341
    @parthbhatia341 7 месяцев назад

    This is definitely not a medium

  • @vecstudio
    @vecstudio 3 года назад

    awesome

  • @pisanghangus2
    @pisanghangus2 3 года назад

    EUREKA!

  • @hetjayeshbhaipatel1075
    @hetjayeshbhaipatel1075 4 месяца назад

    wowwwwww

  • @ManavChauhan-ze2bi
    @ManavChauhan-ze2bi 5 месяцев назад

    Alright But I don't understand what its say 3 4 5 6 7 and k = 6. The above code fails on it.
    Edit: My bad I thought you could increment or decrement and for so long I've been butting my head on that, turns out the question is so much easier.

  • @pratikgehlot1973
    @pratikgehlot1973 Год назад

    ahh haa moment

  • @tusharvatsa5293
    @tusharvatsa5293 2 года назад

    Your videos are very helpful but your voice is irritating af.

    • @triscuit5103
      @triscuit5103 2 года назад +1

      wtf are you talking about? First of all, what a pointless comment, you are clearly an insecure moron, especially when it comes to social interactions. I feel sorry for you and hope you get better. Second of all, his voice is not the least bit irritating at all, I actually sometimes just listen to his videos as I find his way of talking very calming. And lastly, even if he had an irritating voice (which he certainly does not), learn to be thankful for these amazing videos which are available for all of us for free.

  • @andreytamelo1183
    @andreytamelo1183 2 года назад +1

    Thanks!