N-Queens - Backtracking - Leetcode 51 - Python

Ғылым және технология

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

Пікірлер: 178

  • @NeetCode
    @NeetCode3 жыл бұрын

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

  • @wookyumkim4669
    @wookyumkim46692 жыл бұрын

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

  • @nameless2850

    @nameless2850

    2 жыл бұрын

    Right? It truly is fascinating

  • @nachiket9857

    @nachiket9857

    11 ай бұрын

    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

    8 ай бұрын

    truly

  • @demaxl732

    @demaxl732

    6 ай бұрын

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

  • @Cld136
    @Cld1363 жыл бұрын

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

  • @harishsn4866
    @harishsn48662 жыл бұрын

    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
    @chaitu20372 жыл бұрын

    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 Жыл бұрын

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

  • @miaowcat1
    @miaowcat1 Жыл бұрын

    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

  • @SameenIslam
    @SameenIslam2 жыл бұрын

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

  • @arjunv1624
    @arjunv16243 жыл бұрын

    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.

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

  • @jadkhalil9263
    @jadkhalil9263 Жыл бұрын

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

  • @umutkavakli
    @umutkavakli Жыл бұрын

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

  • @kwetuligee8087
    @kwetuligee80873 жыл бұрын

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

  • @rajrsa
    @rajrsa Жыл бұрын

    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
    @salehsaeed57342 жыл бұрын

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

  • @NeetCode

    @NeetCode

    2 жыл бұрын

    Thanks, happy it was helpful! 😃

  • @CostaKazistov

    @CostaKazistov

    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
    @symbol7672 жыл бұрын

    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

  • @airatvaliullin8420
    @airatvaliullin84202 жыл бұрын

    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.

  • @onlinealias622
    @onlinealias6225 ай бұрын

    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

  • @VysePresidentGeo
    @VysePresidentGeo8 ай бұрын

    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!

  • @Adarsh-mn7pl
    @Adarsh-mn7pl2 жыл бұрын

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

  • @user-lx1fc6ii9o
    @user-lx1fc6ii9o11 ай бұрын

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

  • @NamasteSaurav
    @NamasteSaurav8 ай бұрын

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

  • @vinaf4494
    @vinaf44946 ай бұрын

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

  • @carloslazarin
    @carloslazarin Жыл бұрын

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

  • @The6thProgrammer
    @The6thProgrammer8 ай бұрын

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

  • @hyk-f4r
    @hyk-f4r2 жыл бұрын

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

  • @ivantishchenko4686
    @ivantishchenko46862 жыл бұрын

    Superb explanation as usual. Calm and thought out.

  • @parthsalat
    @parthsalatАй бұрын

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

  • @ilanaizelman3993
    @ilanaizelman39932 жыл бұрын

    Best explanation I have seen. Thanks!!!

  • @vatsalsharma5791
    @vatsalsharma57913 жыл бұрын

    Much needed ❤️

  • @nuamaaniqbal6373
    @nuamaaniqbal63732 жыл бұрын

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

  • @summaiyaparveen8730
    @summaiyaparveen87302 жыл бұрын

    Thank You So Much for this amazing Explanation!!

  • @kunafeh
    @kunafeh2 жыл бұрын

    Thanks for this amazing explanation. Loved it! 😍

  • @eshwarprasad2541
    @eshwarprasad25412 жыл бұрын

    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.

  • @tanayasharma7776
    @tanayasharma7776 Жыл бұрын

    this is the best explanation i've found so far

  • @krisrocker437
    @krisrocker4372 жыл бұрын

    Great explanation!!! Keep it up, neetcode!

  • @karankanojiya7672
    @karankanojiya76722 жыл бұрын

    OMG that diagonal intuition 🤐 Respect ++ Sir!

  • @NeetCode

    @NeetCode

    2 жыл бұрын

    Thanks! :)

  • @amrutaparab4939
    @amrutaparab49393 ай бұрын

    You are a blessing to this world!

  • @rishabhnitc
    @rishabhnitc2 жыл бұрын

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

  • @winstonkoh672
    @winstonkoh6722 жыл бұрын

    Hi NeetCode, thank you for the amazing explanation

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

  • @LeeK301
    @LeeK3017 ай бұрын

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

  • @spy9740
    @spy97403 жыл бұрын

    Thanks for the content bro

  • @nderimbunjaku
    @nderimbunjaku2 жыл бұрын

    Great explanation, thank you very much!

  • @pythonbrothersandfamily
    @pythonbrothersandfamily6 ай бұрын

    wow, you nailed it. Thanks a lot

  • @sagarchawla4926
    @sagarchawla4926 Жыл бұрын

    Your explanations are amazing.

  • @yassineacherkouk
    @yassineacherkouk8 ай бұрын

    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.

  • @tnmyk_
    @tnmyk_4 ай бұрын

    Excellent explanation!

  • @chliang3499
    @chliang3499 Жыл бұрын

    pretty genius way to detect collision of diagonal!!

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

  • @lesterdelacruz5088
    @lesterdelacruz50883 ай бұрын

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

  • @allenmu8021
    @allenmu8021 Жыл бұрын

    Great video!

  • @yinglll7411
    @yinglll74112 жыл бұрын

    Thank you so much again!

  • @tarangnima4641
    @tarangnima46412 ай бұрын

    Amazing Explanation..💥

  • @sudeepdalai
    @sudeepdalai2 жыл бұрын

    This solution is elegant and ingenious. 🤩🤩

  • @sushilkhadka8207
    @sushilkhadka82072 жыл бұрын

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

  • @clara8490
    @clara84903 жыл бұрын

    Simply the best :)

  • @zappist751
    @zappist751 Жыл бұрын

    Best explanation yet!

  • @supervince110
    @supervince1102 жыл бұрын

    Such an elegant solution!

  • @Cloud-577
    @Cloud-5772 жыл бұрын

    thank you this was very helpful

  • @santhosh20071993
    @santhosh200719932 жыл бұрын

    You Just Nailed the Power of Python.

  • @DanielTruongDev
    @DanielTruongDev2 жыл бұрын

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

  • @robyc9545
    @robyc9545 Жыл бұрын

    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?

  • @Hiroki-Takahashi
    @Hiroki-Takahashi4 ай бұрын

    This is art

  • @UnfinishedYara
    @UnfinishedYara2 жыл бұрын

    thank you so much youre a hero!

  • @nhrtsa9010

    @nhrtsa9010

    2 жыл бұрын

    No!!! he's a super hero !

  • @AbyssiniaBenchmark
    @AbyssiniaBenchmark9 ай бұрын

    Man you are awsome. Really awesome.

  • @knightye
    @knightye2 жыл бұрын

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

  • @Avinashkk360
    @Avinashkk3603 жыл бұрын

    Just brilliant :)

  • @Eddie-um6cw
    @Eddie-um6cw2 жыл бұрын

    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?

  • @orangethemeow
    @orangethemeow2 жыл бұрын

    You made this problem so easy :)

  • @NeetCode

    @NeetCode

    2 жыл бұрын

    Glad it helped!

  • @surajslab984
    @surajslab9842 жыл бұрын

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

  • @puckwang6850
    @puckwang68502 ай бұрын

    The posDiag and negDiag solution is amazing!

  • @sahilchoudhary1473
    @sahilchoudhary14739 ай бұрын

    You are the best neet code

  • @imtsrk04
    @imtsrk04Ай бұрын

    GOAT for a Reason!!!

  • @thanirmalainagappan9472
    @thanirmalainagappan9472 Жыл бұрын

    Amazing explaination

  • @saswatmishra4055
    @saswatmishra4055 Жыл бұрын

    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

  • @ameynaik2743
    @ameynaik27433 жыл бұрын

    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

  • @frankl9634
    @frankl96342 жыл бұрын

    Thanks!

  • @NeetCode

    @NeetCode

    2 жыл бұрын

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

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

  • @fredtrentini6791
    @fredtrentini67918 ай бұрын

    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 ?

  • @shrimpo6416
    @shrimpo64162 жыл бұрын

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

  • @tanmeshnm
    @tanmeshnm3 жыл бұрын

    😱🤯excellent !!

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

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

  • @jonaskhanwald566
    @jonaskhanwald5663 жыл бұрын

    Finally its here

  • @ValhaVaiyagam
    @ValhaVaiyagam17 күн бұрын

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

  • @mapo5959
    @mapo59592 жыл бұрын

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

  • @MohitJayee
    @MohitJayee2 жыл бұрын

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

  • @yoman9446
    @yoman94463 жыл бұрын

    awesome!

  • @manojjain3501
    @manojjain35012 жыл бұрын

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

  • @rohanchess8332
    @rohanchess8332 Жыл бұрын

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

  • @AJK-a2j00k4
    @AJK-a2j00k42 ай бұрын

    what is the time complexity for this?

  • @manubachhal404
    @manubachhal4043 жыл бұрын

    Now ,i understood why channel name is Neetcode.

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

  • @greatred2558
    @greatred25582 жыл бұрын

    bro thanks a lot

  • @ravishraj664
    @ravishraj6642 жыл бұрын

    Great video :)(:

  • @yajat4763
    @yajat47632 жыл бұрын

    My mind is blown

  • @EranM
    @EranM2 ай бұрын

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

Келесі