Minimum Increment to Make Array Unique | Sorting | Counting Sort | Leetcode 945 | codestorywithMIK

Поділитися
Вставка
  • Опубліковано 26 сер 2024
  • Whatsapp Community Link : www.whatsapp.c...
    This is the 34th Video of our Playlist "Greedy Technique : Popular Interview Problems" by codestorywithMIK
    In this video we will try to solve a good practice greedy sorting Problem : Minimum Increment to Make Array Unique | Sorting | Counting Sort | Leetcode 945 | codestorywithMIK
    We will specifically see why a normal Greedy approach will fail and why we go with the Backtracking Approach for this problem.
    I will explain the intuition so easily that you will never forget and start seeing this as cakewalk EASYYY.
    We will do live coding after explanation and see if we are able to pass all the test cases.
    Also, please note that my Github solution link below contains both C++ as well as JAVA code.
    Problem Name : Minimum Increment to Make Array Unique | Sorting | Counting Sort | Leetcode 945 | codestorywithMIK
    Company Tags : will soon update
    My solutions on Github(C++ & JAVA) : github.com/MAZ...
    Leetcode Link : leetcode.com/p...
    My DP Concepts Playlist : • Roadmap for DP | How t...
    My Graph Concepts Playlist : • Graph Concepts & Qns -...
    My Recursion Concepts Playlist : • Introduction | Recursi...
    My GitHub Repo for interview preparation : github.com/MAZ...
    Instagram : / codestorywithmik
    Facebook : / 100090524295846
    Twitter : / cswithmik
    Subscribe to my channel : / @codestorywithmik
    ╔═╦╗╔╦╗╔═╦═╦╦╦╦╗╔═╗
    ║╚╣║║║╚╣╚╣╔╣╔╣║╚╣═╣
    ╠╗║╚╝║║╠╗║╚╣║║║║║═╣
    ╚═╩══╩═╩═╩═╩╝╚╩═╩═╝
    Summary :
    Approach 1: Using Sorting
    Time Complexity: O(nlogn)
    Space Complexity: O(1)
    Steps:
    Sort the array nums.
    Initialize a variable moves to keep track of the number of increments.
    Iterate through the sorted array starting from the second element.
    For each element, if it is not greater than the previous element, increment it to make it unique and update moves with the number of increments made.
    Return the total number of moves.
    Pros:
    Simple and easy to understand.
    Efficient for small to moderately sized arrays.
    Cons:
    Requires sorting the array, which may not be optimal for very large arrays.
    Approach 2: Using Counting Sort
    Time Complexity: O(n+maxVal)
    Space Complexity: O(n+maxVal)
    Steps:
    Find the maximum value in the array to determine the size of the counting array.
    Initialize a counting array count of size n+maxVal.
    Populate the count array with the occurrences of each value in nums.
    Iterate through the count array to ensure all values are unique:
    If the count of any value is more than 1, move the excess to the next value and update moves accordingly.
    Return the total number of moves.
    ✨ Timelines✨
    00:00 - Introduction
    #coding #helpajobseeker #easyrecipes #leetcode #leetcodequestionandanswers #leetcodesolution #leetcodedailychallenge #leetcodequestions #leetcodechallenge #hindi #india #coding #helpajobseeker #easyrecipes #leetcode #leetcodequestionandanswers #leetcodesolution #leetcodedailychallenge#leetcodequestions #leetcodechallenge #hindi #india #hindiexplanation #hindiexplained #easyexplaination #interview#interviewtips #interviewpreparation #interview_ds_algo #hinglish #github #design #data #google #video #instagram #facebook #leetcode #computerscience #leetcodesolutions #leetcodequestionandanswers #code #learning #dsalgo #dsa #newyear2024

