L11. Subarray with k different integers | 2 Pointers and Sliding Window Playlist

Поділитися
Вставка
  • Опубліковано 10 лют 2025

КОМЕНТАРІ • 110

  • @takeUforward
    @takeUforward  10 місяців тому +198

    There is a slight mistake in the code. Please find the fix below
    while (mpp.size() > k) {
    mpp[nums[l]]--;
    if (mpp[nums[l]] == 0)
    mpp.erase(nums[l]);
    l++;
    }
    The while condition and the value of L

    • @ManishKumar-dk8hl
      @ManishKumar-dk8hl 10 місяців тому +1

      👍

    • @rainyvideo6936
      @rainyvideo6936 5 місяців тому

    • @karthik-varma-1579
      @karthik-varma-1579 4 місяці тому +1

      Java Code
      class Solution {
      public int subarraysWithKDistinct(int[] nums, int k) {
      return subArraysLessThanEqualToK(nums,k)-subArraysLessThanEqualToK(nums,k-1);
      }
      public int subArraysLessThanEqualToK(int[] nums,int k){
      int l=0,r=0,count=0;
      HashMap hm = new HashMap();
      while(r k){
      int rm = nums[l];
      hm.put(rm,hm.get(rm)-1);
      if(hm.get(rm) == 0){
      hm.remove(rm);
      }
      l++;
      }
      count += (r-l);
      r++;
      }
      return count;
      }
      }

    • @pranjuljaiswal1974
      @pranjuljaiswal1974 3 місяці тому

      its working fine
      int n=arr.length,l=0,r=0,count=0;
      HashMap map = new HashMap();
      while(r k){
      map.put(arr[l],map.getOrDefault(arr[l],0)-1);
      if(map.get(arr[l]) == 0)
      map.remove(arr[l]);
      l++;
      }
      count+=(r-l+1);
      r++;
      }
      return count;

    • @harshkumar-r1m
      @harshkumar-r1m 2 місяці тому

      ✌✌✌✌

  • @rohitn8883
    @rohitn8883 10 місяців тому +137

    Hey Striver,
    I think there are two corrections needed to be done
    the while condition should be while (mp.size() > k)
    and instead of l-1, it should be incremented to l+1

  • @yogeshinba6809
    @yogeshinba6809 10 місяців тому +54

    Solved this on my own using learnings from previous lectures, thanks striver :)

  • @anubhavpal1071
    @anubhavpal1071 4 місяці тому +6

    Bro u r goated, I was able to solve the problem without looking at the solution thanks to you covering all patterns in the previous problems. Your last few vids helped me in understanding pattern 2 and 3 perfectly.

  • @AdityaSingh-uy8ms
    @AdityaSingh-uy8ms 10 місяців тому

    The explanation of the problem and its solutions from basic to optimized solutions... everything is crystal clear ... truely helpful ... thanks

  • @trailblazer555
    @trailblazer555 10 місяців тому +17

    Today's Leetcode Problem of the Day!!!

  • @AkshitChaudhary-vx8iw
    @AkshitChaudhary-vx8iw 2 місяці тому

    thanks Striver..Only because of you i can solve subarray related problems during my college contest.. thank you so much

  • @RoshanPathak-i4l
    @RoshanPathak-i4l 6 місяців тому +1

    Hi Striver, I think few corrections required, but I think you have already addressed it, adding in the java reference code, but bro you are awesome.
    class Solution {
    public int subarraysWithKDistinct(int[] nums, int k) {
    return countSubArraysWithGoal(nums, k) - countSubArraysWithGoal(nums, k-1);
    }
    private int countSubArraysWithGoal(int[] nums, int goal){
    if(goal

  • @data-fi4hl
    @data-fi4hl 6 місяців тому +2

    did this question on my own by learning from previous lecture!! thanks striver bhaiya

  • @AdityaMaurya-dw3od
    @AdityaMaurya-dw3od 6 місяців тому

    Did this question on my own! Feeling so good. The previous lectures helped me

  • @soumyajit_0
    @soumyajit_0 10 місяців тому +19

    3 Corrections.
    1) The inner while condition should be while(mp.size>k)
    2) The l=l-1 should be l=l+1 in the inner loop.

  • @MuhammadAzeem-bd7xf
    @MuhammadAzeem-bd7xf Місяць тому

    Solved it completely by myself Thanks Striver

  • @stith_pragya
    @stith_pragya 8 місяців тому +1

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

  • @stith_pragya
    @stith_pragya 8 місяців тому +1

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

  • @HimanshuYadav-fg8sm
    @HimanshuYadav-fg8sm 10 місяців тому +10

    Sir There are 2 mistakes thre should be if(map.size()>k)
    and l++ in the place of l=l-1.

  • @jaiswalvarrnit
    @jaiswalvarrnit 10 місяців тому +10

    Bro can predict future. Daily problem solvers can relate.

    • @kenil98
      @kenil98 10 місяців тому

    • @taqimustafa7665
      @taqimustafa7665 10 місяців тому

      hahaha yes.i had seen the videoes before this and thought i watch the playlist from this video today,saw daily question,was easy to solve from the previous videoes knowledge and now when i open this playlist again,i see this video hahah

  • @hareshnayak7302
    @hareshnayak7302 9 місяців тому

    Undeerstood,Thanks Striver for this amazing video.

  • @devanshsingh2
    @devanshsingh2 7 місяців тому

    Solved on my own thanks to you!

  • @AbhishekKumar-vu3cp
    @AbhishekKumar-vu3cp 3 місяці тому

    i solved this on my own Thanks Striver

  • @abhisheksinghdangi5027
    @abhisheksinghdangi5027 10 місяців тому +9

    Todays lc potd

  • @Cool96267
    @Cool96267 8 місяців тому

    Thankyou so much Striver for all you efforts throughout in delivering us so much valuable content. Any student / working professional can now be able to transition their career without paying money for courses.
    Would also like your insights on the point :
    While preparing for interviews most of the aspirants are going through the videos solely and solving the question after completely watching the video. And also are feeling lazy trying to solve the question on our own. What is the best way to complete any topic without being lazy and how should an aspirant approach any topic/playlist?

  • @knowthrvdo
    @knowthrvdo 7 місяців тому

    00:04 Count the number of subarrays with exactly K different integers.
    02:26 Use two pointers and a sliding window to find subarrays with k different integers
    04:52 Algorithm for counting total number of subarrays with k different integers
    07:12 Using count and frequency to determine valid windows
    09:43 Using sliding window to find subarrays with k different integers.
    12:16 Creating valid subarrays using 2 Pointers and Sliding Window approach
    14:37 Using sliding window to find subarrays with k different integers
    17:03 Using the sliding window technique to solve for subarrays with k different integers.
    19:17 Discussion on time and space complexity with the use of map data structure.
    Crafted by Merlin AI.

  • @Krishna-ti8ys
    @Krishna-ti8ys 10 місяців тому

    Thank you so much bhaiya. I learned a lot from you. Please make a playlist on greedy as well if possible.

  • @torishi82
    @torishi82 8 місяців тому

    Understood. Completed full playlist.

  • @ashishsinghNITR
    @ashishsinghNITR 10 місяців тому

    Hii striver, you are wonderful
    for helping millions of peoples with your knowledge. ❤❤

  • @rushidesai2836
    @rushidesai2836 5 місяців тому

    This is a gold question

  • @VarunPattikonda
    @VarunPattikonda 3 місяці тому

    Point to remember: when you are not sure which pointer to move,then try to find different approach like striver used in previous 3 videos

  • @shreyxnsh.14
    @shreyxnsh.14 3 місяці тому

    super easy if you have watched the previous videos:
    class Solution {
    public:
    int subarraysWithKDistinct(vector& nums, int k) {
    //optimal: (atmost k different) - (atmost k-1 different)
    int count1 = 0, count2 = 0, l = 0, r = 0;
    unordered_map mpp;
    while(r < nums.size()){
    mpp[nums[r]]++;
    if(mpp.size() > k){
    while(mpp.size() > k){
    mpp[nums[l]]--;
    if(mpp[nums[l]]==0)
    mpp.erase(nums[l]);
    l++;
    }
    }
    if(mpp.size() k-1){
    while(mpp.size() > k-1){
    mpp[nums[l]]--;
    if(mpp[nums[l]]==0)
    mpp.erase(nums[l]);
    l++;
    }
    }
    if(mpp.size()

  • @techmatein
    @techmatein 6 місяців тому

    solved hard question on my own by applying the previous questions logic

  • @RajanKumar-vf7op
    @RajanKumar-vf7op 10 місяців тому +14

    class Solution {
    public:
    int helper(vector& nums, int k) {
    int left = 0, right = 0;
    map map;
    int cnt = 0;
    while(right < nums.size()) {
    map[nums[right]]++;
    while(map.size() > k) {
    map[nums[left]]--;
    if(map[nums[left]] == 0)
    map.erase(nums[left]);
    left++;
    }

    cnt += right - left + 1;
    right++;
    }
    return cnt;
    }

    int subarraysWithKDistinct(vector& nums, int k) {
    return helper(nums, k) - helper(nums, k - 1);
    }
    };

  • @codeman3828
    @codeman3828 9 місяців тому

    Was able to solve by myself. Thanks

  • @siddharthsharma7938
    @siddharthsharma7938 3 місяці тому

    solved it on my own!

  • @wilhelmrudolphfittig3577
    @wilhelmrudolphfittig3577 8 місяців тому +1

    understood !
    L9,L10,L11 are the same.

  • @niteshkumarjha7914
    @niteshkumarjha7914 10 місяців тому +4

    here is java solution code
    class Solution {
    public int subarraysWithKDistinct(int[] nums, int k) {
    int subK = helper(nums,k);
    int sub = helper(nums,k-1);
    return subK-sub;
    }
    private int helper(int nums[], int k){
    HashMap map = new HashMap();
    int left=0;
    int right=0;
    int count=0;
    while(rightk){
    map.put(nums[left],map.get(nums[left])-1);
    if(map.get(nums[left])==0){
    map.remove(nums[left]);
    }
    left++;
    }
    count = count+ right-left+1;
    right++;
    }
    return count;
    }
    }

    • @jitinroy2246
      @jitinroy2246 3 місяці тому

      in helper function, i think you missed the edge case when k is negative.
      if(k < 0){
      return 0;
      }

  • @vinaykumarratnala5832
    @vinaykumarratnala5832 6 місяців тому

    Solved before watching the video

  • @pawanshimpi_dev
    @pawanshimpi_dev Місяць тому

    I have a question:
    When we see that more than k elements are occurring in the subarray, then we remove it from the map
    So at max the map will always store (k+1) elements
    So the overall space complexity should be O(K)

  • @sksanoyarali1067
    @sksanoyarali1067 7 місяців тому

    class Solution {
    int subarraywithlessthankequaltok(vector& nums, int k){
    int n=nums.size();
    int l=0,r=0,cnt=0;
    map mpp;
    while(rk){
    mpp[nums[l]]--;
    if(mpp[nums[l]]==0){
    mpp.erase(nums[l]);
    }
    l++;
    }
    cnt=cnt+(r-l+1);
    r++;
    }
    return cnt;
    }
    public:
    int subarraysWithKDistinct(vector& nums, int k) {
    return subarraywithlessthankequaltok(nums,k)-subarraywithlessthankequaltok(nums,k-1);
    }
    };

  • @N1903-q9t
    @N1903-q9t 9 місяців тому

    striver can you please do problems on in how many ways an array can be splitted based on the given condition

  • @oyeshxrme
    @oyeshxrme 5 місяців тому

    thanks bhaiya

  • @117_mainakpaul2
    @117_mainakpaul2 4 місяці тому

    Can we use hashset instead of hashmap ??

  • @DeadPoolx1712
    @DeadPoolx1712 4 місяці тому

    UNDERSTOOD;

  • @SaurabhAgastya
    @SaurabhAgastya Місяць тому

    understood

  • @raushankumargupta7018
    @raushankumargupta7018 8 місяців тому

    Striver❤

  • @untitled6483
    @untitled6483 22 дні тому

    Why are we missing subarray? Whats the exact reason and which led you to

    • @untitled6483
      @untitled6483 22 дні тому

      I can observe but cannot digest mathematically why we are missing them.

  • @anantsaxena5454
    @anantsaxena5454 7 місяців тому +1

    Solved

  • @harsh2518
    @harsh2518 3 місяці тому +1

    this problem be like : Am I a joke to you 😂

  • @karthik-varma-1579
    @karthik-varma-1579 4 місяці тому

    class Solution {
    public int subarraysWithKDistinct(int[] nums, int k) {
    return subArraysLessThanEqualToK(nums,k)-subArraysLessThanEqualToK(nums,k-1);
    }
    public int subArraysLessThanEqualToK(int[] nums,int k){
    int l=0,r=0,count=0;
    HashMap hm = new HashMap();
    while(r k){
    int rm = nums[l];
    hm.put(rm,hm.get(rm)-1);
    if(hm.get(rm) == 0){
    hm.remove(rm);
    }
    l++;
    }
    count += (r-l);
    r++;
    }
    return count;
    }
    }

  • @HimanshuYadav-fg8sm
    @HimanshuYadav-fg8sm 10 місяців тому

    Same code in java
    class Solution {
    public int subarraysWithKDistinct(int[] nums, int k) {
    return fun(nums,k)-fun(nums,k-1);
    }
    int fun(int []nums,int k){
    Map frequencyMap = new HashMap();
    int left = 0, right = 0, count = 0;
    while (right < nums.length) {
    frequencyMap.put(nums[right], frequencyMap.getOrDefault(nums[right], 0) + 1);
    while (frequencyMap.size() > k) {
    frequencyMap.put(nums[left], frequencyMap.get(nums[left]) - 1);
    if (frequencyMap.get(nums[left]) == 0) {
    frequencyMap.remove(nums[left]);
    }
    left++;
    }
    count=count+(right-left+1);
    right++;
    }
    return count;
    }
    }

  • @UtkarshWasHereBeforeYou
    @UtkarshWasHereBeforeYou 3 місяці тому

    Did it myself, But I'm sure it is because i was in the flow of thinking in the sliding window approach, Wouldn't be able to do it if it was randomly thrown at me,

  • @VinayQ-
    @VinayQ- 4 місяці тому

    I think the code sippet liitle bit wrong
    while(mpp.size() > k){
    l=l+1
    }

  • @RadheShyam33455
    @RadheShyam33455 5 місяців тому

    Hey can anyone explain me why space complexity is O(n) I think it should be O(k+1) because as soon as size exceeds 2*(k+1) we are shrinking the window .Please rectify me if I am wrong 😊

  • @md.sabbirahmed4482
    @md.sabbirahmed4482 10 місяців тому

    Sir please add OPPS playlist.

  • @foziezzz1250
    @foziezzz1250 8 місяців тому +1

    How can we do this in O(N) time instead of O(2N) time ..??❓ 🤔🤔

    • @sid_ofc17
      @sid_ofc17 7 місяців тому

      with sliding window i dont think so

    • @ayushmishra6575
      @ayushmishra6575 4 місяці тому

      We can use 3 pointer approach for that

  • @shivangitiwari2485
    @shivangitiwari2485 9 місяців тому

    Understood

  • @SHIVAMOJHA21
    @SHIVAMOJHA21 3 місяці тому

    SUPERHERO

  • @ManishKumar-dk8hl
    @ManishKumar-dk8hl 10 місяців тому +2

    class Solution {
    public int help(int[] arr, int k) {
    int l = 0;
    int r = 0;
    int cnt = 0;
    HashMap mpp = new HashMap();
    while (r < arr.length) {
    mpp.put(arr[r],mpp.getOrDefault(arr[r],0)+1);
    while(mpp.size()>k){
    mpp.put(arr[l],mpp.get(arr[l])-1);
    if(mpp.get(arr[l])==0){
    mpp.remove(arr[l]);
    }
    l++;}
    cnt=cnt+r-l+1;
    r++;
    }
    return cnt;

    }
    public int subarraysWithKDistinct(int[] arr, int k) {
    return help(arr,k)-help(arr,k-1);

    }
    }

  • @tanujaSangwan
    @tanujaSangwan 5 місяців тому

    This is similar to lats 2 questions

  • @angeldeveloper
    @angeldeveloper 10 місяців тому

    🎉🎉

  • @akworld2739
    @akworld2739 9 місяців тому +1

    mujhse ek question bhi nhi ho rha sliding window ka bus brute force soch pa rha hu lag rha hai coding mere bas ki bat nhi

  • @aayushgakhar3525
    @aayushgakhar3525 6 місяців тому

    gives tle for string w exactly k diff chars

  • @leslysujith8032
    @leslysujith8032 9 місяців тому

    i im leithls aka the lethal sujith

  • @prasannavenkkatesh1192
    @prasannavenkkatesh1192 9 місяців тому +1

    Why cant we use set?

    • @CodeLaughGrow
      @CodeLaughGrow 7 місяців тому

      We need number and its freq set stores single thing not key value pairs

  • @ChillCoderForever
    @ChillCoderForever 10 місяців тому +1

    Me first 😂😂😂

  • @onetapgaming123-v2x
    @onetapgaming123-v2x 20 днів тому

    21/01/25❤

  • @imdavinder
    @imdavinder 10 місяців тому

    I have still the confusion like How (

    • @teja1184
      @teja1184 10 місяців тому

      when sliding window shrinking is happening then at that time we will use k-1 probably this case arises when there is problems ask us to count. Even in the above problem also when we took up to k then we missed few subarrays so at that time we take k-1 . so by subtracting k and (k-1) we get the exact answer

    • @diwakaranagrawal4673
      @diwakaranagrawal4673 10 місяців тому +11

      for example, k=3
      if we take (i)
      and for (ii)
      so to find for k==3, if we subtract (i) - (ii) => x=3=k
      hope this helps.

    • @imdavinder
      @imdavinder 10 місяців тому +1

      @@diwakaranagrawal4673 Thank you for the crystal clear explanation !

    • @TarunKumar-cn6in
      @TarunKumar-cn6in 6 місяців тому

      @@diwakaranagrawal4673 we can also do
      it by (

  • @THOSHI-cn6hg
    @THOSHI-cn6hg 5 місяців тому +1

    ok]

  • @smitasingh8942
    @smitasingh8942 5 місяців тому

    can someone please correct my code
    class Solution {
    public:
    int subarraysWithKDistinct(vector& nums, int k) {
    int l=0;
    int r=0;
    int cnt=0;
    map m;
    while(rk){
    m[nums[l]]--;
    if(m[nums[l]]==0)m.erase(nums[l]);
    l++;
    }
    if(m.size()==k){
    cnt=cnt+(r-l+1);
    }
    r++;
    }
    return cnt;
    }
    };

  • @dayashankarlakhotia4943
    @dayashankarlakhotia4943 10 місяців тому

    public int subarraysWithKDistinct(int[]nums,int k){
    return atMostK(nums,k)-atMostK(nums,k-1);
    }
    private int atMostK(int[]nums,int k){
    int ans=0;int[]cnt=new int[nums.length+1];
    for(int l=0,r=0;r

  • @shreshthkushwaha
    @shreshthkushwaha 10 місяців тому

    bruh

  • @pranjuljaiswal1974
    @pranjuljaiswal1974 3 місяці тому

    check this out
    int n=arr.length,l=0,r=0,count=0;
    HashMap map = new HashMap();
    while(r k){
    map.put(arr[l],map.getOrDefault(arr[l],0)-1);
    if(map.get(arr[l]) == 0)
    map.remove(arr[l]);
    l++;
    }
    count+=(r-l+1);
    r++;
    }
    return count;

  • @abhinanda7049
    @abhinanda7049 10 днів тому

    understood

  • @SitaRam-m1i
    @SitaRam-m1i 3 місяці тому

    Understood

  • @riaa55
    @riaa55 2 місяці тому +1

    Understood

  • @abhinavabhi3568
    @abhinavabhi3568 Місяць тому

    Understood