Pascal's Triangle - Leetcode 118 - Python

แชร์
ฝัง

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

  • @shoooozzzz
    @shoooozzzz ปีที่แล้ว +46

    The easy problems look like hard problems when you're trying to come up with a solution in O(n). Turns out the "optimal" solution is O(n)^2 using a nested for-loop =)

    • @ferroumsamir6531
      @ferroumsamir6531 ปีที่แล้ว

      what if we already have a list ? like [1,2,1] and we want the next one ? what would be the solution ?

  • @dimakavetskyy2082
    @dimakavetskyy2082 2 ปีที่แล้ว +67

    how is this question easy

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

      Just is babe just is

    • @MrjavoiThe
      @MrjavoiThe ปีที่แล้ว +6

      Agreed, this took me like 1h to solve.

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

      Was thinking the same fr 🤣

    • @seenumadhavan4451
      @seenumadhavan4451 11 หลายเดือนก่อน

      ​@@MrjavoiThejust one hour 🤯 broo

    • @seit-55omvikhe50
      @seit-55omvikhe50 5 หลายเดือนก่อน

      ​@@seenumadhavan4451I have been doing this from past 3 hrs

  • @msyugandhar3377
    @msyugandhar3377 2 ปีที่แล้ว +36

    I have a doubt, Why can't we just add a 1 to the beginning and to the end for every new list so that there is no need to add a 0 to the previous list??

    • @thebigpart783
      @thebigpart783 2 หลายเดือนก่อน +1

      this is a way of doing it and it works, I have this solution:
      triangle = []
      triangle.append([1])
      if numRows == 1:
      return triangle
      triangle.append([1, 1])
      if numRows == 2:
      return triangle
      for i in range(2, numRows):
      curr_row = [1]
      prev_row = triangle[-1]
      for j in range(1, i):
      curr_row.append(prev_row[j-1] + prev_row[j])
      curr_row.append(1)
      triangle.append(curr_row)
      return triangle

  • @abudajaaj
    @abudajaaj ปีที่แล้ว +6

    There's a mathematical algorithm to find each value by row: (nCk) = (nC(k-1)) * (n+1-k)/k, which works really well, yet I couldn't get it to work because of a weird issue at row 11 where it goes from 461 down to 329, which is 1 less than it should be.

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

    Your two-pointer hint made this easy. I was stuck on this for awhile
    Super annoying problem

  • @jianchoi7434
    @jianchoi7434 2 ปีที่แล้ว +10

    파스칼 삼각형의 각 행의 끝에 0을 넣는다는 아이디어는 인터넷 전체에서 이 분이 처음으로 내신 것 같은데, 정말 기발한 것 같아요. 다음에는 저 방식으로 스크립트를 짜 봐야겠다는 생각이 듭니다 감사합니다

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

    I had solved this before watching the video. His solution is better, but, for the sake of seeing another solution, I thought I would post the solution I had come up with.
    Python3
    def generate(cls, num_rows: int) -> List[List[int]]:
    if num_rows

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

      wow

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

      Nice
      Here is my solution, time complexity is O(n^2), need to optimize
      class Solution:
      def generate(self, numRows: int) -> List[List[int]]:


      lst, finalLst = [0, 1, 0], [[1]]
      for i in range(numRows - 1):
      l, r = 0, 1
      newLst = []
      while(r < len(lst)):
      element = lst[l] + lst[r]
      newLst.append(element)
      l = r
      r = r + 1
      finalLst.append(newLst)
      newLst = [0]+newLst+[0]
      lst = newLst

      return finalLst

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

    U a God. Got another way instead of dealing with those pesky 0's on the left and right end. We create another temp array already filled with 1's for both sides:
    res = [[1]]
    for _ in range(1,numRows):
    temp = [1] * (len(res[-1]) + 1)
    for i in range(1,len(temp)-1):
    temp[i] = res[-1][i-1] + res[-1][i]
    res.append(temp)
    return res

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

      good idea, i like it!

    • @chandank5266
      @chandank5266 10 หลายเดือนก่อน

      @@NeetCode here's the code without worrying much *)
      final_res = [ ]
      for i in range(numRows):
      res = [ ]
      for j in range(i+1):
      if j == 0 or j == i:
      res.append(1)
      else:
      elem = final_res[i-1][j] + final_res[i-1][j-1]
      res.append(elem)
      final_res.append(res)

      return final_res

  • @kbizzy111
    @kbizzy111 8 วันที่ผ่านมา

    class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
    res = []
    for i in range(numRows):
    temp = [1]*(i+1)
    for j in range(1,i):
    temp[j] = res[i-1][j-1] + res[i-1][j]
    res.append(temp)
    return res

  • @JashSingh-bv5ge
    @JashSingh-bv5ge 6 หลายเดือนก่อน +1

    im still not understanding how the code works :(

  • @Melvinn27
    @Melvinn27 2 ปีที่แล้ว +5

    So appreciative of these videos.

  • @putin_navsegda6487
    @putin_navsegda6487 11 หลายเดือนก่อน +1

    I did this problem by myself, however i used binomial distribution. Thank you for your video and explication

  • @AryanKumar-cm2iq
    @AryanKumar-cm2iq 2 ปีที่แล้ว +1

    There is no need to add a 0 in the start or the end
    def generate(self, numRows: int) -> List[List[int]]:

    if numRows==1: return [[1]]
    if numRows==2: return [[1],[1,1]]
    itr=numRows-2
    pa=[[1],[1,1]]
    while itr:
    l=[]
    for i in range(len(pa[-1])-1):
    s=pa[-1][i]+pa[-1][i+1]
    l.append(s)
    l.insert(0,1)
    l.append(1)
    pa.append(l)
    itr-=1
    return pa

    • @thebigpart783
      @thebigpart783 2 หลายเดือนก่อน

      you can remove your insert at the beginning this is O(n), you can just write l = [1]

  • @challangour5557
    @challangour5557 หลายเดือนก่อน

    class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
    if numRows == 0:
    return []
    elif numRows == 1:
    return [[1]]

    x = [[1], [1, 1]]

    for i in range(2, numRows):
    y = [1]
    for j in range(1, len(x[i-1])):
    y.append(x[i-1][j] + x[i-1][j-1])
    y.append(1)
    x.append(y)

    return x

  • @Progamer-fq8st
    @Progamer-fq8st ปีที่แล้ว

    Another solution without adding zeros at the end
    class Solution {
    public:
    vector generate(int numRows) {
    vector v;

    for(int i = 0;i

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

    Correction maybe :
    for i in range(1,numRows): #should be the first loop

  • @danielsun716
    @danielsun716 ปีที่แล้ว

    excluding tricks' version FYI:
    def generate(self, numRows: int) -> List[List[int]]:
    if numRows == 1:
    return [[1]]
    res = [[1], [1, 1]]
    dp = res[-1]
    for i in range(2, numRows):
    nextDP = [1] * (len(dp) + 1)
    for j in range(1, len(nextDP) - 1):
    nextDP[j] = dp[j - 1] + dp[j]
    dp = nextDP
    res.append(dp)
    return res

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

    what will be the code for numrows=o?

  • @theelitecoder5981
    @theelitecoder5981 2 ปีที่แล้ว +7

    Sir can u please check this once...
    I think this is a pretty clever approach..
    Code :
    result = []
    for i in range(row):
    s = []
    for j in range(i + 1):
    if j !=0 and j != i:
    s.append(result[i-1][j] + result[i-1][j-1])
    else:
    s.append(1)
    result.append(s)
    return result
    Please let me know !!

    • @huzaifanaseerkhan
      @huzaifanaseerkhan ปีที่แล้ว

      Yeah, it's good but it is the same O(n^2) space and time complexity

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

      Yes, Your solution took 13.9 mb and his solution took 13.8 mb. It may seem insignificant for smaller inputs, but not for larger inputs. I think. Thanks for your sharing your solution.

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

    in line 8 how was the range(len(res[-1]) + 1) deduced? can't wrap my head around it..

    • @akshatshukla143
      @akshatshukla143 2 ปีที่แล้ว +11

      So basically, len(res[-1]) is used to get the length of the last row in the list cuz [-1] represents the last element . Since every new row in the pascal's triangle is 1 element longer we add 1 to len(res[-1]) to get the range.

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

      I used for(let j=0;j

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

    I was asked this question for a 5 thousands per month internship

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

    i just added a 1 at the start and at the end of each new row

  • @bobbobby3056
    @bobbobby3056 ปีที่แล้ว

    how does this question have anything to do with bfs it doesnt use a queue? seems like you just store each layer so you can use it to calculate the next...

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

    when you use res[-1] you are using another O(n) there , that is makes this O(n^3) solution. Instead , you can use i.

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

      we can use len(temp)-1

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

      Sorry, Actually res[-1] is not O(n) it is O(1) since we giving the index. Just realised. My bad!

    • @Rajmanov
      @Rajmanov ปีที่แล้ว

      @@thirunaavukkarasum4487 actually
      Here's a breakdown:
      [0]: This list creation has a time complexity of O(1) because it involves a single element.
      res[-1]: This operation has a time complexity of O(1). It's a simple retrieval operation that gets the last element of res. If res[-1] itself is a list of length m, then creating a new copy of this list (which happens implicitly when we do list concatenation) will take O(m).
      [0]: Same as the first operation, it's O(1).
      +: The concatenation operation has time complexity O(n), where n is the length of the resulting list.
      So overall you are right it is a O(n^3) solution

  • @vishnusunil9610
    @vishnusunil9610 10 หลายเดือนก่อน

    Absolutely stunning piece of code can i get a reference to Google or Amazon 😃

  • @sureshbabuk5241
    @sureshbabuk5241 11 หลายเดือนก่อน

    I Have added 1 at both ends and updated unfilled columns with two pointer solution
    List result = new ArrayList(numRows);
    if (numRows >= 1) {
    result.add(Arrays.asList(1));
    }
    if (numRows >= 2) {
    result.add(Arrays.asList(1, 1));
    }
    if (numRows > 2) {
    for (int i = 3; i

  • @PriyanshuRaj-bx6to
    @PriyanshuRaj-bx6to 4 หลายเดือนก่อน

    class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
    outerArray = []
    for i in range(1,numRows+1):
    tempArray = [1]*i
    for j in range(1,i-1):
    tempArray[j] = outerArray[i - 2][j-1] + outerArray[i - 2][j]
    outerArray.append(tempArray)
    return outerArray
    Is it good Solution

  • @chamikaonyt
    @chamikaonyt ปีที่แล้ว

    #My solution
    class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
    answer = [[1], [1,1]]
    if numRows == 1: return [answer[0]]
    if numRows == 2: return answer
    for i in range(numRows-2):
    answer.append([1])
    for i in range(2, len(answer)):
    for j in range(1, i):
    answer[i].append(answer[i - 1][j - 1] + answer[i - 1][j])
    answer[i].append(1)
    return answer

  • @CyrusWong-yq4uw
    @CyrusWong-yq4uw 6 หลายเดือนก่อน +2

    Dude I litterally understand the drawing explaination but when I get to the actual coding part, I have no clue on how to code even after watching this video, maybe I am just too dumb for coding :(

    • @DanielPratt-bj9ly
      @DanielPratt-bj9ly หลายเดือนก่อน

      I was there, there’s a reason a degree takes 4 years. No one gets this stuff without thousands of hours of practice. If you’re not prepared to commit to that I wouldn’t bother, but if you are it can show you some of the coolest things you’ll ever see,

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

    Brilliant explanation!

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

    we can use our math knowledge, with combunations.
    *from math import comb*
    *class Solution:*
    *def generate(self, numRows: int) -> List[List[int]]:*
    *ans = []*
    *temp = [i for i in range(numRows)]*
    *for v in temp:*
    *i = 0*
    *temp1 = []*
    *while i

  • @anupriya5535
    @anupriya5535 ปีที่แล้ว

    In line 8:- we cannot concatenate int to list. I am not able to fix that

    • @StfuSiriusly
      @StfuSiriusly ปีที่แล้ว

      your + 1 is prob outside of a paren

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

    nicely explained.

  • @amitozazad1584
    @amitozazad1584 8 หลายเดือนก่อน

    Hmm, I used the same solution :)

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

    Idk how to thank you anyway sending luck your way✨🌻

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

      Appreciate it :)

  • @fareedahshaik1519
    @fareedahshaik1519 ปีที่แล้ว

    why have we took res[-1]?

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

      Negative indices count from the end of the list. So -1 refers to the last element, -2 to the second last, and so on.
      In this case, res[-1] gives you the last element of res, which is [1].

  • @rafx
    @rafx 6 หลายเดือนก่อน

    fuck, i guess im too stupid for that

    • @DanielPratt-bj9ly
      @DanielPratt-bj9ly หลายเดือนก่อน

      No you’re not, it’s just your first time in the thunderdome.

  • @burburchacha
    @burburchacha ปีที่แล้ว

    I use dynamic programming and its faster

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

    instead of looping through (len(res[-1]) + 1), can you loop through (len(temp) -1) instead?

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

    I do not understand the space complexity of O(numRows^2). If we ignore the output space wouldn’t the space complexity be O(1)

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

      Yes if you do exclude the resultant array from the space complexity, you resulting complexity will be O(1)

    • @Rajmanov
      @Rajmanov ปีที่แล้ว

      it's completely impossible to be 0 (1) just saying,

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

    How is this related to dynamic programming

    • @neslzkusfep
      @neslzkusfep ปีที่แล้ว

      This problem lends itself well to the application of dynamic programming techniques, but Neetcode didn't use any in his solution.

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

    Solve Restore Binary Search Tree in O(1) space complexity solution. Thanks

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

    Didn't work

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

      me tooo

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

      Use the formula binomial theorem, you can reply me if you want the code

  • @user-yj5qw8pd3p
    @user-yj5qw8pd3p 2 หลายเดือนก่อน

    Python is shit

  • @Sandeep-yw2rb
    @Sandeep-yw2rb 2 ปีที่แล้ว

    If you are making video, atleast use an optimized way i.e DP with Recursion instead of showing ads with n2 solution

  • @Richard-yz2gy
    @Richard-yz2gy 7 หลายเดือนก่อน

    how the hell you come up with that solution, that is clever

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

    this guy's brain works differently. cant believe how much "neater" his code comparing to mine 🥲😅