Product of Array Except Self (LeetCode 238) | Full solution with visuals | Study Algorithms

Sdílet
Vložit
  • čas přidán 23. 07. 2024
  • To see more videos like this, you can buy me a coffee: www.buymeacoffee.com/studyalg...
    A very important and an interesting problem that will assess your logical thinking skills. From an array find the product of all other elements except self. Watch this video to understand why the most obvious way to approach this problem will give you a wrong answer, and how can you come up with an efficient solution. Follow along with animations, visual aids and a dry-run of code in JAVA
    Chapters:
    00:00 - Intro
    00:50 - Problem Statement and Test cases
    03:05 - The most obvious way fails
    06:33 - Thinking out of the box
    10:55 - Dry-run of Code
    12:57 - Final Thoughts
    Actual problem on LeetCode: leetcode.com/problems/product...
    📚 Links to topics I talk about in the video:
    LeetCode Problems: • Leetcode Solutions
    Problems on Arrays: • Arrays
    What is Big O?: • Big O Notation Simplif...
    Other medium difficulty problems: • Medium Problems
    📘 A text based explanation is available at: studyalgorithms.com
    Code on Github: github.com/nikoo28/java-solut...
    Test-cases on Github: github.com/nikoo28/java-solut...
    📖 Reference Books:
    Starting Learn to Code: amzn.to/3sJm8Wl
    Favorite book to understand algorithms: amzn.to/4848xJH
    Favorite book for data structures: amzn.to/3P96YBv
    Get started for interview preparation: amzn.to/44Nn5du
    🎥 My Recording Gear:
    Recording Light: amzn.to/3PdsViT
    Microphone: amzn.to/3Exv83x
    Recording Camera: amzn.to/3PwyN8e
    Tablet to sketch and draw: amzn.to/3ZdKVy7
    Sketching Tool: amzn.to/45XJEgY
    Laptop to edit videos: amzn.to/460ofDu
    💻 Get Social 💻
    Follow on Facebook at: / studyalgos
    Follow on Twitter at: / studyalgorithms
    Follow on Tumblr at: / studyalgos
    Subscribe to RSS feeds: studyalgorithms.com/feed/
    Join fan mail: eepurl.com/g9Dadv
    #leetcode #programming #interview

