Valid Sudoku - Amazon Interview Question - Leetcode 36 - Python

Sdílet
Vložit
  • čas přidán 2. 07. 2024
  • 🚀 neetcode.io/ - A better way to prepare for Coding Interviews
    🐦 Twitter: / neetcode1
    🥷 Discord: / discord
    🐮 Support the channel: / neetcode
    ⭐ 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 - ...
    💡 BINARY SEARCH PLAYLIST: • Binary Search
    Problem Link: neetcode.io/problems/valid-su...
    0:00 - Read the problem
    4:49 - Drawing Explanation
    8:50 - Coding Explanation
    leetcode 36
    This question was identified as an amazon interview question from here: github.com/xizhengszhang/Leet...
    #valid #sudoku #python
    Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.
  • Věda a technologie

Komentáře • 218

  • @NeetCode
    @NeetCode  Před 2 lety +49

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

  • @ashtag4043
    @ashtag4043 Před rokem +213

    Bro I'm literally in awe when you used simple division of indices with 3 to point to a particular square. Amazing as always.

    • @Flite999
      @Flite999 Před rokem +18

      Agreed that is an elegant solution - what I have trouble with is getting to that kind of approach on my own!

    • @Cruzylife
      @Cruzylife Před rokem +24

      @@Flite999 you dont, you pick up patterns and practice similar problems.

    • @pinakadhara7650
      @pinakadhara7650 Před rokem +2

      ​@@Flite999 Apart from practice, getting good in maths.

    • @henryfeng6300
      @henryfeng6300 Před rokem +1

      I used "Math.floor(r/ 3) * 3 + Math.floor(c / 3)" to get the index of sub-box

    • @rohitchand3853
      @rohitchand3853 Před rokem +4

      Sigma solution🤕

  • @jesuscruz8008
    @jesuscruz8008 Před rokem +48

    the row/3 and colum/3 idea is sooo neat i love it. I was having trouble iterating thru each of the squares. Im doing the NeetCode 150 on your website and I love that you have videos for each of the problems even if i get the right solution i look at your videos to see the alternative ways to solve it.

    • @servantofthelord8147
      @servantofthelord8147 Před 10 měsíci +11

      You mean, it's so "neet" ;)

    • @dhavallimdiwala
      @dhavallimdiwala Před 8 měsíci

      Additionally, we can convert into single number key instead of pair as a key. after doing devision by 3, we do 3*x+y. where x and y are indices from [0..2,0..2].

  • @mehdiezatabadi
    @mehdiezatabadi Před 2 lety +35

    This guy is more than just a legend :) He is THE legend!

  • @parthvalani3273
    @parthvalani3273 Před 2 lety +53

    I haven't seen that much easy explanation of all the code you explained. It helps me to improve my overall logical skills. Thanks Bud!!

  • @Hys-01
    @Hys-01 Před 3 měsíci +4

    this is the first medium problem that ive done myself which aligns exactly with the optimal solution, i feel accomplished 😅

  • @sayaksengupta4335
    @sayaksengupta4335 Před rokem +21

    This solution is simply beautiful. You have my respect, Neetcode.

  • @choiiohc1
    @choiiohc1 Před rokem +18

    I never thought in this question that tuple (r//3, c//3) could be keys for defaultdict. Amazing!

    • @rishabhsetty3109
      @rishabhsetty3109 Před rokem +1

      keys for a dictionary have to be immutable so tuples work

    • @pahehepaa4182
      @pahehepaa4182 Před rokem

      Same man. 2 years as a python developer still this popped

  • @MP-ny3ep
    @MP-ny3ep Před 2 lety +15

    This is the best channel in the whole of CZcams🔥

  • @AkshithaKukudala
    @AkshithaKukudala Před rokem +15

    Omg!!!!! What an explanation. I literally spend an entire day trying this problem and you explained me clearly within these few minutes. You are the best teacher!!!!!

  • @chaitanyasharma6270
    @chaitanyasharma6270 Před 2 lety +2

    the best way to do this really, i had been struggling with this problem for a few days now, the sudoku solver really, i did the more complex way at first but i was worried that i would not be able to think of that solution in a coding test but this way is beautiful

  • @syafzal273
    @syafzal273 Před 6 měsíci

    The implementation for the squares with floor division and using a tuple as the key is simply amazing!

  • @dnguyendev
    @dnguyendev Před 2 lety +9

    The way you explain this problem is brilliant man! So glad I found your channel

  • @ChanChan-pg4wu
    @ChanChan-pg4wu Před 2 lety +2

    excellent explanation! Thank you Neetcode!

  • @ramsesD925
    @ramsesD925 Před rokem

    Mind blown when you said you recorded on 4th of July!! It's been exactly one year! Thanks for everything you do

  • @tiennguyenthuy7563
    @tiennguyenthuy7563 Před 2 lety +1

    Brilliant answers and explanations. Thank you very much

  • @zainrab8629
    @zainrab8629 Před rokem +2

    Amazing explanation with some really easy and clean code!

  • @rahulsbhatt
    @rahulsbhatt Před rokem

    Your way of explaining things and implementation is neet.
    Thanks for posting this!

  • @Wanderor1
    @Wanderor1 Před 2 lety +1

    Amazing! Simply Amazing! Going to join your channel to help support the channel. Keep the videos coming.!

  • @varunajmera
    @varunajmera Před 2 lety +2

    very well explained and very easy and intuitive

  • @theartvillebyjessica
    @theartvillebyjessica Před 2 lety +1

    Amazing explanation. Thank you for the wonderful videos.

  • @gianniprocida3332
    @gianniprocida3332 Před 2 lety

    Excellent explanation for every problem.

  • @vamseekotha
    @vamseekotha Před 11 měsíci

    Wow. This is an excellent solution. I used a list of lists to iterate through the grids. But, this is an amazing solution man. Keep up the great work.

  • @hunterzhang9489
    @hunterzhang9489 Před rokem +1

    This is the definition of NEAT CODE

  • @EagerEggplant
    @EagerEggplant Před 2 lety

    Sets in side of hashes with with the row/column as the key... that's pretty awesome!

  • @Moch117
    @Moch117 Před 11 měsíci

    Thanks bro I had the right idea but didn't know how to implement detecting what box we are in. Row/3 and column/3 helped a lot

  • @user-wt2jd2qc3m
    @user-wt2jd2qc3m Před 6 měsíci

    I came to almost the same solution! Instead of using hash maps for the rows, columns, squares, I just initialized them as arrays of size 9 with a set at each position. Using defaultdict(set) is definitely a neat way to make the row, columns, squares sets.

  • @fahimahyder2394
    @fahimahyder2394 Před 2 lety

    Beautifully done

  • @ThanhPhan-it5gm
    @ThanhPhan-it5gm Před 2 měsíci

    thanks a lot. What you've done is truly delightful

  • @c0dertang
    @c0dertang Před 2 lety +2

    I hard coded the squares XD. This really opened my eyes. Thanks!

  • @gottuparthiharichandana3381

    You are awesome!
    The code very neat and understandable!!
    Thanks alot

  • @aakashgyl
    @aakashgyl Před 6 měsíci

    It couldn't have been more easier than this. I tried thinking whole day for the best way to solve it. But your solution is too simple yet very powerful.
    Thanks for the amazing content.

  • @Cocamo1337
    @Cocamo1337 Před rokem

    Thank you! Just used this method to solve the problem in C#

  • @gurudatt-shahane
    @gurudatt-shahane Před rokem

    Thanks for making this video. It's a simple and intuitive explanation 🙏

  • @ruicheng1241
    @ruicheng1241 Před 2 lety

    Thanks So Much For Explanation!

  • @ngndnd
    @ngndnd Před 6 měsíci

    the java solution you provided in the website actually intimidated me from trying this problem but it was so simple... i think your java solution made it more complicated than it needed to be

  • @gogolaygo1903
    @gogolaygo1903 Před 5 měsíci

    Idk how i'd ever figure this one out without watching a video. As always, thanks!

  • @the_hasnat
    @the_hasnat Před 9 měsíci

    such an elegant solution. makes it so easy!

  • @akagamishanks7991
    @akagamishanks7991 Před 9 měsíci +1

    Naaaaaahhh I'm here to say it NeetCode is all time top 1 teacher when it comes to explaining and solving algorithm and data structure problems. My guy is HIM!!!

  • @Myshio
    @Myshio Před 9 měsíci +1

    I did it exactly the same way but I opted for just using 1 hashmap where the key was the number and the value was a tuple of (row, column, box number), then at every value I can just look up if it exists in the hashmap and compare each value in the tuple. I can't tell which solution would be better in terms of time complexity though since I would have to iterate all 3 values of my tuple after the constant lookup.

  • @georgeli6820
    @georgeli6820 Před 2 lety

    great explanation brother!

  • @hamzaehsankhan
    @hamzaehsankhan Před 11 měsíci +3

    This makes my solution look like a crayon drawing of a 2-year-old. Awesome solution and well explained.

  • @AlexanderKharitonov-cc1ei

    Wonderful explanation! Could you please do 229 Majority Element 2? I am interested in algorithm with O(n) time complexity and O(1) space.

  • @aboronilov
    @aboronilov Před 2 lety +2

    Bro you are awesome. I hope you have a huge salary and you are working on some top IT company!

  • @Cruzylife
    @Cruzylife Před rokem +1

    preparing for doordash technical rounds, thanks neet

  • @uberwebd9824
    @uberwebd9824 Před 2 lety

    very clean and pythonic code

  • @wildinsights5033
    @wildinsights5033 Před rokem

    subscribed and liked, thank you for sharing your knowledge

  • @davidbuderim2395
    @davidbuderim2395 Před 11 měsíci

    Thanks - most helpful

  • @m_elhosseiny
    @m_elhosseiny Před rokem

    awesome as usual! :)

  • @symbol767
    @symbol767 Před 2 lety

    Thanks man, liked

  • @lizgarcia4626
    @lizgarcia4626 Před 8 měsíci

    This is incredible

  • @shantipriya370
    @shantipriya370 Před 2 měsíci

    simple neat and amazing

  • @MrjavoiThe
    @MrjavoiThe Před rokem

    I did a 11 separated for loops solution in Swift, but still get beats 90% in time complexity and 60% in Space complexity.

  • @codingtriangle
    @codingtriangle Před rokem

    Thanks sir...before watching your solution when i solved this question my time complexity was like O(9^4) ....

  • @MrShihab100
    @MrShihab100 Před 4 dny

    Thanks a lot for your videos :)

  • @GoziePO
    @GoziePO Před rokem +1

    Funny you recorded this on the 4th of July.! I'm watching it on the 4th of July 2023

  • @dataman4503
    @dataman4503 Před 2 lety +4

    It's actually much easier to call them 3 - NxN matrices instead of 3 hash sets each of size NxN.

  • @serhiiDev
    @serhiiDev Před 7 měsíci +1

    Actually, time complexity will be O(1). because O(n^2) in our case is O(81) which is equal to O(1) as it's not depend on size of array.

  • @piyushpawar4815
    @piyushpawar4815 Před rokem

    You are awesome!!

  • @slava_xd
    @slava_xd Před 5 měsíci

    I did by using a normal vector
    for each row I created an adittional 1x9 vector
    same for each column
    then I sorted and used std::unique to check for valid rows and columns. Had to use a custom lambda to ignore the "."
    then for each 3x3 square I created a std::vector sorted each row and used std::unique again.
    But each the unordered_set approach is better

  • @lifeanddatingadvice1711
    @lifeanddatingadvice1711 Před 3 lety +1

    Do sudoku solver next!

  • @mingzhejan3906
    @mingzhejan3906 Před rokem

    Thank you from Taiwan

  • @Fauna.Fantastica
    @Fauna.Fantastica Před 6 měsíci

    you are the goat

  • @brindhadhinakaran9672

    Thanks !!!

  • @sanooosai
    @sanooosai Před 7 měsíci

    thank you sir

  • @ljason6361
    @ljason6361 Před 9 měsíci

    great solution

  • @arjunprasad1071
    @arjunprasad1071 Před rokem +8

    Thanks for the explanation, it was superb✔👌 I am sharing the C++ code for the same implementation below 👇:
    class Solution
    {
    public:
    bool isValidSudoku(vector&board)
    {
    int rowCheck[9][9] = {0}; //for checking rows
    int colCheck[9][9] = {0}; //for checking columns
    int subMatrix[3][3][9] = {0}; //for checking sub matrices/boxes
    for(int i=0;i

  • @diwasmainali1
    @diwasmainali1 Před 6 měsíci

    Genius solution

  • @servantofthelord8147
    @servantofthelord8147 Před 10 měsíci

    Thank you, sir :)

  • @servantofthelord8147
    @servantofthelord8147 Před měsícem

    This was a fun problem!

  • @_dion_
    @_dion_ Před 5 měsíci +1

    this problem should have been in the hard category instead of medium. but u explained it really well as always. thanks.

  • @aboutvenice
    @aboutvenice Před 11 měsíci

    You are good!

  • @rahuljain281
    @rahuljain281 Před 2 lety +2

    Please make a video for leetcode 37 Sudoku Solver... Big Fan❤️

  • @heyasobi
    @heyasobi Před 3 lety +1

    Can you do LC 1048 Longest String Chain? Watched a few other vids but can't quite wrap my head around it.

  • @SurfsUpSeth
    @SurfsUpSeth Před 11 měsíci

    Surprisingly did this first try, may not have been the best solution but I'm happy I atleast got to A solution lol. I did modulo to figure out when every three in a row and every three rows was. Then I stored values based on the row and subsection in a map with frequency values. Probably didn't need the frequency and could have just set a value now that I'm thinking about it but got to a solution lol.

  • @MK-xl5yo
    @MK-xl5yo Před rokem +1

    under loop if you just set temp variable
    cell = board[r][c]
    and could use everywhere in conditions and assignments just cell instead of board[r][c] to keep code more clean and less dupes
    ```
    for r in range(9):
    for c in range(9):
    cell = board[r][c]
    if cell == '.':
    continue
    if (cell in rows[r] or
    cell in cols[c] or
    cell in squares[(r//3, c//3)]):
    return False
    cols[c].add(cell)
    rows[r].add(cell)
    squares[(r//3, c//3)].add(cell)
    ```

  • @lancetv4826
    @lancetv4826 Před měsícem

    I'm not an expert at Big 0 notation, but according to chatGPT `* - The time complexity is O(1). Although we perform nested iterations over the 9x9 board (total 81 cells), this number is constant and independent of the input size.`
    Kindly correct me if I'm wrong @NeetCode

  • @amynguy
    @amynguy Před 5 měsíci

    can use a single hash map and append the identity [Row/Col/SubBox]

  • @mohammadsaudkhan8186
    @mohammadsaudkhan8186 Před měsícem

    That's why he's the goat.......THE GOAT!!!

  • @jonaskhanwald566
    @jonaskhanwald566 Před 3 lety +1

    Please do more Linked list problems

  • @ThamaraiselvamT
    @ThamaraiselvamT Před 2 lety +4

    What the hell, Initially i thought it is a very tough problem to solve. After your explanation it was a cakewalk.
    you are very good at this. 👏 and thanks for your videos.

  • @naimeimran3247
    @naimeimran3247 Před 2 lety

    Thanks,

  • @alittlecoding
    @alittlecoding Před 2 lety

    awesome

  • @hwang1607
    @hwang1607 Před 9 měsíci

    the (row, col):set() default dictionary is insane

  • @kokob5715
    @kokob5715 Před 2 lety

    How do you get yourself to approach a given problem this way?

  • @robr4501
    @robr4501 Před 2 lety

    holy shit, this question become so easy!!!! genius

  • @user-fb4iv4me6g
    @user-fb4iv4me6g Před 8 měsíci

    The operations of a HashSet are not O(1), they are O(n). A HashMap has a bound of O(1)

  • @Kitsune_Dev
    @Kitsune_Dev Před 2 měsíci

    It would have probably been a bit easier to understand if you explained the grid position as Blocks in a Chunk, since Minecraft is pretty popular I think it'd be easy for us to relate

  • @indhumathi5846
    @indhumathi5846 Před rokem

    understood

  • @148nihalmorshed2
    @148nihalmorshed2 Před 8 měsíci

    Can you please explain the defaultdict part , adn and also how is the rows column and squares are stored inside the dictionary? It's really confusing!

  • @josephjoestar4318
    @josephjoestar4318 Před 8 měsíci

    You can use a single Set with each number prefixed by {column | row | box}{0...9}{value} ie: 'c08'.
    If you think this is or is not as good as neetcodes 3 by 9 sets, explain to me why.
    Thanks.

    • @gmoney_swag1274
      @gmoney_swag1274 Před 8 měsíci +1

      Its not as good as its much less readable - which is important in coding interviews as on of the things they test is your ability to write clean, maintainable code

  • @ritwik121
    @ritwik121 Před 2 lety

    @neetcode ... how to come up with own testcases ?

  • @harishdukkipati8921
    @harishdukkipati8921 Před rokem

    The problem mentions that each row, square, and column need to have a digit between 1-9. From the code u have written it returns false if there is any duplicates in the row, square, or column but where exactly does it check that each row, square, and column have a digit from 1-9.

    • @NeetCode
      @NeetCode  Před rokem

      We know that the only values are between 1 and 9. So if there are no duplicates, what other possible value could be there? It's basically pidgen hole principle.

    • @harishdukkipati8921
      @harishdukkipati8921 Před rokem

      @@NeetCode I forgot only the filled cells need to be validated. I thought the problem required u to make sure there isn't any empty row, column, or square. Thanks for the explanation

  • @c0dertang
    @c0dertang Před 2 lety +1

    hey it's technically O(1)! thats cool

  • @cortisol_induced_coma
    @cortisol_induced_coma Před 7 měsíci

    Holy shit, I had to use two variables to keep track of the column and rows, then used board[y][(index % 3) + (x % 9)] to advance through the sub-blocks. The simple division by 3 is genius.

  • @sammyapsel1443
    @sammyapsel1443 Před 5 měsíci

    can you explain the initialilzations of the sets?
    can't i just initialize them with : rows= {} ?

  • @bpsupergirl
    @bpsupergirl Před 2 lety +2

    I have an interview in 3 weeks and...how the hell am I supposed to figure this out 😂

  • @bonle3771
    @bonle3771 Před 4 měsíci

    what does it mean by only filled cells need to be validated?

  • @amansaxena4446
    @amansaxena4446 Před rokem

    how much time it took to get good level grasp on DSA? when u were able to solve quesitons in half hour

  • @muskanmall4401
    @muskanmall4401 Před 4 měsíci

    if I just used deaultdict(list) or something, would that be wrong?