COUNT INVERSIONS in an ARRAY | Leetcode | C++ | Java | Brute-Optimal

Поділитися
Вставка
  • Опубліковано 19 вер 2024
  • Please watch the new video which covers it in more depth, and also prints it: • Count Inversions in an...
    Check our Website:
    In case you are thinking to buy courses, please check below:
    Link to get 20% additional Discount at Coding Ninjas: bit.ly/3wE5aHx
    Code "takeuforward" for 15% off at GFG: practice.geeks...
    Code "takeuforward" for 20% off on sys-design: get.interviewr...?_aff=takeuforward
    Crypto, I use the Wazirx app: wazirx.com/inv...
    Take 750 rs free Amazon Stock from me: indmoney.oneli...
    Earn 100 rs by making a Grow Account for investing: app.groww.in/v...
    Linkedin/Instagram/Telegram: linktr.ee/take...
    ---------------------------------------------------------------------------------------------------------------------------------------------------- I have decided to make a free placement series comprising of video lectures on the entire SDE sheet.. (bit.ly/takeUfo...) ..
    ✅Entire Series: • Two Sum Problem | Leet...
    ✅Use coupon-code "TAKEUFORWARD" for getting 10% for all GFG courses: practice.geeks...
    Problem Link: www.geeksforge...
    If you appreciate the channel's work, you can join the family: bit.ly/joinFamily
    Thumbnail Creator: / rikonakhuli
    Striver's Linkedin Profile: / rajarvp
    Instagram: / striver_79
    Connect with us: t.me/Competiti... (Use Link in Mobile only, if not works search "takeUforward" in telegram)..
    #dsa #leetcode #placements

