Apple Coding Interview Question - Product Of Array Except Self

แชร์
ฝัง
  • เผยแพร่เมื่อ 23 ส.ค. 2024

ความคิดเห็น • 298

  • @aryamankukal1056
    @aryamankukal1056 3 ปีที่แล้ว +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

  • @AndrewYatzkan
    @AndrewYatzkan 4 ปีที่แล้ว +411

    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

    • @MrZeffy
      @MrZeffy 4 ปีที่แล้ว +7

      That's literally dividing dude.

    • @NeverGiveUp186
      @NeverGiveUp186 4 ปีที่แล้ว +4

      Modern problems require modern solutions 🤣🤣

  • @hahahahhahahhaha786
    @hahahahhahahhaha786 4 ปีที่แล้ว +63

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

  • @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 3 ปีที่แล้ว

      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)

  • @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.

  • @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 7 หลายเดือนก่อน

      @@bhavyajain638 So??

  • @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.

  • @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

  • @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

  • @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

  • @ImranHossain-by6nk
    @ImranHossain-by6nk 3 ปีที่แล้ว

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

  • @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 😊

  • @yogeshgupta6094
    @yogeshgupta6094 3 ปีที่แล้ว +1

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

  • @androidking8158
    @androidking8158 3 ปีที่แล้ว

    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))

  • @KaisarAnvar
    @KaisarAnvar 2 ปีที่แล้ว

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

  • @user-ps9vn7hq1j
    @user-ps9vn7hq1j 4 ปีที่แล้ว +13

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

    • @nickfratto2439
      @nickfratto2439 3 ปีที่แล้ว

      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.

  • @shailendratripathi3944
    @shailendratripathi3944 3 ปีที่แล้ว

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

  • @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)

  • @zombiekiller7101
    @zombiekiller7101 3 ปีที่แล้ว

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

  • @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 3 ปีที่แล้ว

      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 3 ปีที่แล้ว

      @@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 :)

  • @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

  • @selfquerynil7532
    @selfquerynil7532 4 ปีที่แล้ว +3

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

    • @sabe607
      @sabe607 3 ปีที่แล้ว

      That’s quadratic time

  • @eliyahutarab4862
    @eliyahutarab4862 3 ปีที่แล้ว +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

  • @codeymiller5954
    @codeymiller5954 3 ปีที่แล้ว

    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

    • @JJCUBER
      @JJCUBER 25 วันที่ผ่านมา

      O specifies a class/set of functions; accordingly, O(n) = O(2n) = O(an) for a in R* . Having multiple for loops does not violate the constraints (not to mention, 1. doing more work in a single loop isn’t all that different from having multiple separate for loops [in the sense that you would be doing, say, 2 units of work per iteration instead of 1], and 2. having simpler separated for loops can be more easily unrolled and optimized, so your solution is likely *slower* than having multiple separate for loops).

  • @zerefX_
    @zerefX_ 2 ปีที่แล้ว

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

  • @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

  • @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

  • @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 4 ปีที่แล้ว

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

  • @kenhaley4
    @kenhaley4 4 ปีที่แล้ว +48

    In addition, the second solution only requires 2 loops instead of 3.

    • @sammndl9592
      @sammndl9592 3 ปีที่แล้ว +1

      After all, it's just a more condensed/optimised version of the original solution.

  • @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

  • @omkumar0900
    @omkumar0900 3 ปีที่แล้ว

    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.

    • @damianm2896
      @damianm2896 2 ปีที่แล้ว

      how'd the interview go?

  • @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 ]

  • @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 :)

  • @sannge6471
    @sannge6471 4 ปีที่แล้ว +4

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

    • @james.lambert
      @james.lambert 3 ปีที่แล้ว

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

  • @brijbhansingh6350
    @brijbhansingh6350 3 ปีที่แล้ว +1

    thank you so much for this amazing solution

  • @ashishranjan4623
    @ashishranjan4623 4 ปีที่แล้ว +1

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

  • @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)

  • @dqXIMet
    @dqXIMet 4 ปีที่แล้ว +3

    Amazing solution! Thank you

  • @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.

  • @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 😁!

  • @nutsirimaunjit7427
    @nutsirimaunjit7427 3 ปีที่แล้ว

    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

  • @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)

  • @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.

  • @victorbarinov
    @victorbarinov 3 ปีที่แล้ว +1

    This solution is correct only for small arrays. E.g. if all elements >= 2, it will overflow for lengths of 64+.
    If it is not correct for n > 63, what is the point to have O(n), while O(n*n) is simpler and likely not slower in real CPU architecture?

    • @bhavyajain638
      @bhavyajain638 2 ปีที่แล้ว

      Can you explain why will it break? And how does n^2 solution overcome it?

  • @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

  • @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

  • @kobenade
    @kobenade 3 ปีที่แล้ว

    const produce = arr => {
    return arr.map((e, i, a) => {
    const sub = [...a];
    sub.splice(i, 1);
    return sub.reduce((a, b) => a * b)
    })
    }
    console.log(produce([1, 2, 3, 4]));

  • @abimaelmartell
    @abimaelmartell 3 ปีที่แล้ว +3

    Love how you explain this stuff 😅

    • @wikyprash6638
      @wikyprash6638 3 ปีที่แล้ว

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

  • @revraitah
    @revraitah 4 ปีที่แล้ว +2

    Thanks man, it is really helpful!

  • @lb9970
    @lb9970 3 ปีที่แล้ว

    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?

  • @LordErnie
    @LordErnie 3 ปีที่แล้ว

    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 2 ปีที่แล้ว

      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;
      }

  • @minhazulislam4682
    @minhazulislam4682 2 ปีที่แล้ว

    My progress (3 functions for this one, last one is the Nick's version)
    def func(arr):
    ans = [0]*len(arr)
    x = 1
    for i in arr:
    x *= i
    for i, e in enumerate(arr):
    ans[i] = x // e
    return ans
    def func2(arr):
    ans = [0]*len(arr)
    x = 1
    for i in arr:
    x *= i
    cnt_global = 0
    for i, e in enumerate(arr):
    m = e
    cpy = x
    cnt = 0
    while cpy >= m:
    cnt += 1
    cpy -= m
    cnt_global += 1
    ans[i] = cnt
    # print(cnt_global)
    return ans
    def func3(arr):
    length = len(arr)
    ans = [0]*length
    left = [1]*length
    right = [1]*length
    cnt = 0
    x = 1
    for i in range(length-1):
    x *= arr[i]
    left[i+1] = x
    cnt += 1
    x = 1
    for i in range(length-1, 0, -1):
    x *= arr[i]
    right[i-1] = x
    cnt += 1
    for i in range(length):
    ans[i] = left[i]*right[i]
    cnt += 1
    # print(cnt)
    return ans
    arr = [1, 2, 3, 4, 5]
    print(func(arr))
    print(func2(arr))
    print(func3(arr))

  • @muhammadsalmankhan9326
    @muhammadsalmankhan9326 4 ปีที่แล้ว

    input = [1,2,3,4]
    # output = [24,12,8,6]
    n = input
    o = [ ]
    y=1
    for i in input:
    for j in n:
    if(i!=j):
    y=y*j
    o.append(y)
    y=1
    print(o)
    # i have solved it by my self using python

  • @muddycalendar3292
    @muddycalendar3292 2 ปีที่แล้ว

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

  • @vishistsd
    @vishistsd 3 ปีที่แล้ว

    Amazing stuff mate as usual

  • @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

  • @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)

  • @gouravsaini9375
    @gouravsaini9375 3 ปีที่แล้ว

    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

  • @user-ug4vx8yl8w
    @user-ug4vx8yl8w 4 ปีที่แล้ว +5

    No division? How about this: Log(a/b) = log(a)-log(b); a=b*exp(log(a)-log(b)). We gotta deal with the negatives and zeroes additionally though, which is not a problem

    • @orkhanalikhanov
      @orkhanalikhanov 4 ปีที่แล้ว

      log and exp are costy functions but this is a clever trick 👍🏽

    • @letao12
      @letao12 4 ปีที่แล้ว

      I agree it's clever, but you can potentially lose precision and get the wrong result. Floating point operations are not good when solving integer problems.

  • @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

  • @Hogojub
    @Hogojub 4 ปีที่แล้ว +7

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

  • @amitk476
    @amitk476 4 ปีที่แล้ว +1

    Thanks for the wonderful explanation.
    you make problems look simple

  • @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?

  • @frankribery3362
    @frankribery3362 4 ปีที่แล้ว +3

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

  • @lifeofhiren
    @lifeofhiren 3 ปีที่แล้ว

    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

  • @SuperGilly123456789
    @SuperGilly123456789 4 ปีที่แล้ว +5

    Great explanation and technique.
    I had a solution in my mind that can't we just loop through the array and multiply each element and store it. Then loop again and divide the stored value by every element and store it in output array.

    • @_techwaves
      @_techwaves 4 ปีที่แล้ว

      In the problem they said "solve it without division"

    • @SuperGilly123456789
      @SuperGilly123456789 4 ปีที่แล้ว +1

      @@_techwaves okay. Thanks for clarifying it for me.😊

    • @_techwaves
      @_techwaves 4 ปีที่แล้ว +1

      @@SuperGilly123456789 ❤❤

    • @LoganKearsley
      @LoganKearsley 4 ปีที่แล้ว +1

      If the numbers have a bounded range, you could do exactly that but use bitshifts and multiplication by the modular inverse (acquired via lookup table) to get around the division restriction. Then you could do it in-place.

    • @SuperGilly123456789
      @SuperGilly123456789 4 ปีที่แล้ว

      @@LoganKearsley Okay. Thanks mate.

  • @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 3 ปีที่แล้ว

      This is N^2

  • @voidtype
    @voidtype 3 ปีที่แล้ว

    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])

  • @cobain8102
    @cobain8102 4 ปีที่แล้ว +2

    hey nick! I have been watching your videos a lot recently. I am 16 and still in my sophomore year of high school. I am learning my first language (python) and i have gotten to OOP. Do you have any advice for my future (hopefully a SWE). Thanks!

  • @DOOREO
    @DOOREO 4 ปีที่แล้ว +3

    Wouldn’t two pointers or two indexes take less time?

    • @sarkarasm285
      @sarkarasm285 4 ปีที่แล้ว +2

      Yes it will take less time but the complexity remains the same.

  • @saidaouyous3485
    @saidaouyous3485 2 ปีที่แล้ว

    Great as usual ✊

  • @GauravSingh-ku5xy
    @GauravSingh-ku5xy 2 ปีที่แล้ว

    well explained bro

  • @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

  • @nikhilrana8800
    @nikhilrana8800 4 ปีที่แล้ว

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

  • @pulgupta
    @pulgupta 4 ปีที่แล้ว

    Nice solution

  • @Antagon666
    @Antagon666 3 ปีที่แล้ว

    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.

  • @omartahboub2900
    @omartahboub2900 4 ปีที่แล้ว +1

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

  • @gammastrain5289
    @gammastrain5289 3 ปีที่แล้ว

    To avoid division maybe we could use logarithmic approach

  • @GG-hk5iz
    @GG-hk5iz 4 ปีที่แล้ว

    Only video where I understood the solution/technique

  • @anuragsandhu9590
    @anuragsandhu9590 4 ปีที่แล้ว +1

    In Javascript:
    1. Without Division : `function withOutDivision(ar) {
    let leftProdArray = [1], rightProdArray = [1], outputArray = [];
    for (let index = 1; index < ar.length; index++) {
    leftProdArray.push(leftProdArray[index - 1] * ar[index - 1])
    }
    for (let index = ar.length - 2; index >= 0; index--) {
    rightProdArray.unshift(rightProdArray[0] * ar[index + 1])
    }
    leftProdArray.forEach((value, index) => {
    outputArray.push(value * rightProdArray[index])
    });
    return outputArray;
    }`
    OR
    2. With division :
    `function withDivision(ar) {
    let outputArray = [],
    product = 1;
    ar.forEach((value) => {
    product *= value
    });
    ar.forEach((value) => {
    outputArray.push(product / value);
    });
    return outputArray;
    }`

    • @shivpadsharma8875
      @shivpadsharma8875 4 ปีที่แล้ว +1

      Bro u need to give special care to cases where element of array is 0

    • @shivpadsharma8875
      @shivpadsharma8875 4 ปีที่แล้ว +1

      In division

  • @n_fan329
    @n_fan329 4 ปีที่แล้ว

    let tab=[12,3,11,20,19,10]
    let result = []
    tab.forEach(val => {
    return result.push(tab.filter(val2=>val2!==val).reduce((a,b)=>a*b))
    }

  • @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.

  • @sumeetbansal3552
    @sumeetbansal3552 4 ปีที่แล้ว

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

  • @pepperet5216
    @pepperet5216 3 ปีที่แล้ว +1

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

  • @encrypt5248
    @encrypt5248 4 ปีที่แล้ว

    easy way:
    int a[]={2,3,4,5};
    int i,j,m=1;
    for(i=0;i

  • @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.

  • @TheElementFive
    @TheElementFive 3 ปีที่แล้ว

    How about this solution (Python) using a sliding window?
    import numpy as np
    if len(arr) == 0:
    raise Exception("Invalid array")
    else:
    products = []
    for i in range(len(arr)):
    product = np.prod(arr[:i] + arr[i + 1:])
    products.append(product)
    return products

    • @killermonkey1392
      @killermonkey1392 2 ปีที่แล้ว +1

      That's O(n^2), you're looping over the whole array for each element.

  • @Kokurorokuko
    @Kokurorokuko 4 ปีที่แล้ว

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

  • @n00b_asaurus
    @n00b_asaurus 4 ปีที่แล้ว

    I'm gonna take a stab at 2:23, before you show your solution.
    create a variable total_product, set it equal to the product of all numbers in nums.
    go through nums and set output[i] to total_product / nums[i]
    Edit: 3:10.... I see the problem here...
    power of -1 then!

  • @K_RNDM
    @K_RNDM 4 ปีที่แล้ว

    what about creating a duplicate of given array and swapping the element of whose product without self is to calculate with the first element then multiplying index 1 to 4 and storing it in result array on corresponding index... then assigning resetting the previous value of duplicate array again and do it for the next element till last element to ignore dividing? pretty easy question

    • @gorijalakiran7132
      @gorijalakiran7132 4 ปีที่แล้ว

      Check ur complexity if it is o(n) than its right....

    • @K_RNDM
      @K_RNDM 4 ปีที่แล้ว

      @@gorijalakiran7132 yeah it's O(n)

  • @shivampurbia6169
    @shivampurbia6169 4 ปีที่แล้ว

    How about Divide and conquer like merge sort ?

  • @nontth5355
    @nontth5355 3 ปีที่แล้ว

    time to create my own division function

  • @abhishekmalaviya7
    @abhishekmalaviya7 4 ปีที่แล้ว

    public static void main(String[] args) {
    int problemArray[] ={1,2,3,4},resultArray[] = new int[4];
    int resultMultiplication=1;
    for(int i =0;i

  • @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

  • @Sunil_1200
    @Sunil_1200 4 ปีที่แล้ว

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

  • @vanamutt43
    @vanamutt43 2 ปีที่แล้ว

    if array element cant be 0, then this solution is faster.
    int[] input = {1, 2, 3, 4};
    int[] output = new int[input.length];
    double temp, result = 1;
    for(Integer i : input)
    result *= i;
    for (int i = 0; i < input.length; i++) {
    temp = result * Math.pow(input[i], -1);
    output[i] = (int)temp;
    }

  • @scoperesolution2915
    @scoperesolution2915 4 ปีที่แล้ว +2

    Yet again, thanks for this.

  • @patrickjoel8779
    @patrickjoel8779 4 ปีที่แล้ว +1

    I used 2 for loops

  • @jgtb0pl
    @jgtb0pl 3 ปีที่แล้ว

    Ok so my solution worked a lil something like this:
    First multiply everything and store it
    Second for every element in input array store into second array stored/element

    • @jgtb0pl
      @jgtb0pl 3 ปีที่แล้ว

      Welp I had the same solution as him...