КОМЕНТАРІ • 66

  • @manibhushankumarsingh5196
    @manibhushankumarsingh5196 2 місяці тому +8

    00:01 Minimum Increment to Make Array Unique
    02:01 Use sorting to minimize increments and make array unique
    05:56 Increase minimum to make elements unique
    07:51 Using sorting to minimize duplicate elements for array uniqueness
    12:11 Explaining frequency increment and adding extra one for unique array
    14:02 Increment the array elements to make them unique
    17:54 Explaining the process of making array elements unique using counting sort method.
    19:33 Understanding the frequency and adjustments for array uniqueness
    22:47 Understanding the frequency of array elements for incrementing
    24:23 Updating array elements to make them unique.
    28:01 Optimal approach to solve Leetcode 945 using counting sort

  • @mithleshkumar-ds9ex
    @mithleshkumar-ds9ex 2 місяці тому +3

    Apke samjhane ka tarika itna acha hai ki apke aik testcase ke explain krte hi logic click ho gya.
    Bhai app coding ke GOD ho.

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

    following the channel from 5k followers, now your content have massive impact. if I can solve a problem then also still come here to learn different approaches

  • @Thriftinghai
    @Thriftinghai 2 місяці тому

    You are the GOAT of DSA explanation
    No doubt

  • @user-is6pf9gh2r
    @user-is6pf9gh2r 2 місяці тому +6

    hashmap approach was nice mik bhaiya

  • @souravjoshi2293
    @souravjoshi2293 2 місяці тому

    you are a great teacher. your calmness while teaching is worth appreciating

  • @priyanshkumar_iitd
    @priyanshkumar_iitd 2 місяці тому +4

    My initial thought process was of using Next Greater to Left & Next Greater to Right concepts, & did dry run as per below written code for the test cases, [1,2,2], [3,2,1,2,1,7] & [4,4,4,4,4]. According to the dry run, I got the correct answers, but when I run the test cases on leetcode, I get correct output for [1,2,2], but for [3,2,1,2,1,7] & [4,4,4,4,4], it shows output of 4, which is wrong. My dry run (as per the same code) yielded correct answer, but on running on platform, it fails. Can anyone help me address this issue ? The code is :
    class Solution {
    private:
    vector NGR(vector& arr, int n){
    stack st;
    vector result(n, -1);
    for (int i = n - 1; i >= 0; i--) {
    while (!st.empty() && st.top()

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

    Solved this on my own with the first approach. But the second approach was great. Thanks for that !

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

    i did it without modifying the data values
    class Solution {
    public:
    int minIncrementForUnique(vector& nums) {
    int mini = -1;
    sort(nums.begin(),nums.end());
    int n = nums.size();
    int ans = 0;
    for(int i = 0;i

  • @wearevacationuncoverers
    @wearevacationuncoverers 2 місяці тому

    hats off to your consistency

  • @knowledgeseekers303
    @knowledgeseekers303 2 місяці тому

    sir please make more videos on other topics like concepts of bit manipulation, and a video of shortest path in graphs all variation. leetcode daily are very basic nowadays.

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

    waiting for thiss videoo whole day,thankyouu!!

  • @aws_handles
    @aws_handles 2 місяці тому

    Love the way you explain

  • @EB-ot8uu
    @EB-ot8uu 2 місяці тому

    2nd wala approach mast tha. thank you.

  • @ugcwithaddi
    @ugcwithaddi 2 місяці тому

    Thanks a lot. I was able to solve using sorting. But wanted to understand counting sort approach. It was tricky but understood finally

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

    I had a doubt but while typing my doubt in the comment section, I got the answer myself😅

  • @gui-codes
    @gui-codes 2 місяці тому

    I was able to solve this on my own. Counting sort wala approach mast tha

  • @Engineeringlife651
    @Engineeringlife651 2 місяці тому

    can you bring the course on dsa the way you expalin ht cocept is amzazing i have seen your recursion,bit manupliation,binary search playlist

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

    Second approach to khud se bn gyi seekhra hu aapse

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

    #define ll long long
    class Solution{
    public:
    int minIncrementForUnique(vector& nums) {
    sort(nums.begin(), nums.end());
    const ll MAX = 1e7;
    bitset bn;
    signed int c = 0;
    for(size_t i = 0; i < nums.size(); i++){
    while(bn[nums[i]]){
    nums[i]++;
    c++;
    }
    bn.set(nums[i]);
    }
    return c;
    }
    };
    this is also woking

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

    Second approach op!

  • @Jenny-rs4ok
    @Jenny-rs4ok 2 місяці тому

    I really like your explanation. can you please share video for this problem 642. Design Search Autocomplete System

  • @rdxrdx1792
    @rdxrdx1792 2 місяці тому

    Sir plz add ipad notes also for every video. I have been taking screenshot for revision

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

    mik bhaiya you are great

  • @RishabhChatterjee-fg2gz
    @RishabhChatterjee-fg2gz 2 місяці тому +2

    Mik bhai mere dimag mein pehele aaya tha ki array ko sort karenge, Usk baad map mein frequency store Kar lenge, fir array ko traverse karunga, aur ek ek number ka frequency check Karunga, agar frequency > 1 hua, to usko ek temp mein store karke increment karunga tab tak jab tak wo element map mein present na ho, aur Jo element aayega, usko us index mein dal denge

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

    Thankyouuuuuuuuuuu!

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

    plz make more videos on dp plz

  • @pokeindia5361
    @pokeindia5361 2 місяці тому

    Bhaiya *longest valid parantheses* par video vanaiye please...

  • @sonakshibajpai6445
    @sonakshibajpai6445 2 місяці тому

    Thank you!

  • @ikrgaurav
    @ikrgaurav 2 місяці тому

    I had a doubt! Why did we prefer array over a map? if we see space complexity, both will be O(N) then why array?

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

    Very helpful

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

    Amazing!

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

    arey bhai mauj

  • @YashJain-ex2ex
    @YashJain-ex2ex 2 місяці тому

    I was able to get the 2nd solution own my own but when I coded in java, I was getting concurrentModificaiton error as while iterating the we are modifying the map so getting error, I also thought of counting sort but checking 10^5 size that is why did not try for it

  • @AnishKumar-mz7gb
    @AnishKumar-mz7gb 2 місяці тому

    sir , I encountered a similar problem in which cost was also given to increment a number and we need to make all elements unique in min cost.
    I tried this but couldn't do in less than O(n^2). can you please give any idea?

  • @aizad786iqbal
    @aizad786iqbal 2 місяці тому

    few doubts, please answer
    1. HashMap approach, i had tried doing something similar int the morning, I was facing conurruent update issue, as I was reading the current value of the map and updating element, but there is one iteraor approach for this which I will try now
    2. in the last loop, we are running the loop till < count.length , meaning it will go till the the last length, and accessing the i+1 index, there can't be any scenario where this might cause issues ?

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

    Please use white theme of leetcode, visibility of code in the black theme is less .

  • @YogeshYadav-ig5kz
    @YogeshYadav-ig5kz 2 місяці тому

    why can't we take arraylist instead of array to handle the size of counting sort array?

  • @kaushalpadaliya529
    @kaushalpadaliya529 2 місяці тому

    upload the solution of lc contest also if possible

  • @ajaydodiya6889
    @ajaydodiya6889 2 місяці тому

    in second approach can we use map?

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

    nice

  • @himangimalik7010
    @himangimalik7010 2 місяці тому

    hey, so we are initialising the size of the array based on the size of nums. but aisa ho ki agar hamara array sirf 10 places ka ho and uss mein elements hai wo 15 16 ho to uss mein hashing mein bhi problem aayegi and buffer overflwo bhi to ho sakta

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

      look carefully, we are initialising size of array as (nums.size() + maxElement)

  • @ShefaliKanojia-rq1dt
    @ShefaliKanojia-rq1dt 2 місяці тому

    instead of using vector for storing frequency , i am using unordered map, but i am getting wrong answer
    class Solution {
    public:
    int minIncrementForUnique(vector& nums) {
    unordered_map mp;
    for(auto i : nums)
    {
    mp[i]++;
    }
    int ans=0;
    for(auto &[x,y]: mp)
    {
    if(y>1)
    {
    int extra= y-1;
    mp[x]=1;
    ans+=extra;
    mp[x+1]=extra;
    }
    }
    return ans;
    }
    };

  • @cosmicthor7330
    @cosmicthor7330 2 місяці тому

    dono approach socha tha lekin first wala code kr paya second wala nhi

  • @sohiltr2310
    @sohiltr2310 2 місяці тому

    I solved it using set
    It is giving TLE😢

  • @kartikforwork
    @kartikforwork 2 місяці тому

    pls pin:
    save space in last approach to only using mxelement space-
    how?
    let say we got 3 freq at max element, the what mik is doing?
    taking 2 of 3 freq and move it to next element.
    then take 1 out of 2 freq and move it to next element.
    but isn't it like sequence 2-1 sum of first n numbers
    so we just need the extra freq at the max element and apply moves + sum_of (last_element_freq-1 to 1).
    my code- ( see last 2 lines )
    class Solution {
    public:
    int minIncrementForUnique(vector& nums) {
    sort(nums.begin(),nums.end());
    int mxelement=*max_element(nums.begin(),nums.end());
    vector freq(mxelement+1,0);
    for(int i=0;i

  • @RishabhChatterjee-fg2gz
    @RishabhChatterjee-fg2gz 2 місяці тому

    Please reply mik bhai
    I know it is very bad approach, but I want to try, I want to build logic like you, but not clicked, can you help me? How to build logic like you

    • @EB-ot8uu
      @EB-ot8uu 2 місяці тому

      practice and practice and practice

    • @RishabhChatterjee-fg2gz
      @RishabhChatterjee-fg2gz 2 місяці тому

      ​@@EB-ot8uucan you also practice the solved problems

  • @dayashankarlakhotia4943
    @dayashankarlakhotia4943 2 місяці тому

    public int minIncrementForUnique(int[]nums){
    int max=0,n=nums.length;
    for(int num:nums)
    max=Math.max(max,num);
    int[]freq=new int[max+n];
    for(int ele:nums)
    freq[ele]++;
    int ans=0;
    for(int i=0;i

  • @mayankshakya9200
    @mayankshakya9200 2 місяці тому

    Bhaiya maine ek sol kiya hai usme memoisation me prob aari hai koi help nahi karra can you help…

    • @mayankshakya9200
      @mayankshakya9200 2 місяці тому

      Leetcode 3177

    • @mayankshakya9200
      @mayankshakya9200 2 місяці тому

      class Solution {
      public:
      int dp[5010][55][5010];
      int f(int i,vector&a,int k,int lst){
      if(i==a.size())return 0;
      if(dp[i][k][lst+5]!=-1)
      return dp[i][k][lst+5];
      int ans=-1e5;
      if(lst == -1 || a[lst]== a[i]){
      ans =max(ans, 1 + f(i+1,a,k,i));
      }
      else{
      if(k){
      ans =max(ans, 1+f(i+1,a,k-1,i));
      }
      }
      ans =max(ans,f(i+1,a,k,lst));
      return dp[i][k][lst+5]=ans;
      }
      int maximumLength(vector& a, int k) {
      memset(dp,-1,sizeof dp);
      return f(0,a,k,-1);
      }
      };

  • @manasdeora4601
    @manasdeora4601 2 місяці тому

    Can somebody share the map approach code in java?
    public static int minIncrementForUnique2(int[] nums) {
    TreeMap map = new TreeMap();
    for (int i = 0; i < nums.length; i++) {
    if (map.containsKey(nums[i])) {
    map.put(nums[i], map.get(nums[i]) + 1);
    } else {
    map.put(nums[i], 1);
    }
    }
    //at this line the map is giving error as the map is dynamically increased
    for (Map.Entry entry : map.entrySet()) {
    int curr = entry.getKey();
    Integer freq = map.get(curr);
    if (freq > 1) {
    map.put(curr + 1, map.getOrDefault(curr + 1, 0) + freq - 1);
    map.put(curr, 1);
    }
    }
    return map.size();
    }

  • @reqzonegaming7157
    @reqzonegaming7157 2 місяці тому

    are you gujrati ?

    • @Krupal_siddhapura
      @Krupal_siddhapura 2 місяці тому

      muje bhi aesa hi laga ki vo sayad gujarati ho sakte he jab unhone " aaju baju " bola 😄

    • @codestorywithMIK
      @codestorywithMIK  2 місяці тому

      No I am not Gujrati. But I love the place and accent ❤️❤️❤️

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

    I solved it using vector