Komentáře • 102

  • @Sai-fn4lq
    @Sai-fn4lq Před 10 měsíci +34

    Next level teaching sir !! You are literally a hidden gem!!

    • @nikoo28
      @nikoo28  Před 9 měsíci +1

      glad you feel that way

  • @sivaramansankar7463
    @sivaramansankar7463 Před rokem +4

    thanks for the lucid explanation , you're a hidden gem :) , you deserve way more subscribers

  • @nataliechan8535
    @nataliechan8535 Před 7 měsíci +1

    Your explanation is so clear! I like how you draw out everything to explain it! Thank you

    • @nikoo28
      @nikoo28  Před 7 měsíci

      The drawing really helps a lot 😄

  • @gameplays8457
    @gameplays8457 Před 7 dny

    Really good explanation. Clearly understood the concept. Thank you!

  • @SMK1455
    @SMK1455 Před 10 dny

    Thank you a lot for such great explanation of the problems!

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

    Excellent explanation. I am so glad that I came across your YT channel

  • @user-qn9um8ud1t
    @user-qn9um8ud1t Před 19 dny

    Thank you so much for explaining each line in a very simple manner.

  • @Aryan-oc1fq
    @Aryan-oc1fq Před 8 měsíci

    recently found your videos, and im loving the explanations. thank you !

    • @nikoo28
      @nikoo28  Před 8 měsíci +1

      hope they are of help to you

  • @thenormalpen1900
    @thenormalpen1900 Před 13 dny

    Wow, that is such a clear soln, thanks!

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

    Very nice explanation, I really search your channel for Ds-algo questions . Thanks sir for teaching free.

  • @Max-tq1ig
    @Max-tq1ig Před 10 měsíci

    Totally understood. Thanks a lot.

  • @kamehameha38
    @kamehameha38 Před 10 měsíci

    Nicely explained. Thank you very much

  • @kirthananambiar8873
    @kirthananambiar8873 Před rokem

    Thank you so much sir.
    Explained very well.

  • @abhishekkeshri3974
    @abhishekkeshri3974 Před rokem +2

    like always your explanation and video quality is awesome. i will try to share your videos as much as possible .

  • @kenilkanani16
    @kenilkanani16 Před dnem

    Awesome explanation 🎉

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

    THANK YOU , I TRIED VERY HARD BUT COULD NOT SOLVED. YOU CLEARED IT IN A MIN .❤❤❤❤❤❤

  • @LongNguyen-pe5uo
    @LongNguyen-pe5uo Před rokem +1

    Good video, very easy to understand.

  • @anishasaini380
    @anishasaini380 Před 5 měsíci

    Sir Best Explanation!!

  • @ass2412
    @ass2412 Před 11 měsíci +12

    I was stuck in neetcode and i thought it would be impossible. After seeing your video, i understood clearly

  • @user-rg1dr1ou6f
    @user-rg1dr1ou6f Před 7 měsíci

    Fall in love with your explanation ❤❤❤❤❤❤❤❤

  • @Piyush-me9nu
    @Piyush-me9nu Před 7 měsíci

    Amazing explanation!

  • @Infinitycoder01
    @Infinitycoder01 Před rokem

    I like your way of explaining the problem , with this i learnt to solve problems and as well as the way of explaining the code to others.
    It helped me a lot in my interview.Thank you so much.

    • @nikoo28
      @nikoo28  Před rokem

      I try to approach the problem in a way as you would do in an interview. Glad it helps :)

  • @sianwa11
    @sianwa11 Před 8 měsíci +2

    Recently found your channel, whenever I don't understand neetcode solutions I come here. Thank you sir!

    • @nikoo28
      @nikoo28  Před 8 měsíci +2

      @neetcode is also an amazing channel :)

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

      Same!

  • @c4rtel
    @c4rtel Před rokem +1

    Very nice explanation.

  • @vivekjaiswal4391
    @vivekjaiswal4391 Před rokem +1

    Great teacher 👏

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

    Amazing Explaination

  • @abhigoku2022
    @abhigoku2022 Před 5 měsíci +2

    Hi Sir,
    Eveytime I am searching for a leeetcode problem, I add your name in the suffix hoping you have done a video on it. I have understood each and every video that I have watched. Please do solve all the problems, that will be very helpful for people like me.

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

    Man you are god 😭🙏 your explanation is outstanding 👏 you earned a subscriber today ❤️.

  • @papayaw2920
    @papayaw2920 Před 10 měsíci

    Keep going Nikhil, I was stuck and I was about to give up too. I feel taught today

    • @nikoo28
      @nikoo28  Před 9 měsíci

      glad that was helpful

  • @ashishgoyal6256
    @ashishgoyal6256 Před rokem +4

    Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)

  • @infinite639
    @infinite639 Před rokem

    Thanks bhai
    leetcode ke videos banate raho mere liye or sabke liye
    Love you bro

  • @divyasingh6757
    @divyasingh6757 Před rokem +6

    Here our space complexity can be reduced to O(1)..overall nice explanation

  • @AravindKumar-lj7kx
    @AravindKumar-lj7kx Před rokem

    Thanks a lot....you are great....

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

    I usually don't comment but this kind of video I see my hands automatically goes in comment section for comment.
    Thanks Nikhil you even demystified how dividing will give results, most of people don't know how dividing is giving the answer and thanks for explain postfix and prefix in detail.

  • @yxs7
    @yxs7 Před 10 měsíci +1

    u are the best! thx! ❤👏✨

    • @nikoo28
      @nikoo28  Před 10 měsíci

      you are the best

  • @zahrabt6705
    @zahrabt6705 Před 10 měsíci +1

    you explained it very well. thanks

  • @MdArif-pc9bz
    @MdArif-pc9bz Před měsícem

    Thank you

  • @infinite639
    @infinite639 Před rokem +2

    i have shared your tutorials to my friends

    • @nikoo28
      @nikoo28  Před rokem +1

      Thank you so so much 😄

  • @rishabhsaini7836
    @rishabhsaini7836 Před rokem +1

    Nicest explanation ❤❤

  • @nenuanenenuane6645
    @nenuanenenuane6645 Před rokem

    Thank you bro❤❤

  • @TalhaTabrez7
    @TalhaTabrez7 Před 6 měsíci +1

    thank you

  • @user-ph5ek8tg5l
    @user-ph5ek8tg5l Před měsícem

    Leetcode has mentioned to try O(1) space solution. You should add one more part in the video for such optimizations.

  • @bun_bun17
    @bun_bun17 Před rokem

    you are great :)

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

    amazinggggggg

  • @mikedelta658
    @mikedelta658 Před 6 měsíci

    Excellent explanation.

    • @nikoo28
      @nikoo28  Před 6 měsíci

      Glad you liked it

  • @benmyths
    @benmyths Před dnem

    thanks

  • @subee128
    @subee128 Před 6 měsíci +1

    Thanks

  • @SingwithSuhas
    @SingwithSuhas Před 7 měsíci +1

    superb

  • @ankit_yr_senpai
    @ankit_yr_senpai Před měsícem

    great

  • @vlogsaryan2540
    @vlogsaryan2540 Před rokem

    Bhaiya why would you used num[i-1] and [n+1] in both the left and right Loop pls explain

    • @nikoo28
      @nikoo28  Před rokem

      please try to look at the explanation of the left and right array once again, we have to skip those elements. if you are still confused..let me know

  • @jagdishbehera5010
    @jagdishbehera5010 Před rokem +1

    The way you teach it feels like there is nothing in DSA

    • @nikoo28
      @nikoo28  Před rokem

      Thanks for the appreciation…I really try to simplify things as much as possible.

  • @jayeshjain4540
    @jayeshjain4540 Před 5 měsíci

    Sir the question also says You must write an algorithm that runs in O(n) time and without using the division operation.

    • @nikoo28
      @nikoo28  Před 5 měsíci

      I don't use the division operator.

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

    Thank you for the video. But somehow I don't know how it's possible to find the solution without knowing this trick (prefix, suffix). What am I missing in my reasoning?

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

      This is a kind pf problem which comes with practice. The idea is that once you solve a problem like this, it will open your mind and you will try to apply the same pattern to future problems.

  • @sainathkadam2213
    @sainathkadam2213 Před rokem

    You r osm 🔥

    • @nikoo28
      @nikoo28  Před rokem

      Thank you so much 😀

  • @truecoding8659
    @truecoding8659 Před rokem +2

    Here is my solution in python, i used to for loop and it givs the same answer.
    arr=[2,1,3,4]
    arr1=[]
    r=1
    for i in range(len(arr)):
    pro=arr[i]
    for j in arr:
    if j is not pro:
    r=r*j
    arr1.append(r)
    r=1
    print(arr1)

    • @nikoo28
      @nikoo28  Před rokem +2

      but the time complexity of your solution is O(n^2)...because of the nested loops. You can try to improve that.

    • @avanishraj386
      @avanishraj386 Před rokem

      @@nikoo28 this will fail when arr = [0,0]

    • @nikoo28
      @nikoo28  Před rokem

      @@avanishraj386 did you try the code given on github? It will work with your sample test case. What error are you getting?

    • @avanishraj386
      @avanishraj386 Před rokem +1

      @@nikoo28 I am not talking about your code, I have replied the above comment of "True Coding".

  • @siddharthmehta4223
    @siddharthmehta4223 Před rokem

    it gives the following error for the array you created to store right side value.
    error: cannot find symbol [in __Driver__.java]
    int[] ret = new Solution().productExceptSelf(param_1);
    ^
    symbol: class Solution
    location: class __DriverSolution__

    • @nikoo28
      @nikoo28  Před rokem

      Check the github link in the description below, for a working code :)

  • @thakurabhishtpratapsingh1686
    @thakurabhishtpratapsingh1686 Před 3 měsíci +1

    i was getting time limit exceeded for one of the test cases.

    • @nikoo28
      @nikoo28  Před 3 měsíci +1

      Check out the code given in video description

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

    Sir i didn't understand the approach that you have explained about 2^32 and 10^12>2^32

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

      What part are you getting confused with?

  • @58harshverma57
    @58harshverma57 Před rokem

    brackets are not allowed here; to declare an array, place the brackets after the name
    int[] left = new int[nums.size()];
    ~~ ^
    []
    this error is coming

    • @nikoo28
      @nikoo28  Před rokem +1

      Please recheck your code. The declaration is correct. Also check my complete code in the github link available in video description.

    • @58harshverma57
      @58harshverma57 Před rokem

      @@nikoo28 yes sir I have corrected it ..I haven't made left and right as vectors! Thanks for the solution ! 😄

  • @Dineshkumar_dk
    @Dineshkumar_dk Před 9 měsíci +1

    but we have to solve this with O(1) space

    • @nikoo28
      @nikoo28  Před 9 měsíci +2

      let me come back to you.

  • @prakhargarg4166
    @prakhargarg4166 Před 6 měsíci

    Question says no extra space, then why left and right arrays

    • @nikoo28
      @nikoo28  Před 6 měsíci +1

      That part got added to the question recently. It wasn't there when I created the video. Will post an update soon on it.

  • @user-om9lc1qt9t
    @user-om9lc1qt9t Před 10 měsíci

    class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
    # Check if the input list is empty
    if not nums:
    return []

    length_of_nums = len(nums)
    # Initialize the result list with 1s
    result = [1] * length_of_nums
    product = 1
    # Calculate the product of all elements to the left of each element
    for index in range(length_of_nums):
    result[index] = product # Store the product of elements to the left
    product *= nums[index] # Update the product for the next element

    product = 1
    # Calculate the product of all elements to the right of each element
    for index in range(length_of_nums - 1, -1, -1):
    result[index] *= product # Multiply by the product of elements to the right
    product *= nums[index] # Update the product for the next element
    return result

  • @user-kd5gp4ds4p
    @user-kd5gp4ds4p Před 10 měsíci

    i think this is good approach then your code please review it
    solving in O(n) time and o(1) space complexity
    class Solution {
    public:
    vector productExceptSelf(vector& nums) {
    int zero = 0;
    int tmul = 1;
    for(auto num : nums){
    if(num)
    tmul *= num;
    else{
    if(zero){
    tmul = 0;
    break;
    }
    zero++;
    }
    }
    for(auto &num : nums){
    if(num)
    num = zero>0 ? 0 : tmul/num;
    else num = tmul;
    }
    return nums;
    }
    };

  • @danishmehmood6110
    @danishmehmood6110 Před 10 dny

    bro this problem has a better and more simple solution
    step 1 - just calculate the product of the whole array in this example the answer would be 1*2*3*4=24
    step 2 - in the second step to calculate result [ i ] just divide the calculated result by nums [ i ] e.g to calculate result [ 0 ] = 24/1 =24
    result [ 1 ] =24/2 =12 and so on

    • @nikoo28
      @nikoo28  Před 9 dny

      does this method get accepted? I believe you will hit limits when trying to multiply all the numbers.

  • @ahamedsha9688
    @ahamedsha9688 Před 7 měsíci +1

    I am dumb