N-Queens - Backtracking - Leetcode 51 - Python

Поділитися
Вставка
  • Опубліковано 29 лис 2024

КОМЕНТАРІ • 213

  • @NeetCode
    @NeetCode  3 роки тому +27

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

  • @wookyumkim4669
    @wookyumkim4669 3 роки тому +196

    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 Рік тому

      @@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 Рік тому +1

      truly

    • @demaxl732
      @demaxl732 10 місяців тому +1

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

  • @Cld136
    @Cld136 3 роки тому +106

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

  • @harishsn4866
    @harishsn4866 2 роки тому +16

    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.

  • @salehsaeed5734
    @salehsaeed5734 3 роки тому +13

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

    • @NeetCode
      @NeetCode  3 роки тому +7

      Thanks, happy it was helpful! 😃

    • @CostaKazistov
      @CostaKazistov 2 роки тому +5

      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.

  • @arjunv1624
    @arjunv1624 3 роки тому +22

    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.

  • @rajrsa
    @rajrsa Рік тому +6

    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)

  • @chaitu2037
    @chaitu2037 2 роки тому +9

    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.

  • @jadkhalil9263
    @jadkhalil9263 2 роки тому +7

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

  • @umutkavakli
    @umutkavakli Рік тому +2

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

  • @karankanojiya7672
    @karankanojiya7672 3 роки тому +9

    OMG that diagonal intuition 🤐
    Respect ++ Sir!

  • @alibagheri
    @alibagheri 2 місяці тому +4

    Can't believe I solved this on my own (after 1.5 hours of thinking)!

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

  • @SameenIslam
    @SameenIslam 2 роки тому +2

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

  • @kwetuligee8087
    @kwetuligee8087 3 роки тому +3

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

  • @slygg
    @slygg 3 місяці тому

    Altough it's an understandable reflex to use a 2d-array to represent this chess board, since a normal chess board is a matrix, in this case that's subobtimal. Since the problem definition is so that you can have only one queen/row anyways you can just get away with a regular array. When you do this checking for conflicts also becomes less computationally expensive since you can just do this: Let b equal chessBoard, if b[row] == b[i] || abs(b[i] - b[j]) == abs(i - j)), conflict found. This probably doesn't matter for small n but once n gets moderately large every little bit starts to add up, especially if your method is time complexity O(n!) as in the video here.

  • @Adarsh-mn7pl
    @Adarsh-mn7pl 2 роки тому

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

  • @parthsalat
    @parthsalat 5 місяців тому +1

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

  • @NamasteSaurav
    @NamasteSaurav Рік тому

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

  • @onlinealias622
    @onlinealias622 9 місяців тому

    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

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

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

  • @lesterdelacruz5088
    @lesterdelacruz5088 7 місяців тому

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

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

  • @WBPCS
    @WBPCS Рік тому +1

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

  • @manojjain3501
    @manojjain3501 3 роки тому +2

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

  • @Lan-so5gv
    @Lan-so5gv 2 роки тому +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.

  • @VysePresidentGeo
    @VysePresidentGeo Рік тому +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!

  • @robyc9545
    @robyc9545 2 роки тому +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?

  • @LeeK301
    @LeeK301 11 місяців тому

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

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

  • @carloslazarin
    @carloslazarin Рік тому

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

  • @vinaf4494
    @vinaf4494 10 місяців тому

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

  • @ivantishchenko4686
    @ivantishchenko4686 2 роки тому +2

    Superb explanation as usual. Calm and thought out.

  • @yassineacherkouk
    @yassineacherkouk Рік тому

    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.

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

  • @The6thProgrammer
    @The6thProgrammer Рік тому

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

  • @leonscander1431
    @leonscander1431 3 місяці тому

    Damn, the difficulty is in this diagonal trick, the backtracking itself is pretty straightforward.

  • @tanayasharma7776
    @tanayasharma7776 2 роки тому

    this is the best explanation i've found so far

  • @nuamaaniqbal6373
    @nuamaaniqbal6373 2 роки тому

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

  • @DeGoya
    @DeGoya 2 роки тому

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

  • @amrutaparab4939
    @amrutaparab4939 8 місяців тому

    You are a blessing to this world!

  • @chliang3499
    @chliang3499 Рік тому

    pretty genius way to detect collision of diagonal!!

  • @fredtrentini6791
    @fredtrentini6791 Рік тому

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

  • @EranM
    @EranM 6 місяців тому

    wow. simply fkn wow with the pos diag neg diag.. such a nice pattern to this.. holy moly. neet! 1337!!

  • @puckwang6850
    @puckwang6850 6 місяців тому

    The posDiag and negDiag solution is amazing!

  • @santhosh20071993
    @santhosh20071993 2 роки тому

    You Just Nailed the Power of Python.

  • @mostinho7
    @mostinho7 Рік тому +1

    Thanks
    TODO:-
    Take notes
    Backtracking the positions of the queens, but since queens can move horizontally vertically and diagonally, we can’t put two queens together in the same row (because they move horizontally so would attack each other) and also can’t put them in same column or diagonal. So when backtracking, we place queen in a position in row and make recursive call to place the other in next row and keep track of:
    Column that queen was placed in
    Both diagonals of the queen (YES there are TWO diagonals that the queen can move in, positive slope and negative slope, so need to keep track of both)

  • @ilanaizelman3993
    @ilanaizelman3993 3 роки тому +2

    Best explanation I have seen. Thanks!!!

  • @thisisankitgaur
    @thisisankitgaur 3 роки тому +1

    What do you eat man? Seriously, you make Backtracking problems look like a joke. Thanks for the solution!!

  • @knightye
    @knightye 3 роки тому

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

  • @sudeepdalai
    @sudeepdalai 2 роки тому

    This solution is elegant and ingenious. 🤩🤩

  • @palakjain2505
    @palakjain2505 Місяць тому

    you are amazing! thank god this video exists! I am confused what the time complexity of this approach would be??

  • @yinglll7411
    @yinglll7411 2 роки тому +1

    For people wondering what's the time complexity for this solution, I guess its O(n*2) because we are essentially taking a brute force approach, trying out all combinations of rows and columns implies (n*n). Please correct me if i'm wrong😇

    • @veliea5160
      @veliea5160 2 роки тому +12

      to me seems like O(N!). because first we have n options, in the second row we have (n-1) options and then (n-2) and so on

    • @Lan-so5gv
      @Lan-so5gv 2 роки тому +1

      @@veliea5160don'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

  • @piglovesasy
    @piglovesasy 3 місяці тому

    I like this approach!

  • @zahraBatenin
    @zahraBatenin 5 днів тому

    The explanation was great! thanks

  • @rishabhnitc
    @rishabhnitc 2 роки тому

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

  • @illu1na
    @illu1na Рік тому

    Please always include time and space complexity for all solutions. My understanding is that interviewer always ask for time and space complexity in pretty much all interviews.
    Time O(N^N), Space O(N^2). I struggle with tighter time complexity for backtracking problems. If we can ignore previously visited locations from the search then it can actually be O(N!)?

  • @ameynaik2743
    @ameynaik2743 3 роки тому +12

    What is the time complexity of this solution?

    • @Lan-so5gv
      @Lan-so5gv 2 роки тому

      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

  • @Method5440
    @Method5440 2 роки тому

    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?

  • @vatsalsharma5791
    @vatsalsharma5791 3 роки тому +2

    Much needed ❤️

  • @kunafeh
    @kunafeh 2 роки тому

    Thanks for this amazing explanation. Loved it! 😍

  • @summaiyaparveen8730
    @summaiyaparveen8730 2 роки тому

    Thank You So Much for this amazing Explanation!!

  • @sagarchawla4926
    @sagarchawla4926 Рік тому

    Your explanations are amazing.

  • @karandhinakaran1420
    @karandhinakaran1420 2 роки тому

    Great Explanation! Keep up the good work! Just an observation that if we use list instead of set, the code is faster by 6ms and saves about 0.1MB of space.

  • @pythonfamily
    @pythonfamily 11 місяців тому

    wow, you nailed it. Thanks a lot

  • @jz77096
    @jz77096 3 місяці тому

    Man, you gotta realize the diagonal trick. And then the n-tree instead of the 'true brute force'. BTW - true brute force was so hard to code. I ditched it and came here.

  • @frankl9634
    @frankl9634 3 роки тому +3

    Thanks!

    • @NeetCode
      @NeetCode  3 роки тому +1

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

  • @mapo5959
    @mapo5959 2 роки тому

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

  • @winstonkoh672
    @winstonkoh672 2 роки тому

    Hi NeetCode, thank you for the amazing explanation

  • @shrimpo6416
    @shrimpo6416 2 роки тому

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

  • @krisrocker437
    @krisrocker437 3 роки тому

    Great explanation!!! Keep it up, neetcode!

  • @shoooozzzz
    @shoooozzzz 2 роки тому +3

    if you ask this question in an interview, you are what is wrong with the hiring process

  • @imtsrk04
    @imtsrk04 5 місяців тому

    GOAT for a Reason!!!

  • @supervince110
    @supervince110 2 роки тому

    Such an elegant solution!

  • @nderimbunjaku
    @nderimbunjaku 2 роки тому

    Great explanation, thank you very much!

  • @sushilkhadka8207
    @sushilkhadka8207 2 роки тому

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

  • @sahilchoudhary1473
    @sahilchoudhary1473 Рік тому

    You are the best neet code

  • @parthsalat
    @parthsalat 5 місяців тому +1

    This ain't brute force, in brute force sol, you'd ITERATE and check if a queen is already placed at an attacking position

  • @spy9740
    @spy9740 3 роки тому +1

    Thanks for the content bro

  • @tarangnima4641
    @tarangnima4641 6 місяців тому

    Amazing Explanation..💥

  • @orangethemeow
    @orangethemeow 2 роки тому

    You made this problem so easy :)

  • @UnfinishedYara
    @UnfinishedYara 3 роки тому +1

    thank you so much youre a hero!

    • @nhrtsa9010
      @nhrtsa9010 2 роки тому

      No!!! he's a super hero !

  • @zappist751
    @zappist751 2 роки тому

    Best explanation yet!

  • @tnmyk_
    @tnmyk_ 8 місяців тому

    Excellent explanation!

  • @manubachhal404
    @manubachhal404 3 роки тому

    Now ,i understood why channel name is Neetcode.

  • @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 2 роки тому

      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

  • @prafulparashar9849
    @prafulparashar9849 2 роки тому

    Great explanation !!
    One question though,
    Any specific reason to use sets? The solution works with lists as well.
    If anyone have any idea, do let me know.

    • @NeetCode
      @NeetCode  2 роки тому +2

      Mainly because checking if a value exists in a HashSet is O(1) time, but with a list it's O(n).

    • @prafulparashar9849
      @prafulparashar9849 2 роки тому

      @@NeetCode Thanks for clarifying, makes so much sense now to use a set in case of these scenarios.

  • @MohitJayee
    @MohitJayee 2 роки тому

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

  • @samridhshubham8109
    @samridhshubham8109 8 місяців тому

    Me after seeing the problem: This is so hard what todo, how todo
    After seeing the sol: This is the easiest question I've seen in my entire life

  • @AbyssiniaBenchmark
    @AbyssiniaBenchmark Рік тому

    Man you are awsome. Really awesome.

  • @allenmu8021
    @allenmu8021 2 роки тому

    Great video!

  • @yinglll7411
    @yinglll7411 2 роки тому

    Thank you so much again!

  • @SurbhiSingh-t2o
    @SurbhiSingh-t2o 8 місяців тому

    could you please also explain intuition behind TC ?

  • @SANJAYSINGH-jt4hf
    @SANJAYSINGH-jt4hf Рік тому +3

    Java Solution:
    class Solution {
    public List solveNQueens(int n) {
    List res = new ArrayList();
    HashSet col = new HashSet();HashSet pdiag = new HashSet();
    HashSet ndiag = new HashSet();
    char[][] board = new char[n][n];
    for(int i=0;i

  • @kyn7329
    @kyn7329 2 роки тому +4

    This question describes my romantic relationship with my four girlfriends perfectly. It's no surprise that it's hard.

  • @Hiroki-Takahashi
    @Hiroki-Takahashi 8 місяців тому

    This is art

  • @shivigupta6524
    @shivigupta6524 3 місяці тому

    I have a doubt, by your solution, it will consider duplicate chessboard added to your result
    do you consider only unique solution in your appoarch?