Count Subarrays Where Max Element Appears at Least K Times - Leetcode 2962 - Python

Sdílet
Vložit
  • čas přidán 27. 07. 2024
  • 🚀 neetcode.io/ - A better way to prepare for Coding Interviews
    🧑‍💼 LinkedIn: / navdeep-singh-3aaa14161
    🐦 Twitter: / neetcode1
    ⭐ BLIND-75 PLAYLIST: • Two Sum - Leetcode 1 -...
    Problem Link: leetcode.com/problems/count-s...
    0:00 - Read the problem
    0:15 - Drawing Explanation
    9:56 - Coding Explanation
    leetcode 2962
    #neetcode #leetcode #python

Komentáře • 71

  • @Rahul-pr1zr
    @Rahul-pr1zr Před 4 měsíci +31

    Hate the subarray problems. So hit or miss!

    • @samuraijosh1595
      @samuraijosh1595 Před 4 měsíci +2

      I dont struggle with all subarray problem. but subarray problems that involve counting/combinatorics are awful lol

    • @fireman9068
      @fireman9068 Před 3 měsíci

      @@samuraijosh1595 same lol

  • @45052so
    @45052so Před 4 měsíci +19

    I solved this problem by sliding window with another approach.
    First I count the subarray that the occurrence of the maximum is less than k, and the answer would be total number of subarray minus the result.
    The code is similar to the problem yesterday, so I personally think it is better to understand (yet in other languages you need to deal with the overflow problem).

    • @AkshatMusic-nl7mx
      @AkshatMusic-nl7mx Před 4 měsíci

      I wrote this code but still i'm getting error, please help:
      class Solution {
      public:
      long long countSubarrays(vector& nums, int k) {
      int n=nums.size();
      unordered_mapmp;
      for(int i=0;imax_freq){
      max_freq = freq;
      max_element = ele;
      }
      }
      int l=0;
      long long ans =0;
      unordered_mapmp1;
      for(int r=0;r=k){
      mp1[nums[l]]--;
      l++;
      }
      ans+=r-l+1;
      }
      long long result = (n*(n+1))/2;
      result = result-ans;
      return result;
      }
      };

    • @kgCode658
      @kgCode658 Před 4 měsíci

      same bro ..

    • @kgCode658
      @kgCode658 Před 4 měsíci

      @@AkshatMusic-nl7mx no need of map we just have to find cnt of max element

    • @kgCode658
      @kgCode658 Před 4 měsíci

      class Solution:
      def countSubarrays(self, nums: List[int], k: int) -> int:
      left,right = 0,0
      cnt = 0
      ans = 0
      maxEle = max(nums)
      while right < len(nums):
      if nums[right] == maxEle :
      cnt +=1
      while cnt >= k:
      if nums[left] == maxEle:
      cnt -= 1
      left += 1
      ans = ans + (right-left+1)
      right += 1
      n = len(nums)
      return n*(n+1)//2 - ans

    • @akhlibaratam2118
      @akhlibaratam2118 Před 4 měsíci

      I did the same but got TLE

  • @dxlaam004
    @dxlaam004 Před 4 měsíci +3

    I solved the solution without sliding window and used math :)) The Solution used one for and it beat 100 % of users.
    It was inspired by the brute force algorithm, but instead of having to use a loop to count the number of subarrays when k is satisfied, I came up with a formula to solve the problem.
    long long countSubarrays(vector& nums, int k) {
    ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    int maxValueCurrent = *max_element(nums.begin(), nums.end());
    long long count = 0;
    long long result = 0;
    vector key(nums.size() + 1, 0);
    for (int i = 0; i < nums.size(); i++)
    {
    if (nums[i] == maxValueCurrent) {
    count++;
    key[count] = i;
    }
    if (count >= k) {
    result += key[count - k + 1] + 1;
    }
    }
    return result;
    }

  • @nikhilbhutani5277
    @nikhilbhutani5277 Před 4 měsíci +1

    3 mins into the video, got the hint to think of all possible subarrays after count == k, that was it, I was able to solve it. The best part about your videos is you explain your thought process!

  • @ugola1
    @ugola1 Před 4 měsíci

    I was praying that you have a video on this and there you go! thank you.

  • @Akhillbj
    @Akhillbj Před 4 měsíci +6

    A suggestion,
    If the question specifically asks for ATLEAST, that mean K or More than K are also eligible answers, so why cant we do
    len(array) - rightPointer ! Which gives the same results

    • @plsgivemecat
      @plsgivemecat Před 4 měsíci

      definitely correct!
      this was my code:
      def countSubarrays(self, nums: List[int], k: int) -> int:
      count = 0
      mx = max(nums)
      i = j = 0
      n = len(nums)
      c_mx = 0
      while j < n:
      if nums[j] == mx:
      c_mx += 1
      while c_mx >= k:
      count += (n-j)
      if nums[i] == mx:
      c_mx -= 1
      i += 1
      j += 1
      return count

    • @cassieguo653
      @cassieguo653 Před 4 měsíci +1

      That's what I did! I think this approach is more intuitive!

    • @vijethkashyap151
      @vijethkashyap151 Před 3 měsíci

      Hey, can you please explain?
      I got the intuition for using the left pointer, but somehow can't wrap my head around this.
      How does n-j give us the count of valid subarrays?
      ex: in this array [13,2,3,3] , k = 2.
      When i=0, j=3, n=len(arr)= 5, how does doing n-j give us the count of subarrays. I am super confused!

    • @plsgivemecat
      @plsgivemecat Před 3 měsíci

      ​@@vijethkashyap151 so in the example, [1,3,2,3,3]. i = 0, j = 3. you want the amount of subarrays ending at j which are valid right? maxElement = 3. so at i=0, j =3, we know there's a valid subarray because occurrences of maxElement is = 2 >= k. now, once we've achieved a minimum threshold of atleast k = 2 occurrences of the max element, anything after that in the array will not matter and will still be a valid subarray. therefore, [1,3,2,3] is a valid subarray and so is [1,3,2,3,3]. gives a total of 2.
      (n-1) (last index) - j + 1(including the current subarray where j is pointing at) = n-j.
      in this case, thats 5-3 = 2 which is correct!
      we'll take another example if you want more clarity.
      say i extend the array as [1,3,2,3,3,1,2,3,1,2]. n = 10. k = 2. i = 0, j = 3.
      at j = 3, we've attained at least k = 2 occurrences of the maxElement = 3.
      that means anything after that, will be counted as a valid subarray.
      n-j = 10-3 = 7.
      [1,3,2,3],
      [1,3,2,3,3],
      [1,3,2,3,3,1],
      [1,3,2,3,3,1,2],
      [1,3,2,3,3,1,2,3],
      [1,3,2,3,3,1,2,3,1],
      [1,3,2,3,3,1,2,3,1,2] are all valid subarrays and as you can count, there's 7 of them!

    • @mkum2141
      @mkum2141 Před 3 měsíci

      @@plsgivemecat I got to a point that was extremely similar to your code but I wasn't able to get the count += (n-j) part (I just had += 1 which is obviously wrong).
      Can you explain why you are adding the difference between the length and your right pointer?

  • @pradyumnachakraborty3262
    @pradyumnachakraborty3262 Před 2 měsíci

    You can actually store the position of the maximum values in an array. Then, calculate the number of these subarrays between 0 to n. Now, for all other indices, if the index before it was a max, then you add prev-1 to the count, or if it was not a max, then you add prev to the count, where prev keeps a track of the number of such subarrays for the previous cases. And return the final count.

  • @jaatharsh
    @jaatharsh Před 4 měsíci

    superb explanation as always, loved it

  • @MangoTroll34
    @MangoTroll34 Před 3 měsíci

    As many people have already pointed out, the solution provided in this video (and the editorial) calculates the number of subarrays that can be made with the end of each subarray being the rightmost element in the window.
    Solving this problem by starting with brute force and then moving to sliding window might lead you to calculate the number of subarrays that can be made with the start of each subarray being the leftmost value of the window (all subarrays after k max elements are valid).
    I think the second mentioned approach is more intuitive, however, it's important to understand both approaches for other problems 😊

  • @groznee
    @groznee Před 4 měsíci

    Another approach is to find the indexes of the max value in the nums array. Then you go over each valid window using the list of indexes and choose the possible nums subarrays for that window. Took me an afternoon to do it but if you want to avoid sliding window it's worth it.

  • @DeathSugar
    @DeathSugar Před 4 měsíci +1

    it looks kinda complicated to update it by 1. if we update our right pointer and count became exactly k we can say everything to the left will be valid subarray, so total count increases by size - right, so we just add them and start increase left pointer, adding this diff until count become less then k.

  • @Versatile_Naveen
    @Versatile_Naveen Před 4 měsíci

    The way u approach to a solution is just🤯🤯

  • @shwethaks7994
    @shwethaks7994 Před 4 měsíci

    A big fan of your videos. Can you do a video for word pattern II problem. Thanks in advance.

  • @adnanmurtaza6914
    @adnanmurtaza6914 Před 4 měsíci +1

    Made the same misinterpretation as you in the beginning too lol. What would the solution be for that case and would it still be considered a medium question with that twist?

  • @furkanozbay
    @furkanozbay Před 4 měsíci +2

    I solved it with total subarray minus the subarrays that contains lower than k. But I liked your solution. It is more straightforward, especially the 2nd way, since we generally shift left pointer until the condition fails.

    • @nikhil199029
      @nikhil199029 Před 4 měsíci

      That would have been constant time soln

    • @furkanozbay
      @furkanozbay Před 4 měsíci +2

      @@nikhil199029 Still O(n)

    • @dcvc619
      @dcvc619 Před 4 měsíci

      Can I see your code please

    • @furkanozbay
      @furkanozbay Před 4 měsíci

      @@dcvc619 I tried to reply with a link of my leetcode solution but my comments are disappearing. Anyway, I am posting the code here;
      class Solution {
      public long countSubarrays(int[] nums, int k) {
      int max = 0;
      for (int num : nums) {
      max = Math.max(max, num);
      }
      int left = 0;
      int right = 0;
      long subarraysCount = 0; // this holds subarrays that contains at most k-1 max number.
      int count = 0;
      while (right < nums.length) {
      if (nums[right] == max) {
      count++;
      }
      while (count >= k) { //no need to check left

    • @furkanozbay
      @furkanozbay Před 4 měsíci

      @@dcvc619 I tried to reply you more than 3 times, but my comments are disappearing (It might be the link or the code, I don't know why) If you can write your contact address I can send a link of my leetcode solution

  • @capitaoTigelinha
    @capitaoTigelinha Před 4 měsíci +5

    Cool! Just solved it man, very nice :) same solution as you
    Please give me luck for my interviews!!

    • @NeetCodeIO
      @NeetCodeIO  Před 4 měsíci +11

      You got this king!! 🤴 (or queen 👸)

  • @DebopriyoBasu
    @DebopriyoBasu Před 4 měsíci +2

    I was solving the problem and I had searched Neetcode 2962 even before the video was published, expecting you to already have uploaded a video solution to today's problem. Good to see you're not too far from there. Amazing consistency! Thanks Neetcode!

  • @dragon_id_
    @dragon_id_ Před 4 měsíci +1

    am now at the level of identifying the sliding window but not being able to find the final result myself 😐
    thanks man

  • @markwu1765
    @markwu1765 Před 3 měsíci

    great!

  • @sabalog08
    @sabalog08 Před 3 měsíci

    Do you think you can tackle leetcode problem 2781? I feel like I have the solution right using the sliding window but it's still timing out.

  • @evanilsonp.8183
    @evanilsonp.8183 Před 4 měsíci +1

    Hi. I'm new to programming and I'd like to be a junior developer soon. I'd like to know If I will do leetcode questions in my interviews as a junior or is it for developers with more experience who wanna join FAANG.

    • @evanilsonp.8183
      @evanilsonp.8183 Před 3 měsíci

      Thanks, everyone. Thanks for answering me. I just needed a simple help and none of you guys gave me that. 👌

  • @ecchioni
    @ecchioni Před 4 měsíci +11

    Leetcode's randomizer is stuck on sliding window?

    • @ap2s2000
      @ap2s2000 Před 4 měsíci +3

      lately it's staying with a topic/theme for a week or so

    • @akshaychavan5511
      @akshaychavan5511 Před 4 měsíci

      It's not randomized!

    • @ap2s2000
      @ap2s2000 Před 4 měsíci +1

      @@akshaychavan5511 could be random within a certain topic

  • @user-vp5io1so3i
    @user-vp5io1so3i Před 4 měsíci

    Just saved me from getting stuck on this problem for 1 hr lol

  • @sudeepbattu5525
    @sudeepbattu5525 Před 4 měsíci

    Hey guys, why don't you explain the leetcode contest questions after completing the contest ?

  • @asagiai4965
    @asagiai4965 Před 4 měsíci

    I know your solution works but can't we just add another variable for the last count?
    this variable will only hold count until k
    so the final answer is count + xcount?

  • @staywithmeforever
    @staywithmeforever Před 4 měsíci

    3-0 +1 no of elements that is no of sub arrays
    every time we get an extra count we will do L-0+1 so every time L+1

  • @yang5843
    @yang5843 Před 4 měsíci +2

    I made the same mistake too

  • @rohananthwal2527
    @rohananthwal2527 Před 4 měsíci

    even though cnt is not the best variable name the solution is pretty smart

  • @staywithmeforever
    @staywithmeforever Před 4 měsíci

    if i would explain to my friend i would like this

  • @tejascj9906
    @tejascj9906 Před 4 měsíci

    You mention it's n^2 sub arrays. Isn't it the arithmetic series ? The number of sub arryas are n(n+1)/2

    • @JuanSB827
      @JuanSB827 Před 3 měsíci

      cuz he's talking in O(n) terms, he's not referring to the exact amount.

    • @tejascj9906
      @tejascj9906 Před 3 měsíci

      @@JuanSB827 The no. of subarrays is not a relative component. No of possible subarrays is a concrete number.

  • @nirjhardas446
    @nirjhardas446 Před 4 měsíci

    is this code working?

  • @pastori2672
    @pastori2672 Před 4 měsíci

    make a leetcode 100k montage

  • @satyamjha68
    @satyamjha68 Před 4 měsíci

    Solved it! 3 sliding window problems in a row!

  • @MerrowGula
    @MerrowGula Před 26 dny

    I also made that mistake

  • @Maghawry
    @Maghawry Před 4 měsíci +1

    What about this ? 12:42
    for maxCount >= k && start

  • @shashwatsingh9247
    @shashwatsingh9247 Před 4 měsíci

    Some of the subarray problems... ughhh

  • @logchamption
    @logchamption Před 4 měsíci

    Once u find max_c = k no need to check remaining because every number will form the subarray
    So the logic goes like this .......
    m = max(nums)
    l = 0
    d=defaultdict(int)
    n = len(nums)
    c = 0
    for r in range(n):
    If nums[r] == m:
    d[nums[r]] += 1
    While d[nums[r]] >= k:
    Rem = n-r
    c += rem
    If nums[l] == m:
    d[m] -= 1
    l += 1
    else:
    l+=1
    return c

  • @spsc07
    @spsc07 Před 4 měsíci

    man I waited so long for your video T_T
    Edit: please accept my connection request on LinkedIn 🙏

    • @NeetCodeIO
      @NeetCodeIO  Před 4 měsíci +6

      I have over 15000 connection requests

    • @spsc07
      @spsc07 Před 4 měsíci +1

      @@NeetCodeIO probability of my request getting accepted is x>1/15000

    • @leeroymlg4692
      @leeroymlg4692 Před 4 měsíci

      @@spsc07 it's < 1/15000
      and how would he even know what profile is yours