Apple Coding Interview Question - Product Of Array Except Self

Поделиться
HTML-код
  • Опубликовано: 2 июл 2024
  • The Best Place To Learn Anything Coding Related - bit.ly/3MFZLIZ
    Join my free exclusive community built to empower programmers! - www.skool.com/software-develo...
    Preparing For Your Coding Interviews? Use These Resources
    --------------------
    (My Course) Data Structures & Algorithms for Coding Interviews - thedailybyte.dev/courses/nick
    AlgoCademy - algocademy.com/?referral=nick...
    Daily Coding Interview Questions - bit.ly/3xw1Sqz
    10% Off Of The Best Web Hosting! - hostinger.com/nickwhite
    Follow My Twitter - / nicholaswwhite
    Follow My Instagram - / nickwwhite
    Other Social Media
    ----------------------------------------------
    Discord - / discord
    Twitch - / nickwhitettv
    TikTok - / nickwhitetiktok
    LinkedIn - / nicholas-w-white
    Show Support
    ------------------------------------------------------------------------------
    Patreon - / nick_white
    PayPal - paypal.me/nickwwhite?locale.x...
    Become A Member - / @nickwhite
    #coding #programming #softwareengineering
  • НаукаНаука

Комментарии • 297

  • @AndrewYatzkan
    @AndrewYatzkan 4 года назад +410

    Can’t divide?... a * Math.pow(b, -1); 😎

    • @prajwalchoudhary4824
      @prajwalchoudhary4824 4 года назад +24

      check mate

    • @akashg9108
      @akashg9108 4 года назад +2

      res[i] = (int)(p * Math.pow(nums[i],-1)); fails for 3 of the test cases O.o. I'm really curious about how you would solve it doing this

    • @DiasDenny
      @DiasDenny 4 года назад +3

      Just to know won't this be the same as divide ,so can we do it

    • @damankumar3277
      @damankumar3277 4 года назад +7

      That's literally dividing dude.

    • @NeverGiveUp186
      @NeverGiveUp186 4 года назад +4

      Modern problems require modern solutions 🤣🤣

  • @aryamankukal1056
    @aryamankukal1056 2 года назад +18

    I love how nick treats you like you know absolutely nothing; it helps so much; everyone else just speeds through the solution and I couldn't understand it; you're #1 for algo explanations, dude, gj

  • @yakinwissem8665
    @yakinwissem8665 4 года назад +7

    Hi, man I found your channel today and I love it so much! You are amazing man, you are helping a lot of beginners like me, thank you so much

  • @natebrunette
    @natebrunette 4 года назад +3

    The first time I did this I did it recursively. Basically pass in the current product * the current number to the recursive function. Then you can set the current answer to the current product (what was initially passed in) * whatever was returned from your recursive function. Then return the returned product * current number.

  • @patrickjoel8779
    @patrickjoel8779 4 года назад +3

    I woke up and i fell on this video .
    It's my first time seeing and interview qiestion and i
    just did the code in c it worked,but i guest there are more stronger and effective algorithms .
    Thanks for posting such question.

  • @vladonekingman4829
    @vladonekingman4829 4 года назад

    Even if you do can not use division, it can still be done in O(n) with only one for loop going from 1 to n-2, computing left array and right array at the same time. For left array, the value at i-th position is a[i-1]*left[i-1], and for right array, the value is a[i+1]*right[i+1]. But the algo is very smart. Good job and nice video

  • @hahahahhahahhaha786
    @hahahahhahahhaha786 4 года назад +63

    Dude you're so chill. Watching these simple explanations is relaxing.
    no homo.

  • @dqXIMet
    @dqXIMet 4 года назад +3

    Amazing solution! Thank you

  • @saeedbaig4249
    @saeedbaig4249 4 года назад +31

    Great vid! Another problem with the simple division solution is you gotta watch out for division by 0 error (if the input array contains 0).

    • @MohammadIshfaqueJahanRafee
      @MohammadIshfaqueJahanRafee 4 года назад +4

      The input doesn't contain anything less than 1

    • @0x656e
      @0x656e 4 года назад +12

      @@MohammadIshfaqueJahanRafee i think it was the length of array not the input of array

    • @rajamourya9473
      @rajamourya9473 4 года назад +4

      Use try n except blocks
      If it throws zero division error
      Then try to catch that error via exception block......store the result as zero

    • @allo2799
      @allo2799 3 года назад +3

      If it contained 0, easiest thing would be to write every other answer as 0 and then put the value of the product at the 0 value's index

    • @oida10000
      @oida10000 2 года назад

      You can easily come by that. In the first loop calculate the product of all non-zero numbers and set a boolean wheater or not you have seen a zero. If you run across a second zero, you can imedially return an all zero-array of the of the orginial length, otherwise replace the zero with the product and all other values with zero. Otherwise do the "division". Python Code:
      def productExceptSelf(inputArray):
      seenZero=False
      product=1
      for i in inputArray:
      if i==0:
      if seenZero: return [0]*len(inputArray)
      seenZero=True
      else:
      product*=i
      outputArray=[]
      for i in inputArray:
      if seenZero:
      outputArray.append(0 if i!=0 else product)
      else:
      outputArray.append(product//i)

  • @revraitah
    @revraitah 4 года назад +2

    Thanks man, it is really helpful!

  • @brijbhansingh6350
    @brijbhansingh6350 3 года назад +1

    thank you so much for this amazing solution

  • @vishistsd
    @vishistsd 2 года назад

    Amazing stuff mate as usual

  • @tarunj
    @tarunj 4 года назад +2

    You Really Make Good Videos! It’s Just best whenever you explain those! Thank you for these and yeah, already subscribed 😁!

  • @visiedo72
    @visiedo72 3 года назад +1

    I noticed you had the same problem open at CodeSignal. However, if you tried to solve that one, you'd have probably seen that the challenge is a bit different. They do not guarantee that the product of all numbers in the input array fits any of the integer sizes in e.g. C++. It would be interesting to see a video on that one too

  • @zerefX_
    @zerefX_ 2 года назад

    Also we can use division by subtraction method, since technically we are not allowed to use the division operator

  • @ImranHossain-by6nk
    @ImranHossain-by6nk 3 года назад

    Better explanation than Techlead
    +
    Humble and Funny and probably more talented
    ..
    This dude is the whole package

  • @naturallyweird661
    @naturallyweird661 3 года назад

    This left of it and right of it like key to solving half the array questions I have tried ... It's kind of like recursion so I like it but it always ends up taking a lot of space

  • @nikhilrana8800
    @nikhilrana8800 4 года назад

    You are doing great work bro. Keep it up!!! 😀😀

  • @qwerty83484
    @qwerty83484 2 года назад +1

    this is how I did it in matlab:
    a= [1,2,3,4];
    out=[];
    for i = 1:length(a)
    b=a;
    b(i)=[];
    multi = prod(b);
    out=[out,multi]
    end

  • @saidaouyous3485
    @saidaouyous3485 2 года назад

    Great as usual ✊

  • @ashishranjan4623
    @ashishranjan4623 4 года назад +1

    Man, I came back here after 2 months and look you are a star now ! So happy for you buddy !

  • @codeymiller5954
    @codeymiller5954 2 года назад

    A way of making it O(n) instead of O(2n) which the problem asks for is to put them into the same for loop and put them both in at the same time, however, you do have to add an if statement to check whether the item is already in the list, and if so, times it by the item already in the list, if not, just add it in. However, you do have to have to keep track of the current multiplier which means an extra two variables, but these are only ints. This is it in PHP:
    function productExceptSelf($nums){
    $length = count($nums);
    $output_arr = array();
    $left_current=1;
    $right_current = 1;
    $j=$length-2;
    $output_arr[0]=1;
    for($i=1;$i

  • @IvanRandomDude
    @IvanRandomDude 4 года назад +4

    Division is also much more expensive operation than multiplication. So even if second algorithm looks more complex (O(3n) versus O(2n)) it will be much faster since there is no excessive usage of slow / operator. Time analysis gives us time complexity in regards to n. But it doesn't tell us how much time individual operations take. Something interesting to know... And btw, I got this question for internship interview in Microsoft Development Center in my country (Serbia)

    • @bhavyajain638
      @bhavyajain638 2 года назад

      I'll code both the variants. Let's see what's faster.

    • @mohasan6713
      @mohasan6713 5 месяцев назад

      @@bhavyajain638 So??

  • @davidrain71
    @davidrain71 4 года назад +1

    @Nick White I noticed that in your previous video you initalized a hashSet and went ahead without looking at the complexity of it but I thought creating a null hash table required time O(m)

  • @eliyahutarab4862
    @eliyahutarab4862 2 года назад +1

    You can rotate the array every time abd gthan you can multiply everything that in the array to m-1 so every time you rotate it will be to the number you dont want to multiply in and than you can just to it but i dont thing its good for time complicity

  • @amitk476
    @amitk476 4 года назад +1

    Thanks for the wonderful explanation.
    you make problems look simple

  • @KaisarAnvar
    @KaisarAnvar Год назад

    You're the coolest programmer I've ever seen on youtube.

  • @GauravSingh-ku5xy
    @GauravSingh-ku5xy 2 года назад

    well explained bro

  • @chiragyadav1533
    @chiragyadav1533 4 года назад

    we can get the product of every element in the array and then loop through the array one by one and divide that product with each element and store it in a new array of the same size

  • @abrishphoenix
    @abrishphoenix 2 года назад +1

    mine solution:
    simplicity is a king :
    def solution(arr):
    out = []
    mul = 1
    for i in range(len(arr)):
    mul *= arr[i]
    for i in range(len(arr)):
    out.append(int(mul/arr[i]))
    return out
    print(solution([1,3,7,5]))
    if there is another way to get multiply of all members we can get ride off that first for loop 😊

  • @abimaelmartell
    @abimaelmartell 3 года назад +3

    Love how you explain this stuff 😅

    • @wikyprash6638
      @wikyprash6638 2 года назад

      you know, what tool he use to explain the solution?

  • @owenfer6458
    @owenfer6458 4 года назад

    hey im curious if i followed the rule , my step is to gather all number in inputarray and then remove one of the number depend on the i or how many time it loops (example if the second loop remove the number from index 1) and then multiply all the number within the array after that store it to outputrray

  • @user-ps9vn7hq1j
    @user-ps9vn7hq1j 4 года назад +13

    You can multiply in the second loop so it will be 2n

    • @nickfratto2439
      @nickfratto2439 2 года назад

      Number of operations would still be the same, still 3n. First loop: n. Second loop: 2n, so the total is still 3n :) Comes out to being a simple question of which solution is more legible or error-prone.

  • @scoperesolution2915
    @scoperesolution2915 4 года назад +2

    Yet again, thanks for this.

  • @Kokurorokuko
    @Kokurorokuko 4 года назад

    Just multiply i in a cycle unless i is equal to index of the numbee on output

  • @pulgupta
    @pulgupta 4 года назад

    Nice solution

  • @sumeetbansal3552
    @sumeetbansal3552 4 года назад

    Its just like the question of calculating area Between two towers.

  • @Sunil_1200
    @Sunil_1200 4 года назад

    Thank you for ur videos. It helps us alot. Much appreciated!!

  • @prateek4524
    @prateek4524 3 года назад

    nice explanation 🔥

  • @maythecodesbewithyou29
    @maythecodesbewithyou29 4 года назад

    great explanation

  • @yogeshgupta6094
    @yogeshgupta6094 2 года назад +1

    For i in range(n):
    For j in range(n):
    If i=!J:
    s=s*arr[i]
    m.append(s)
    print(m)

  • @gammastrain5289
    @gammastrain5289 3 года назад

    To avoid division maybe we could use logarithmic approach

  • @sualehalam4259
    @sualehalam4259 4 года назад

    Using the first approach If we cannot divide then we can instead of dividing by 2 we can multiply by 1/2 so generalizing it instead of dividing by n we will multiply by 1/n just a trick to get around this problem using the first approach.

  • @selfquerynil7532
    @selfquerynil7532 4 года назад +3

    for x in array: array[x]=1, multiply, output[x]=result

    • @sabe607
      @sabe607 2 года назад

      That’s quadratic time

  • @androidking8158
    @androidking8158 2 года назад

    Initially, 😁 ,
    I came up with this just after looking at the thumbnail (before watching) :
    def pro(l):
    p=1
    for x in l:
    p*=x
    for i in range(len(l)):
    k=l[i]
    l[i]=p//k
    return l

    l=[1,2,3,4]
    print(pro(l))

  • @sannge6471
    @sannge6471 3 года назад +4

    Can we also use recursion to the left, and right, then multiply them after ? Divide and conquer?

    • @james.lambert
      @james.lambert 2 года назад

      That was my first solution before watching his solution but I think it is O(n*log(n))

  • @frankribery3362
    @frankribery3362 4 года назад +3

    Yo Nick I just wanted to say something really surprising ...
    You're awesome bud

  • @lb9970
    @lb9970 2 года назад

    Im an electrical engineer. I can code but Im not familiar with any of the computer science jargon you used. I solved it with a nested for loop. What is time complexity and space complexity?

  • @omkumar0900
    @omkumar0900 2 года назад

    I was asked this exact question in a recent interview by Goldmann Sachs. First I used division, then the interviewer asked to do it without division. I followed up with precalculating suffix products and calculating prefix products on the go.

  • @laxmanjeergal3827
    @laxmanjeergal3827 3 года назад

    good logic !! 🤓

  • @shailendratripathi3944
    @shailendratripathi3944 3 года назад

    That chrome tab, "make bottom taskbar disappear" 😂😂

  • @muddycalendar3292
    @muddycalendar3292 2 года назад

    I assume you wouldn’t be allowed to multiply by i^-1 each time right?

  • @GG-hk5iz
    @GG-hk5iz 4 года назад

    Only video where I understood the solution/technique

  • @chandrashekard.7543
    @chandrashekard.7543 4 года назад +7

    I don’t think you need the 3rd loop. You could do the output array calculation in the 2nd loop after getting the right_products.

    • @MegaPremios
      @MegaPremios 2 года назад

      It's same time and space complexity

    • @bhavyajain638
      @bhavyajain638 2 года назад

      @@MegaPremios how is it same time complexity? Just Going through the loop, doing nothing will take some time. Won't it?
      I'm a beginner.

    • @MegaPremios
      @MegaPremios 2 года назад +1

      @@bhavyajain638 You either do 2 operations N times, or you do 1 operation 2*N times. If you are looking at lines of code execution, it's the same

    • @bhavyajain638
      @bhavyajain638 2 года назад

      @@MegaPremios yes I get it. Thanks

  • @mdouet
    @mdouet 3 года назад +2

    Having not seen the solution in the video yet, my brute force approach would be to have two loops, the first loop goes through each element in the input array to keep track of the element we are skipping in the calculation. The next loop simply goes through the array again, this time we skip the element pointed to in the first loop, and simply get the product of every other element in the array, storing the result in a new array (we keep track of our location in this new array using the outer loop).
    I believe this is O(N^2) complexity, so not sure if it would be an acceptable solution in an interview however, but this would be where I would start with this problem:
    public static int[] productExcludingSelf(int[] input) {
    int[] products = new int[input.length];
    for(int i=0; i

    • @nayanyadav6919
      @nayanyadav6919 2 года назад

      Hey man! I also tried doing it this way but the output is way too different than what I expected it to be. I'm kind of new to programming so I didn't really go into complexity for this question and following the boilerplate code mentioned in the question. Can you pls tell me where I'm going wrong? Would be a great help. Here's my logic.
      public static void prod(int[] arr)
      {
      for(int i=0; i

    • @harshavardan9054
      @harshavardan9054 2 года назад

      @@nayanyadav6919 hi man do not use this approach as you get it wrong when the particular element is repeated in the array. I will paste my sol in the below you can check it out you can do it by taking to loops and inputting the number of the second loop where both the loops run from 0 to the len(array)-1 and you can create two lists one outside the two loops and one inside the 1st loop and you will check that if the number in the 1st loop != number In the second loop in this way you can eliminate the element repetition and you will append
      it with the 2nd list which is present inside and then at last you can append the second loop with the first loop in this way you can append only those numbers which are not same as the 1st loop number and at the end you can create another loop where it is in the form of a list inside the list and you can multiply the numbers in the end.
      The solution in python:-
      a=[2,2,3,4]
      r=[]
      for j in range(len(a)):
      s=[]
      for m in range(len(a)):
      if j==m:
      s=s
      else:
      s+=[m]
      r+=[s]
      for ch in r:
      s=1
      for m in ch:
      s*=a[m]
      print(s)

  • @thattoofunny
    @thattoofunny 4 года назад +8

    When it comes to job interview coding questions what are they mainly looking for? It is mostly or heavily Algorithms and understand how they perform???

    • @XxM1G3xX
      @XxM1G3xX 4 года назад +7

      I have read a lot about this, so tldr; you are expected to 'get the job done' but talking your way trough is very important, since they can't tell what you are thinking; so you've got to talk! You have to try make it more like a friendly technical-conversation, rater than technical question and answer test :)

  • @yashrastogi3726
    @yashrastogi3726 4 года назад +6

    At first I thought why u make video on such a simple question but at the end I realise why u did

  • @nutsirimaunjit7427
    @nutsirimaunjit7427 2 года назад

    we can divide so we get to 2n (1. loop to multiple all elements to get product of all, 2. loop again to take elements and divide product)
    but without division and with this solution it's 3n (left product , right product , result)
    but why tho ... without division

  • @z08840
    @z08840 3 года назад +1

    ...or use logarithm property: a/b = pow(x, logx(a) - logx(b)), where x is any base... and pay attention to zeros and signs :)

    • @freeshavaacadooo1095
      @freeshavaacadooo1095 2 года назад

      It would be computationally expensive compared to just looping 3 times. Imagine how that operation scales for an array of length 1000 or something.

    • @z08840
      @z08840 2 года назад

      @@freeshavaacadooo1095 1000? you've gotta be kidding me :D besides multiplication anyway will suffer for any large numbers due to overflow - from this point you'll find yourself solving quite another puzzle than pesky logarithm expensiveness :)

  • @xlr8tanmay
    @xlr8tanmay 4 года назад

    Can you please upload a video for a matrix travel in Python?

  • @shivampurbia6169
    @shivampurbia6169 4 года назад

    How about Divide and conquer like merge sort ?

  • @welltypedwitch
    @welltypedwitch 4 года назад

    To anyone who still says something like 'languages are all the same except different syntax' , this is litterally a one-liner in haskell (this legitimately took me 2 mins)
    pes l = (product . (`delete`l)) l
    Or in a less point-free style:
    pes l = map (\x -> product (delete x l)) l

  • @aceaem08
    @aceaem08 2 года назад

    Nice... Great video

  • @zombiekiller7101
    @zombiekiller7101 2 года назад

    Index = int(input ("which Index you want?"))
    C = 1
    for I , j in enumerate(nums):
    If I != index:
    c*= j
    Print(c)

  • @lifeofhiren
    @lifeofhiren 2 года назад

    I got a idea as take initial array contain 1s as same size of input and then multiple all items of output array expect the one for we are calculating

  • @shahvezali1
    @shahvezali1 4 года назад

    Thanks a lot Bro 👍
    Logics do not click on mind what to do.
    I am learning java by myself.
    Even I do not able to understand the problem like code chef questions.

    • @harsimransidhu3961
      @harsimransidhu3961 4 года назад

      Me too and on which platform u r learning

    • @shahvezali1
      @shahvezali1 4 года назад

      @@harsimransidhu3961 First I studied from the Oracle book the complete reference upto inheritance. After that topic I am not getting from the book.
      Then I studied on particular topics from random youtube search.
      But problem is that I am not able solve the problems. Still struggling.

  • @ghcrocket
    @ghcrocket 4 года назад

    Master of codings :D

  • @patrickjoel8779
    @patrickjoel8779 4 года назад +1

    I used 2 for loops

  • @SurfsUpSeth
    @SurfsUpSeth 4 года назад

    Would we not want to use the length call and instead check to see if the end of the array was nil and do all of that if this was in C since it’s O(n). I mean it would increase runtime by only alittle, it would still be O(n) lol.

  • @omartahboub2900
    @omartahboub2900 3 года назад +1

    This is usually a phone screen interview question :) !!

  • @raahelbaig8347
    @raahelbaig8347 4 года назад

    What advantage does the leftproduct and rightproduct arrays provide as opposed to calculating and multiplying the elements in the list to the left and right of that index in the loop itself?

    • @F272g
      @F272g 4 года назад

      Raahel Baig time complexity. If you calculate the product of elements to the left and right of every single index (which would be necessary to be able to use your implementation), you have a time complexity of O(n^2) which is too long for the problem

  • @mdabidiqbal1153
    @mdabidiqbal1153 4 года назад +1

    Awsm bro, I always wait for your video.

  • @vojtechsejkora1554
    @vojtechsejkora1554 4 года назад

    Thats cheeting with reading from output array. it is allowd? Maybe I study too much of turing machine where you have output tape witch is write-only.

  • @Antagon666
    @Antagon666 2 года назад

    Wait what.
    The division part is absolutely mental. There is no way that looping through all the elements n times will be faster than n divisions.

  • @nalinprabhath7062
    @nalinprabhath7062 4 года назад

    shouldn't the nums[i-1] in the final code for calculating left products be nums[i]????

  • @prithulbahukhandi1714
    @prithulbahukhandi1714 4 года назад

    Good work bro !! Nice explaination.
    You make me better..

  • @LordErnie
    @LordErnie 2 года назад

    I solved it with a nested for loop. The first loop loops over the array, the second loop does the multiplying, and skips over the index of the current item. Less complicated and it allows you to make only 1 new array. Your indexes are tracked by the for loops and you only need to make 1 variable, the array.

    • @nayanyadav6919
      @nayanyadav6919 2 года назад

      Hey man! I also tried doing it this way but the output is way too different than what I expected it to be. I'm kind of new to programming so I didn't really go into complexity for this question and following the boilerplate code mentioned in the question. Can you pls tell me where I'm going wrong? Would be a great help. Here's my logic.
      public static void prod(int[] arr)
      {
      for(int i=0; i

    • @minciNashu
      @minciNashu Год назад

      That's quadratic not linear

  • @redwilliams1804
    @redwilliams1804 4 года назад

    My go to solution was to have 2 for loops (1 is nested), *= a variable (initialized at 1). Only thing is that if the iteration variable of inner loop == interation variable of outer loop, continue through inner for loop. Store to temp, return temp, but I guess this is too long?

    • @redwilliams1804
      @redwilliams1804 4 года назад

      My code:
      int[] allBut(int[] input){
      int[] output = new int[input.length];
      for(int i = 0; i < input.length; i++){
      int product = 1;
      for(int move = 0; move < input.length; move++){
      if (move == i) continue;
      product *= input[move];
      }
      output[i] = product;
      }
      return output;
      }

  • @grandromusic683
    @grandromusic683 4 года назад

    My solution would be (JS):
    function productExceptSelf(input) {
    var output = [];
    for (var i = 0; i < input.length; i++) {
    var product = 1;
    for (var j = 0; j < input.length; j++) {
    if (j != i) {
    product *= input[j];
    }
    }
    output.push(product)
    }
    return output;
    }
    Seems the least complicated to me, because while multiplying with left and right is true, its easier to say it multiplies with everything except the own index (j != k)

  • @Victoria-ow7zi
    @Victoria-ow7zi 4 года назад

    I would have copied all the values from the input array into a new one in a loop and changed the index value to 1 and multiplied the elements in the array and added that to the output array

  • @n_fan329
    @n_fan329 3 года назад

    let tab = [1, 2, 3, 4]
    let output=[]
    tab.forEach(val1 =>output.push(tab.filter(val2=>val2!==val1).reduce((a,b)=>a*b,1)))
    console.log(output); // [ 24, 12, 8, 6 ]

  • @jeestudy2398
    @jeestudy2398 4 года назад

    Cant we get the product of all elements, and then divide that product for each index element

  • @nikhilreddy719
    @nikhilreddy719 3 года назад +1

    Are these coding questions for Software roles? I have a CAD Engineer role interview with Apple. Can I expect similar questions?

  • @ayushsingh1315
    @ayushsingh1315 4 года назад +3

    Define a function
    Int divide(Divident, divisor):
    c=1
    while (Divident>1):
    Divident-=divisor
    c-=-1
    return c
    I think this should also work...

    • @zephyrred3366
      @zephyrred3366 4 года назад

      if divisor is 0 or negative it's an infinite loop

    • @bamberghh1691
      @bamberghh1691 3 года назад

      Division here is O(n) so the entire solution would be O(n^2)

  • @rajatagrawal7016
    @rajatagrawal7016 4 года назад

    Great work man

  • @killermonkey1392
    @killermonkey1392 2 года назад

    A (surprisingly expressive) one-liner Haskell version of the first solution:
    productExceptSelf :: [Int] -> [Int]
    productExceptSelf nums = zipWith (*) (init $ scanl (*) 1 nums) (tail $ scanr (*) 1 nums)

  • @MrCitizen00
    @MrCitizen00 4 года назад

    We can also solve this by simply taking the except element to 0th index in single loop and splitting the list from 0th index and finding the product of elements of list from first index to end, so no notation of left and right required..🙌

    • @think_tank5603
      @think_tank5603 4 года назад

      In that case, you won't be able to solve it on O(n) complexity.

  • @Hogojub
    @Hogojub 4 года назад +7

    I knew what to do but I couldn't translate it into code :/

  • @mehmetserdaruz7261
    @mehmetserdaruz7261 Год назад

    Before even watching the video, this is how I would do it (in C):
    int input[4] = {1, 2, 3, 4}; // input array of the example
    int output[4] = {1, 1, 1, 1}; // initialize output array to 1's (neutral element of multiplication)
    for (int i = 0 ; i < 4 ; i++) {
    // multiply the current position in the OUTPUT array with every value to the left of the current position in the INPUT array (except first one).
    if (i != 0) {
    for (int j = i-1 ; j > 0 ; j--) {
    output[i] *= input[j];
    }
    }
    // Do the same thing but to the right.
    if (i != 3) {
    for (int j = i+1 ; j < 4 ; j++) {
    output[i] *= input[j];
    }
    }
    }
    Edit: I'll take it as a win

  • @ravichandra9866
    @ravichandra9866 4 года назад +1

    How about having a single for loop and each time making that particular index element as 1 and multiplying the whole array... Thus ending without division and O(n).

    • @meetpandya2722
      @meetpandya2722 4 года назад +3

      you'll multiply whole array n times (for each index) that leaves you with O(n^2).

    • @zacgndjdh6828
      @zacgndjdh6828 2 года назад

      This is N^2

  • @gouravsaini9375
    @gouravsaini9375 2 года назад

    First iterate a loop and multiply all elements of an array and store into result variable.
    After that iterate same loop and divide result variable with ith element give ans for that position

  • @pepperet5216
    @pepperet5216 3 года назад +1

    can't you just calculate the total multiplication and then divide by each element ?

  • @harold3802
    @harold3802 4 года назад +1

    Nice, excellent explanation

  • @ragu5542
    @ragu5542 4 года назад

    Nick - how is this explanation ? Its essentially the same as yours but condensed.
    Take S = [2,3,4,5] as an example. The expected answer is P = [60, 40, 30, 24].
    "DIAGRAM" :
    "1"[3,4,5]. product = "1", 3,4,5.
    [2][4,5]. product = 2,4,5.
    [2,3][5]. product = 2,3,5.
    [2,3,4]"1". product = 2,3,4, "1".
    S = the given array, Ni = the i-th element of S,
    Pi = product for Ni, Li = product of numbers on left of Ni, Ri = product of numbers on right of Ni.
    Thus, Pi = Li * Ri, for each Ni. We also see it the above "diagram".
    STEPS -
    (1) First find only Li for each element in S ["1", {1 * 2}, {2 * 3} , {6 * 4}] == [1, 2, 6, 24]
    (2) Next we find only Ri for each element in S [{20 * 3}, {5 * 4}, {5 * 1}, "1"] == [60, 20, 5, 1]
    (3) Now, multiply the corresponding elements of Li & Ri to get Pi == [60, 40, 30,24].
    Thus, step 3 gives us the answer we expected. Notice that we can combine steps 2,3 as discussed at 8:20 instead of doing them separately.

  • @hari8568
    @hari8568 4 года назад

    I was thinking a nested loop with outer loop varying from 0 to n-1,and inner loop with index j such that if i index equals j index increment j by 1 and continue iteration.For last edge case that is when i=n-1 j would have index error so reduce n by 1 in last iteration

    • @GameSteals
      @GameSteals 4 года назад

      Yes, why not, but the algorithm has a complexity of O(n^2), and the question specifies that we need to solve it in O(n)

    • @hari8568
      @hari8568 4 года назад

      @@GameSteals ok

  • @rupaldesai7098
    @rupaldesai7098 4 года назад +3

    Most popular coding interview question!

  • @surajkumargupta7050
    @surajkumargupta7050 3 года назад

    Hey bro it's an amazing video I loved it, I'm following your video from long back and had subscribed your channel 😉.
    I'm stuck to a problem in code signal it is "Election Winner" could you please make a video on it so that people like me can easily refer your video and can clear there doubt. I'm waiting for the video 😊🙏.

  • @reallifegambits
    @reallifegambits 4 года назад +5

    Hi Nick
    Can you please create a playlist of all hard problems in Leetcode? I love the way you explain... keep it up

  • @voidtype
    @voidtype 2 года назад

    Can't you do something like this:
    total = e^(sum(input))
    for i in range 0,len(input):
    output[i] = ln (total - e^input[i])

  • @abdullah1924
    @abdullah1924 4 года назад

    what about using log of exp