N-Queens - Backtracking - Leetcode 51 - Python

Поделиться
HTML-код
  • Опубликовано: 30 июл 2024
  • 🚀 neetcode.io/ - A better way to prepare for Coding Interviews
    🐦 Twitter: / neetcode1
    🥷 Discord: / discord
    🐮 Support the channel: / neetcode
    Twitter: / neetcode1
    Discord: / discord
    ⭐ BLIND-75 PLAYLIST: • Two Sum - Leetcode 1 -...
    💡 CODING SOLUTIONS: • Coding Interview Solut...
    💡 DYNAMIC PROGRAMMING PLAYLIST: • House Robber - Leetco...
    🌲 TREE PLAYLIST: • Invert Binary Tree - D...
    💡 GRAPH PLAYLIST: • Course Schedule - Grap...
    💡 BACKTRACKING PLAYLIST: • Word Search - Backtrac...
    💡 LINKED LIST PLAYLIST: • Reverse Linked List - ...
    Problem Link: neetcode.io/problems/n-queens
    0:00 - Read the problem
    3:56 - Drawing Explanation
    12:27 - Coding Explanation
    leetcode 51
    This question was identified as an interview question from here: github.com/xizhengszhang/Leet...
    #backtracking #python
    Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.
  • НаукаНаука

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

  • @NeetCode
    @NeetCode  3 года назад +24

    🚀 neetcode.io/ - I created a FREE site to make interview prep a lot easier, hope it helps! ❤

  • @wookyumkim4669
    @wookyumkim4669 2 года назад +164

    I love so much the idea of using posDiag set and negDiag set. That is the truly brilliant trick.

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

      Right? It truly is fascinating

    • @nachiket9857
      @nachiket9857 Год назад +2

      It's so good, who even comes up with these!

    • @illu1na
      @illu1na 9 месяцев назад

      @@nachiket9857 y = mx + c and for posDiag y = -x + c so c = y +x, and negDiag y = x +c so c = y-x. Note that the gradient is -1 for posDiag and 1 for negDiag since the given array starts 0 top row and increases as it goes down.

    • @davidbujosa
      @davidbujosa 9 месяцев назад +1

      truly

    • @demaxl732
      @demaxl732 6 месяцев назад +1

      I was fascinated. How can one even think of this!

  • @Cld136
    @Cld136 3 года назад +90

    Backtracking never been this easy after watching your video! Thanks for the excellent intuition about backtracking.

  • @harishsn4866
    @harishsn4866 2 года назад +8

    such an elegant and simple solution without having to pass through loads of different function unlike other videos I've seen. Thank you for this.

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

    I was a bit confused by the problem statement, but your explanation made it looks as simple as possible. Thanks for making such amazing content.

  • @vesicapiscis9717
    @vesicapiscis9717 Год назад +2

    This is the best video on backtracking I've seen so far. It was so good that I applauded after watching it.

  • @arjunv1624
    @arjunv1624 3 года назад +17

    Like the clear explanation of the problem and the code walkthrough. Please provide your analysis on the time/space complexity for each problem you are solving.

  • @SameenIslam
    @SameenIslam 2 года назад +2

    You explain difficult to understand concepts with amazing clarity, thank you for your work!

  • @miaowcat1
    @miaowcat1 Год назад +11

    Amazing, I've seen a couple other variant, but this version is easy, yet really captures the spirit of backtracking without hard to understand tricks

  • @jadkhalil9263
    @jadkhalil9263 Год назад +7

    Easily the best explanation on the internet thank you so much for your contributions :)

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

    AWESOME! The best channel every for explaining problem-solving questions and how to think about them, rather than just throwing the solutions in front of the audiences. ❤

  • @umutkavakli
    @umutkavakli Год назад +1

    I can't express how this explanation blew my mind! You're the best, thank you.

  • @VysePresidentGeo
    @VysePresidentGeo 8 месяцев назад +1

    While I was able to solve this myself quite easily, the use of sets - particularly the posDiag and negDiag sets - are incredibly elegant and I appreciate the tip. Thank you so much for your help!

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

    My best explanation of n-queens problem. Thank you!

  • @rajrsa
    @rajrsa Год назад +3

    I had seen this problem for the first time about 7 years ago in uni and I was too scared to even attempt it.
    Thanks for explaining it so beautifully and helping me conquer my fear. (I was so stupid to be scared of this problem lol)

  • @salehsaeed5734
    @salehsaeed5734 2 года назад +7

    I have been watching several videos on n-queen, your video is the most understandable

    • @NeetCode
      @NeetCode  2 года назад +5

      Thanks, happy it was helpful! 😃

    • @CostaKazistov
      @CostaKazistov 2 года назад +2

      When I am stuck on a problem, I like to watch 2-3 videos from different channels. Then it "clicks".
      Most success I had when it "clicks" on the first go, is when I watch NeetCode.

  • @symbol767
    @symbol767 2 года назад +2

    Awesome, I solved it by using a helper to iterate through the rows then columns, then diags each separately O(N) for each of those loops, but this way is much better.
    Thanks man

  • @user-lx1fc6ii9o
    @user-lx1fc6ii9o Год назад +1

    I learnt something from this video. You explained it very clearly and concisely. Thank you!

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

    Awesome!
    Mistakenly I used to iterate through all squares in a nested for-loop (similar to how we solve sudoku using backtracking). Now I see that there's no need in that.

  • @NamasteSaurav
    @NamasteSaurav 9 месяцев назад

    Shortest and best solution I have even seen. Thank you @Neetcode

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

    I started doing this problem and it was tricky, but the first part of the vid set me on the right track to code it up myself. Thanks bro

  • @hyk-f4r
    @hyk-f4r 2 года назад +1

    @Neetcode you are amazing as always just want to let you know I appreciate your channel and big thank you for these videos. If at all I clear the interview I sure will send at-least bag of chocolates to you.

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

    very clever approach using negative and positive diagonals.. thx a lot for sharing!

  • @Adarsh-mn7pl
    @Adarsh-mn7pl 2 года назад

    This is the most cleanest approach to this problem, specially using sets to check Validity

  • @The6thProgrammer
    @The6thProgrammer 9 месяцев назад

    Awesome solution, you simplified what I was trying to do greatly

  • @ilanaizelman3993
    @ilanaizelman3993 2 года назад +2

    Best explanation I have seen. Thanks!!!

  • @ivantishchenko4686
    @ivantishchenko4686 2 года назад +2

    Superb explanation as usual. Calm and thought out.

  • @vinaf4494
    @vinaf4494 6 месяцев назад

    Very helpful! Very clear with explanation in coding as well. You are the best mentor in my learning way!

  • @eshwarprasad2541
    @eshwarprasad2541 2 года назад +2

    This explanation is simple and to the point. Loved it. Can you make a video on how to frame backtracking logic for any unseen backtracking question. How to frame the logic.

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

    Great explanation!!! Keep it up, neetcode!

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

    Thanks for this amazing explanation. Loved it! 😍

  • @parthsalat
    @parthsalat Месяц назад +1

    Thanks for speaking clearly...was able to watch this on 2x

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

    Much needed ❤️

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

    I wish i could break down things as elegantly as u do in ur videos!!

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

    Thank You So Much for this amazing Explanation!!

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

    great, this helped me optimize my otherwise lengthy solution.😍

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

    this is the best explanation i've found so far

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

    Thanks for the content bro

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

    Hi NeetCode, thank you for the amazing explanation

  • @LeeK301
    @LeeK301 7 месяцев назад

    Brilliant solution; I learned a lot from the whole concept of (r+c) and (r-c); really great learning content.

  • @amrutaparab4939
    @amrutaparab4939 4 месяца назад

    You are a blessing to this world!

  • @Lan-so5gv
    @Lan-so5gv Год назад +1

    In terms of the time complexity, don't forget cloning the memory of the board (n^2), except for it, I think the time complexity would be O(n*n!), cuz your tree has n layers, n! is just the number of the bottom level, so the total time complexity I think is O(n!*n + n!*n^2) = O(n!*n^2), that's why the bounce of n is pretty tiny (1

  • @Karim-nq1be
    @Karim-nq1be Год назад

    I find this solution beautiful, and your explanation is very clear as usual, but at the same time it's not that obvious to see what's going on for the execution stack. Thank you again.

  • @robyc9545
    @robyc9545 Год назад +2

    This dude is a legend. Was wondering how you come up with this solution? Did you learn this at school? Do you consult with any resources?

  • @karankanojiya7672
    @karankanojiya7672 2 года назад +6

    OMG that diagonal intuition 🤐
    Respect ++ Sir!

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

    Great explanation, thank you very much!

  • @pythonbrothersandfamily
    @pythonbrothersandfamily 7 месяцев назад

    wow, you nailed it. Thanks a lot

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

    Your explanations are amazing.

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

    Thank you so much again!

  • @lesterdelacruz5088
    @lesterdelacruz5088 3 месяца назад

    the posDiag and the negDiag set is pretty clever. Makes the code so much more concise.

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

    Great video!

  • @yassineacherkouk
    @yassineacherkouk 8 месяцев назад

    Always after i came up with the brute force algorithm with some optimization i always come back to the channel to see how the work is done.

  • @Cloud-577
    @Cloud-577 2 года назад

    thank you this was very helpful

  • @DanielTruongDev
    @DanielTruongDev 2 года назад +10

    For those who confused what's the purpose of backtrack(0) code, it's basically call the backtrack function starting at row 0

  • @tnmyk_
    @tnmyk_ 4 месяца назад

    Excellent explanation!

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

    Simply the best :)

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

    Such an elegant solution!

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

    Great explaination ...Love from Nepal
    Hope you upload more videos

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

    pretty genius way to detect collision of diagonal!!

  • @tarangnima4641
    @tarangnima4641 2 месяца назад

    Amazing Explanation..💥

  • @Eddie-um6cw
    @Eddie-um6cw 2 года назад

    I don't understand this part: res.append (copy)
    return
    Can anyone help me what does that return mean? Does it return nothing or smt?

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

    This solution is elegant and ingenious. 🤩🤩

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

    Best explanation yet!

  • @AbyssiniaBenchmark
    @AbyssiniaBenchmark 9 месяцев назад

    Man you are awsome. Really awesome.

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

    Just brilliant :)

  • @ameynaik2743
    @ameynaik2743 3 года назад +12

    What is the time complexity of this solution?

    • @Lan-so5gv
      @Lan-so5gv Год назад

      In terms of the time complexity, don't forget cloning the memory of the board (n^2), except for it, I think the time complexity would be O(n x n!), cuz your tree has n layers, n! is just the number of the bottom level, so the total time complexity I think is O(n!*n + n!*n^2) = O(n!*n^2), that's why the bounce of n is pretty tiny (1

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

    thank you so much youre a hero!

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

      No!!! he's a super hero !

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

    This is 2nd backtracking problem I’ve seen, the line I don’t get is the remove line, so you’re adding everything to set just to remove it afterwards?

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

    One Question, Why can't we use regular variable instead of set to track posDiag and NegDiag, Since the values will be same.

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

    the c on line 16 is actually presenting all the rows. Using 'c' is better for visualization

  • @ValhaVaiyagam
    @ValhaVaiyagam 23 дня назад

    Hi Navdeep, Need a help ..how do u draw ? what tool u use ?

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

    You Just Nailed the Power of Python.

  • @Hiroki-Takahashi
    @Hiroki-Takahashi 4 месяца назад

    This is art

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

    Im getting an error on the part that we're trying to assing board[r][c] = "Q",
    typerror: str object does not support item assignment
    Does anyone got the same error?

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

    Your videos are really great. May I know what is the significance of using a set.

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

    I tried writing board = [['.']*n]*n, and rest all the exact same code, but it was giving the wrong output, why?

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

    Amazing explaination

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

    The Big O time complexity of his solution is 2^(n*n) I guess because let's take 4 as n. We have 2^n options for the first row which is 2^4 = 16. Then for every option we multiple times 2^4 for the second row and so on. That means we would have 2^n^n which is 2^(n*n).

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

    i have a doubt..why do we have to do a clean up after calling the first backtrack function(why do we need to remove all the cols and set the board[r][c] again to "."?

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

      this is because we need to check if any other ways of placing the Queen exists. So the sets would be used to keep track of only one Queen before the current row

  • @puckwang6850
    @puckwang6850 2 месяца назад

    The posDiag and negDiag solution is amazing!

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

    You made this problem so easy :)

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

      Glad it helped!

  • @sahilchoudhary1473
    @sahilchoudhary1473 9 месяцев назад

    You are the best neet code

  • @fredtrentini6791
    @fredtrentini6791 8 месяцев назад

    It's insane to me how leetcode hard problems have such peculiar domain-specific techniques.
    I just solved that problem but I had no idea about the posDiag / negDiag pattern and I don't think I would figure it out on my own either, what I did instead was using a cached function that returns a single set with all the "forbidden" (i, j) positions, which led me to a ~3000ms solution rather than a ~60ms solution (good enough I guess but definitely not ideal).

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

    What is the time and space complexity of the above solution ?

  • @imtsrk04
    @imtsrk04 Месяц назад

    GOAT for a Reason!!!

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

    I see why we have to keep track of the column, posDiag and negDiag for each placement of the queen. Is the fact that queen placement also excludes the row hidden by the fact that we’re recursing over the rows atomically?

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

    Great explanation

  • @manojjain3501
    @manojjain3501 2 года назад +2

    Just one word "Genius". What you know belongs to you what you can let other know that is the Talent. Kudos.

  • @frankl9634
    @frankl9634 2 года назад +2

    Thanks!

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

      Hey Frank - thank you so much, I really appreciate it!! 😊

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

    Why can't we do column - row for positive diagonal? It also gives 0 as constant value.

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

    😱🤯excellent !!

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

    awesome!

  • @AJK-a2j00k4
    @AJK-a2j00k4 2 месяца назад

    what is the time complexity for this?

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

    Another masterpiece video on backtracking. Can you please make a video on Robot Room Cleaner | LEETCODE # 489?

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

    genius solution. how do people have the insight to come up with this in anything less than a whole day

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

    Great video :)(:

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

    nice explanation sir

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

    Finally its here

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

    bro
    thanks a lot

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

    Backtrack is hard for me. I try to learn it by watching your videos