КОМЕНТАРІ • 277

  • @takeUforward
    @takeUforward  4 роки тому +73

    Please watch the new video which covers it in more depth, and also prints it: ua-cam.com/video/AseUmwVNaoY/v-deo.html
    Understood or nott? am waiting in the comment section ;)
    .
    Check me out at Instagram: instagram.com/striver_79/
    .
    If you appreciate the channel's work, you can join the family: bit.ly/joinFamily

  • @muditkhanna8164
    @muditkhanna8164 Рік тому +5

    180 questions form sde sheet with striver's solution>>> 1000 self practice questions , you get to learn so many tricks and concepts with in each question. the key is to not fast forward the question. give each question its deserving time. that's all then striver's sheet is enough to you ! thank you dude!

  • @shardulkhadye5875
    @shardulkhadye5875 2 роки тому +191

    i sincerely feel that this problem should not be marked as medium level as its extremely difficult to figure out this answer in an interview if not solved previously.

    • @codding32world50
      @codding32world50 2 роки тому +15

      Yes I was stuck for whole day literally then came here😢

    • @aakashmehta9474
      @aakashmehta9474 2 роки тому +16

      Not at all possible to figure out this solution unless you are genius 😃

    • @ritikashishodia675
      @ritikashishodia675 2 роки тому +10

      Maine to phele kiya tha ye to jb dubara kiya after months nahi hua.😔😔

    • @garvgoel1743
      @garvgoel1743 Рік тому +2

      @@ritikashishodia675 This is very normal 😂

    • @mdhaidarparwez968
      @mdhaidarparwez968 Рік тому +1

      For this type of problem, you should make a note and revise weekly

  • @yashisrivastava5482
    @yashisrivastava5482 4 роки тому +80

    Sir you are really a motivation , after so much of busy schedule your are still selflessly helping us in every way (hats off to you) . I wait the whole day just for your video and only after watching and learning the concept I sleep. Thank you so much sir

    • @takeUforward
      @takeUforward  4 роки тому +37

      Yashi Srivastava glat that you wait, this things keeps me motivated!!

  • @abhijitroy1958
    @abhijitroy1958 2 роки тому +105

    The alpha rule : never lose the concentration while watching striver's video . Best explanation

    • @rohitanjane1668
      @rohitanjane1668 2 роки тому +1

      Highly agree with you 👍🏻🙌🏻

    • @neerajsinghjr
      @neerajsinghjr 2 роки тому +6

      Seriously, this guy is Awesome. but its also true... you can't doze off for a single bit. If you do then rewind ...

  • @baljotsinghchoudhary7434
    @baljotsinghchoudhary7434 3 роки тому +36

    this question is very interesting one should try to solve with all approches merge sort, fenwick and trie

  • @tanayshah275
    @tanayshah275 3 роки тому +12

    Great Explanation!
    One more thing if anyone is implementing it then the invertion count will increase by mid - i + 1

    • @tarungopal3065
      @tarungopal3065 2 роки тому

      @Anand Pandey As you are calling merge() function with 'mid' as as the argument..you have to write " mid- i + 1"
      But the In video...
      He is calling as merge(left, mid+1, right)

    • @tusharvaish8096
      @tusharvaish8096 2 роки тому

      Why.? Can you explain.

    • @tusharvaish8096
      @tusharvaish8096 2 роки тому

      @Anand Pandey why we need to add 1 ? Can you explain

  • @devanshmesson2777
    @devanshmesson2777 4 роки тому +4

    You Speak So Clearly!
    Great Video Quality and Awesome Explaination!!

  • @aasthajain4210
    @aasthajain4210 4 роки тому +19

    You are so hardworking man!!
    I just look up to this✨

  • @shivalikagupta3433
    @shivalikagupta3433 2 роки тому

    Truly each and every word you speak is in align with the question's essence and explanation 1 minute apart and I need to watch the video again. Its a thorough explanation. Wonderful!!!

  • @shanayaarora198
    @shanayaarora198 3 роки тому +3

    Happy Teachers Day :)
    Thanks for such a great content.

  • @ranasauravsingh
    @ranasauravsingh 2 роки тому +1

    UNDERSTOOD... !!!
    Thanks striver for the video... :)

  • @MrJoyRana
    @MrJoyRana Рік тому

    Solution in javascript
    function merge(left, right, obj) {
    let result = [];
    let l = 0;
    let r = 0;
    while (l < left.length && r < right.length) {
    if (left[l] < right[r]) {
    result.push(left[l++]);
    } else {
    obj.count++; // this is one pair as a[i]>a[j]
    obj.count += left.slice(l + 1).length; // if left[l]>left[r], and left array is sorted in ascending order, then all elements to to the right also can be pair
    result.push(right[r++]);
    }
    }
    return [...result, ...left.slice(l), ...right.slice(r)];
    }
    function mergeSort(arr, obj) {
    const length = arr.length;
    if (length < 2) return arr;
    let midPoint = Math.floor(length / 2);
    const left = arr.slice(0, midPoint);
    const right = arr.slice(midPoint);
    return merge(mergeSort(left, obj), mergeSort(right, obj), obj);
    }
    function countInversion(arr) {
    const obj = { count: 0 };
    const mergedArr = mergeSort(arr, obj);
    return obj.count;
    }

  • @mohitsingh7793
    @mohitsingh7793 2 роки тому +1

    Merge-Sort with small modification :
    void merge(int l1, int h1, int l2, int h2, vector&nums, int &count)
    {
    int n1 = h1 - l1 + 1;
    int n2 = h2 - l2 + 1;
    vectora(n1), b(n2), c(n1 + n2);
    for (int i = 0; i < n1; i++)
    a[i] = nums[l1 + i];
    for (int i = 0; i < n2; i++)
    b[i] = nums[l2 + i];
    int i = 0, j = 0, k = 0;
    while (i < n1 and j < n2)
    {
    if (a[i] l)
    {
    int mid = l + (h - l) / 2;
    merge_sort(l, mid, nums, count);
    merge_sort(mid + 1, h, nums, count);
    merge(l, mid, mid + 1, h, nums, count);
    }
    }

  • @atmanirbharladka4467
    @atmanirbharladka4467 3 роки тому +1

    I really appreciate you explaining the prerequisite too for the question.

  • @Sahil-nm7di
    @Sahil-nm7di 4 роки тому +2

    I am already done this question but after that i am loving to see your solution video its helps us to how we should explain our solution in front of interviewer
    thanx..

  • @nayanbhuyan8156
    @nayanbhuyan8156 4 роки тому +3

    Nice explanation, I would love to see more videos on critical questions

  • @stith_pragya
    @stith_pragya 2 роки тому +1

    Thank You very much for providing this video.........👍👍👍👍👍👍

  • @SatyaMantha
    @SatyaMantha Рік тому

    Striver, i make sure i like and comment on every video that i watch. I am learning a lot from your videos.

  • @krisnerdscave394
    @krisnerdscave394 2 роки тому +1

    12:22 I guess there should by said number of elements to the right of the 'i' not 'mid' so the number of elements from left that the right element needed to jump over it. And this is what Striver said here 12:27 basically :)
    11:56 K should not be set to zero, as we won't to have indexes in temp as in original arr.
    13:01 Do we rally need that copying for anything?

    • @krisnerdscave394
      @krisnerdscave394 2 роки тому +1

      Love to discuss with myself :) but yeah we really need that copying and by saying that K should not be zero I've automatically confirmed that it's needed :)

    • @vershamishra8763
      @vershamishra8763 Рік тому

      @@krisnerdscave394 yes, Thank you for the first statement, I got confused then this helped me to clarify.

  • @vartikasinghania9723
    @vartikasinghania9723 3 роки тому +3

    amazing explanation, thank you for your efforts:)

  • @greedycat9845
    @greedycat9845 3 роки тому

    your diagram had made me reailze the core part of the solution.very nice explanatio

  • @bhaveshkumar6842
    @bhaveshkumar6842 2 роки тому +2

    Thank you so much bro!!!!!

  • @roushanraj8530
    @roushanraj8530 3 роки тому +6

    Great work bro, please never stop these explanation videos 💯💯

  • @maulikdev5040
    @maulikdev5040 2 роки тому

    Amazingly taught the concept. Thank you so much!!

  • @SurajVerma-lx6ik
    @SurajVerma-lx6ik 4 роки тому +4

    Hey striver I have one suggestion for placement series U could add 3 similar ques for practice in each vdo of placement series starting from Day -1 ...
    I am not sure i am right or wrong plzz tell striver is it correct or not bas man me kya isliye suggest kar diye .
    Plzz reply #striver 🤔

    • @jayeshgupta8618
      @jayeshgupta8618 4 роки тому +1

      Bro when you solve these questions on leetcode then leetcode suggest similar questions , just do one or two from the suggestions maybe .

    • @SurajVerma-lx6ik
      @SurajVerma-lx6ik 4 роки тому

      @@jayeshgupta8618 uske liye leetcode premium lena padega kya ????

    • @sasiraj1594
      @sasiraj1594 4 роки тому +1

      @@SurajVerma-lx6ik no

    • @SurajVerma-lx6ik
      @SurajVerma-lx6ik 4 роки тому

      @@sasiraj1594 ok

  • @xd9050
    @xd9050 Рік тому

    A small tip for those who are watching this for the first time
    -understand merge sort properly before jumping into this

  • @goodpeople7615
    @goodpeople7615 4 роки тому +15

    Awesome content shows how good preparation it needs and you nail every time .
    Happy teachers day ʕ´•ᴥ•`ʔ

  • @MallistParasite
    @MallistParasite 3 роки тому +2

    The Struggle Between Sort and Shot.Very Evident😛.
    Great Explaination.Understood.

  • @BattlefieldAWWWClips
    @BattlefieldAWWWClips 2 роки тому +2

    Hi striver meet gandhi , here again revising few tough code , i think there is a mistake wen u are doing inv_count =inv_count +(mid-1) ;
    U are telling this for right side of array but ideally we are counting from mid to left (i.e. i) . I think it is left right do correct asap plz if wrong .

  • @amrithapatil4595
    @amrithapatil4595 2 роки тому +4

    I think line number 28 should be inv_count = inv_count + mid - i+1;

    • @brahmkaransingh8804
      @brahmkaransingh8804 2 роки тому +1

      Yes that was the doubt which i was searching for in the comment section

    • @brahmkaransingh8804
      @brahmkaransingh8804 2 роки тому +1

      @Anand Pandey bro can you tell me whats wrong with the below code. Just ignore as i am not maintaining the temp array and just looking for inv_count. Thanks in advance
      Code ->
      long long merge(long long arr[], long long l, long long mid, long long r){
      long long i = l;
      long long j = mid + 1;
      long long inv_count = 0;
      while(i

    • @imtiyazuddin4827
      @imtiyazuddin4827 Рік тому

      yep, i had the same doubt

  • @AdityaKumar-rs5jn
    @AdityaKumar-rs5jn 4 роки тому +1

    Bhai bahut bdiya explain krte..
    Fully understood..

  • @atharvameher5880
    @atharvameher5880 Рік тому

    Yo
    CAME UP WITH MY OWN SOLUTION
    Checks from back of array and maintains a stack of Smaller elements, if larger count is incremented
    Its like the naive approach but optimised
    class Solution
    {
    // arr[]: Input Array
    // N : Size of the Array arr[]
    //Function to count inversions in the array.
    static long inversionCount(long arr[], long N)
    {
    long count=0;
    int flag=0;
    ArrayListal=new ArrayList();
    al.add(arr[(int)N-1]);
    for(int i=(int)N-1;i>=0;i--){
    if(arr[i]

  • @mannthakkar
    @mannthakkar 2 роки тому +1

    Very interesting question once you practice it

  • @dhanubhardwaj6935
    @dhanubhardwaj6935 3 роки тому +5

    why not inv_count=mid-i+1 bcz both i and mid are inclusive

  • @pradeepsaravanau
    @pradeepsaravanau Рік тому

    javascript solution
    function mergeSortAndCount(arr) {
    let count = 0;
    helper(arr);
    return count;
    function helper(nums) {
    if (nums.length right[rightIndex]) {
    count += left.length - leftIndex;
    rightIndex++;
    } else {
    leftIndex++;
    }
    }
    leftIndex = 0;
    rightIndex = 0;
    let sortedArray = [];
    while (leftIndex < left.length || rightIndex < right.length) {
    if (leftIndex >= left.length || left[leftIndex] > right[rightIndex]) {
    sortedArray.push(right[rightIndex]);
    rightIndex++;
    } else {
    sortedArray.push(left[leftIndex]);
    leftIndex++;
    }
    }
    return sortedArray;
    }
    }

  • @ritikdubey3338
    @ritikdubey3338 3 роки тому

    The way you teach, how can anyone one not understand 🔥🙏

  • @rudranilacharya5293
    @rudranilacharya5293 Рік тому +1

    Can we use ordered set in interviews, this ques is much easier with ordered set

  • @peter9759
    @peter9759 Рік тому

    Nice video totally understood optimal approach

  • @ankitkushwaha6269
    @ankitkushwaha6269 2 роки тому +3

    Simple code in java
    public class Solution {
    static long count = 0;
    public static long getInversions(long arr[], int n) {

    mergeSort(arr, 0, arr.length - 1);
    return count;
    }

    public static long[] mergeSort(long[] arr, int lo, int hi){
    if(lo == hi){
    long[] base = new long[1];
    base[0] = arr[lo];
    return base;
    }

    int mid = (lo + hi) / 2;

    long[] left = mergeSort(arr, lo, mid);
    long[] right = mergeSort(arr, mid + 1, hi);

    long[] merge = merge2Sort(left, right);

    return merge;
    }

    public static long[] merge2Sort(long[] left, long[] right){
    int i = 0;
    int j = 0;
    int k = 0;

    long[] merge = new long[left.length + right.length];

    while(i < left.length && j < right.length){
    if(left[i]

    • @mohitratanpal27
      @mohitratanpal27 2 роки тому

      thx bro actually i did merge sort like this,but the video showed a different method,which after 45 min of debugging I understood😅

  • @himanshusinghal5299
    @himanshusinghal5299 4 роки тому +1

    I think we can use binary search(lower_bound stl) which would take O(nlogn)

    • @takeUforward
      @takeUforward  4 роки тому +5

      No pro it will not.. you will have to use set, so after lower bound to find number of elements you need to subtract the iterator which will take n time making it total of n^2

    • @himanshusinghal5299
      @himanshusinghal5299 4 роки тому

      @@takeUforward yeah got it thanx

    • @KathanShah03
      @KathanShah03 2 роки тому

      @@takeUforward is there any other method to solve this problem using hash/set/maps?

  • @shreeramgoyal84
    @shreeramgoyal84 3 роки тому +5

    Hey Striver!
    was wondering if we could do it by Priority Queue. I mean we can but then we would need an extra storage for storing the popped values and an additional complexity to push back to pq. What do you suggest?

    • @prashantbisht2219
      @prashantbisht2219 3 роки тому

      Yeah but wouldn't it be O(n^2).For every element you traversing the entire queue in worst case.

    • @pranav288
      @pranav288 Рік тому

      @@prashantbisht2219 yup

  • @zahidcoc4646
    @zahidcoc4646 4 роки тому +1

    Following from bangladesh..😇😇

  • @souravchakraborty9777
    @souravchakraborty9777 2 роки тому +2

    Would you kindly explain the Fenwick tree method?

  • @acxd
    @acxd 4 роки тому +3

    It would have been much much clearer if you had modified the code of merge sort from gfg because using temp as parameter is confusing and the gfg article from where you have taken the code is also not easy to understand.

    • @takeUforward
      @takeUforward  4 роки тому

      I did not want to modify because a bunch kf students follow gfg 😅

  • @ManojKumar-bk1kp
    @ManojKumar-bk1kp 4 роки тому +2

    Please,
    continue with this series closely following your videos.

  • @rohitjaiswal2563
    @rohitjaiswal2563 4 роки тому +1

    You help us a lot!!!

  • @willturner3440
    @willturner3440 3 роки тому +2

    First video I used to watch at ×0.75

  • @anshumaan1024
    @anshumaan1024 Рік тому +1

    better than gfg's explaination

  • @codingaid2753
    @codingaid2753 2 роки тому

    Such a easy way of explanation
    ThanKs @ striver

  • @mohitsingh7793
    @mohitsingh7793 2 роки тому +2

    Hey Stiver,I can easily solve that question using fenwick tree data structure.But what about if maximum element in array can be upto 10^9.How to solve that using fenwick tree ? Or we can't do incase of large elements of array?

    • @mdazeen8820
      @mdazeen8820 2 роки тому

      this can be done by compressing the array because size of array is 10^5 .For example {10^8,10^9} can be compressed as {1,2}

    • @adityasai550
      @adityasai550 2 роки тому

      Bro can u tell me from where you learned Fenwick tree. There are not many good videos about Fenwick tree in UA-cam

    • @mohitsingh7793
      @mohitsingh7793 2 роки тому

      @@adityasai550 ua-cam.com/video/9uaXG62Y8Uw/v-deo.html

  • @karthikpaladugula5424
    @karthikpaladugula5424 3 роки тому

    Segmentation fault: (Help !!!)
    long long int inversionCount(long long arr[], long long N)
    {
    if(N==1)
    return 0;
    long long mid = (N-1)/2;
    long long s1=mid+1;
    long long left[s1];
    for(int i=0;i

  • @satvrii
    @satvrii Рік тому

    Kitna accha samjhaate ho 🥲🥲💋

  • @harshdasila6680
    @harshdasila6680 Рік тому +1

    GFG SOLUTION: C++
    Public:
    long long int mergeIt(long long arr[], long long temp[], long long left, long long mid, long long right)
    {
    long long inv_count=0;
    long long i=left;
    long long j =mid;
    long long k =left;
    while((i

  • @goswami46457
    @goswami46457 4 роки тому

    Great explanation sir

  • @SreyesSrinivasan
    @SreyesSrinivasan 2 роки тому

    Fabulous solution!

  • @showsshorts4696
    @showsshorts4696 2 роки тому

    class Solution{
    public:
    // arr[]: Input Array
    // N : Size of the Array arr[]
    // Function to count inversions in the array.
    long long getinversioncount(long long a[],long long start,long long end,long long mid)
    {
    long long i=0,j=0,k=start,count=0;
    long long n1=mid-start+1;
    long long n2=end-mid;

    long long L[n1], R[n2];

    for(long long z=0;z

  • @breakthecode8323
    @breakthecode8323 2 роки тому

    Thanks For Your Efforts

  • @darshantank554
    @darshantank554 2 роки тому

    What do you think about a "binary indexed tree" with O(N) ?!?!?!?!?!

  • @gouravkumarshaw5467
    @gouravkumarshaw5467 2 роки тому +1

    great explanation : D

  • @shivendrsrivastava7315
    @shivendrsrivastava7315 3 роки тому +1

    So can we say that the crux is doing inversion is basically sorting ? and merge sort is the most appropriate one

  • @rajatagrawal7016
    @rajatagrawal7016 2 роки тому

    thanks for the explanation

  • @rhythmbhatia8906
    @rhythmbhatia8906 2 роки тому

    Awesome explanation!

  • @abhishekh_p2721
    @abhishekh_p2721 Рік тому

    This is awesome ❤

  • @smartwaytolearn2425
    @smartwaytolearn2425 Рік тому +1

    why can't we solve this with gap method??? please reply.......

  • @sheikhaman6218
    @sheikhaman6218 4 роки тому +4

    Legends are watching this during online class🤣🤣 cos your way of solving a problem is so addictive

    • @takeUforward
      @takeUforward  4 роки тому +1

      Haha, what if your prof sees this comment 🤣

    • @sheikhaman6218
      @sheikhaman6218 4 роки тому

      @@takeUforward then he will reward me with great internal marks, you know what i mean🤪🤣🤣

  • @hemanthvarmas
    @hemanthvarmas 4 роки тому +2

    Great Explanation as always! Thanks anna.😅

  • @shivampokhriyal_
    @shivampokhriyal_ 3 роки тому +1

    MergeSort approach : 3:04

  • @pulkitahuja4750
    @pulkitahuja4750 3 роки тому +1

    Can you please the solution using BIT, I saw it on leetcode but I am not so familiar to using BIT except for the range sums. It would be very helpful if we could learn some applications of BIT.

    • @amitguptapc
      @amitguptapc Рік тому

      whats the name of this problem on leetcode?

  • @farazahmed7
    @farazahmed7 2 роки тому

    WAH KYA SCENE HAI!!

  • @pranjalprasad7544
    @pranjalprasad7544 3 роки тому

    Amazing explanations :)

  • @youngshahrukhkhan8179
    @youngshahrukhkhan8179 3 роки тому

    Awesome Explanation

  • @yasaswinibingimalla4602
    @yasaswinibingimalla4602 Рік тому

    Thank you sir

  • @amitsamratmaurya3170
    @amitsamratmaurya3170 3 роки тому +1

    Can you explain why you are using -> (mid-i) isnt it supposed to be (mid-i+1), but why your code works?

  • @ravishankar9247
    @ravishankar9247 2 роки тому

    Note: Please start solving this SDE sheet if and only if you have studied DSA atleast twice or else you won't be able to understand even through the video solution of the problem.

  • @yashjain1492
    @yashjain1492 3 роки тому

    Thank you very much👍

  • @hhumar987
    @hhumar987 2 роки тому

    tech dose has expained in a better way

  • @anik6110
    @anik6110 4 роки тому

    Really helpful !

  • @funenjoynilaypatel4553
    @funenjoynilaypatel4553 2 роки тому

    understood nicely 1-Aug-2022

  • @arshadmanxoori07
    @arshadmanxoori07 Рік тому

    How can i think that, it will be solve using merge sort ??

  • @code.tle_
    @code.tle_ 2 роки тому

    understood clearly..

  • @ankitdubey9310
    @ankitdubey9310 3 роки тому +2

    can we just move in the array and use stl sort to sort the right half and then compare each element to the one on the right and if its greater we are good to go,
    however after every sort i want to my array back to normal, is there a way around this?

    • @nuclearnadal69
      @nuclearnadal69 3 роки тому +3

      Bro this approach sounds more brute than the brute force itself

    • @ankitdubey9310
      @ankitdubey9310 2 роки тому

      @@nuclearnadal69 my programming 4 months back was "brutal" lol 😂😂

  • @arohibaloda3113
    @arohibaloda3113 3 роки тому +6

    His voice reminds of Pawri

    • @surajroy869
      @surajroy869 3 роки тому

      Pawri ho rhi hai bali ya kuch aur

  • @nayanbhuyan8156
    @nayanbhuyan8156 2 роки тому +1

    Your sde sheet link for this video is not working, directing the spoj

  • @ashwanisingh4931
    @ashwanisingh4931 4 роки тому

    This video is helpful ❤️

  • @yashkhatwani3198
    @yashkhatwani3198 2 роки тому

    Thank you

  • @tusharvaish8096
    @tusharvaish8096 2 роки тому

    Happy teachers day 🌹

  • @nagavedareddy5891
    @nagavedareddy5891 2 роки тому

    Brilliant !!!

  • @gurharpartapdhaliwal3087
    @gurharpartapdhaliwal3087 4 роки тому

    We can do this in 4-5 lines using PBDS bt obv. they will not allow us to use PBDS.

  • @joyalmeida6565
    @joyalmeida6565 3 роки тому +1

    why do we need temp array? I'm not getting in what way will the existing array will be modified. Please Explain

    • @yatinarora1252
      @yatinarora1252 3 роки тому

      U can watch merge sort it that u need a array so that you can basically store your elements and find comparison

  • @infinioda108
    @infinioda108 2 роки тому

    awesome man

  • @venuvenu2719
    @venuvenu2719 2 роки тому +1

    I have been thinking of an alternate easy approach.
    Let's say I sort the array in nlogn,
    then count every element inversion count using O(N) approach where we just count the number of elements on the right side of the array.
    total TC= nlogn + n = nlogn
    Wouldnt this be an easier solution?
    Please correct me if this is wrong.

    • @sak3579
      @sak3579 2 роки тому

      can't sort the array

    • @brahmkaransingh8804
      @brahmkaransingh8804 2 роки тому

      No its wrong bcoz it will count that inversions also which was not a inversion in real array . It will work if array is sorted in descending order, then only your approach will follow good. Hope you understand. If have any doubt let me know

  • @hunnysunaria2450
    @hunnysunaria2450 3 роки тому +1

    can we do this without using temp array??

    • @gautamarora6516
      @gautamarora6516 3 роки тому

      Yes, you can. Use the concept of shell sort.

  • @priyanshigupta1359
    @priyanshigupta1359 3 роки тому

    thanks bro u r best

  • @ashwinvarma9349
    @ashwinvarma9349 2 роки тому

    whats wrong in the code below?
    #include
    using namespace std;
    int merge(vector& nums, int start, int mid, int end){
    int count = 0;
    int n1 = mid - start + 1;
    int n2 = end - mid;
    vector leftArray(n1);
    vector rightArray(n2);
    for(int i = 0; i < n1; i++){
    leftArray[i] = nums[start + i];
    }
    for(int i = 0; i < n2; i++){
    rightArray[i] = nums[mid + 1 + i];
    }
    int i = 0, j = 0, k = start;
    while(i < n1 && j < n2){
    if(leftArray[i] = end) return 0;
    int count = 0;
    int mid = (start + end) / 2;
    count += mergeSort(nums, start, mid);
    count += mergeSort(nums, mid + 1, end);
    count += merge(nums, start, mid, end);
    return count;
    }
    int countInversions(vector& nums) {
    return mergeSort(nums, 0, nums.size() - 1);
    //return nums;
    }

  • @SHASHANKRUSTAGII
    @SHASHANKRUSTAGII 3 роки тому +3

    I tried to think, when i saw nlogn, heapsort, merge sort came to my mind.
    my mind tried to think, but could not develop intuition for O(nlogn) :(
    Although, brute force is easy for me, but how do i optimise?

    • @farazahmed7
      @farazahmed7 2 роки тому +1

      no one can come up with the optimal soln until and unless you have already solved it before.

    • @SHASHANKRUSTAGII
      @SHASHANKRUSTAGII 2 роки тому

      @@farazahmed7 no after 1 ye if practice now i can see why merge sort is the key to solve this problem. We can make use of merge sort in order to find the number of inversions optimally

  • @saunaknandi1814
    @saunaknandi1814 2 роки тому

    What is the thought process behind the Merge sort?

  • @bhaskargarai8371
    @bhaskargarai8371 4 роки тому

    Awesome man....

  • @adityauniyal8632
    @adityauniyal8632 Рік тому

    void merge(long long int *ans,int start,int end,long long arr[])
    {
    int mid=(start+end)/2;
    int len1=mid-start+1;
    int len2=end-mid;
    long long int first[len1];
    long long int second[len2];
    int k=start;
    for(int i=0;i

  • @infinioda108
    @infinioda108 4 роки тому +1

    Sometimes u have a fake English accent & that's funny lol...btw thanks for vid, plz show some competitive programming u used in your amazon internship sirji :)

    • @takeUforward
      @takeUforward  4 роки тому +6

      no i try to make u laugh by making it a musical tone XD so that its not serious all the time huhuhaha

    • @infinioda108
      @infinioda108 4 роки тому

      @@takeUforward Cool still bro plz tell which datastructures or algo or competitive programming strategies u used in ur Internships ... It would be cool