Valid Sudoku - Amazon Interview Question - Leetcode 36 - Python

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

КОМЕНТАРІ • 241

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

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

  • @ashtag4043
    @ashtag4043 2 роки тому +280

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

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

    • @Cruzylife
      @Cruzylife 2 роки тому +31

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

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

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

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

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

    • @rohitchand3853
      @rohitchand3853 Рік тому +4

      Sigma solution🤕

  • @Hys-01
    @Hys-01 7 місяців тому +11

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

  • @jesuscruz8008
    @jesuscruz8008 Рік тому +83

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

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

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

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

  • @parthvalani3273
    @parthvalani3273 2 роки тому +63

    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!!

    • @james3677
      @james3677 3 місяці тому +1

      Hey bro, do you got any opportunity in maang companies.? In which company are you working at present. I am asking you this because you have started solving problems 3 years ago.

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

      @@james3677 search up his name on google , I think he works a Deloitte

  • @mehdiezatabadi
    @mehdiezatabadi 2 роки тому +48

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

  • @choiiohc1
    @choiiohc1 2 роки тому +26

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

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

      keys for a dictionary have to be immutable so tuples work

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

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

  • @AkshithaKukudala
    @AkshithaKukudala Рік тому +18

    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!!!!!

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

    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!!!

  • @sayaksengupta4335
    @sayaksengupta4335 Рік тому +26

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

    • @NeetCode
      @NeetCode  Рік тому +4

      Glad it was helpful!

  • @MP-ny3ep
    @MP-ny3ep 3 роки тому +16

    This is the best channel in the whole of UA-cam🔥

  • @AlanWeiler-c6r
    @AlanWeiler-c6r 19 днів тому

    Dude, seriously, this solution was so elegant and brilliant. Thanks, for explaining these things so simply and effectively.

  • @serhiiDev
    @serhiiDev Рік тому +3

    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.

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

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

    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.

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

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

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

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

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

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

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

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

    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

  • @AdityaSingh-nn2cd
    @AdityaSingh-nn2cd 19 днів тому

    I always fell happy when i got stuck on leetcode problem and you have a video uploaded on it.

  • @_dion_
    @_dion_ 10 місяців тому +3

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

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

    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

  • @hamzaehsankhan
    @hamzaehsankhan Рік тому +3

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

  • @gogolaygo1903
    @gogolaygo1903 9 місяців тому +1

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

  • @dataman4503
    @dataman4503 3 роки тому +5

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

  • @arjunprasad1071
    @arjunprasad1071 Рік тому +9

    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

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

    This is the definition of NEAT CODE

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

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

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

    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.

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

    preparing for doordash technical rounds, thanks neet

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

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

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

    Thanks a lot @NeetCode for sharing awesome videos on DSA problems 🔥
    But In this problem it is mentioned that
    - Each row must contain the digits 1-9 without duplicates.
    same for column and squares
    Based on same if some test cases have digits 9 eg 10, -1
    Then seems like the solution suggested in video may get failed. 🤔
    Not sure, if the condition checking for the same omitted intentional for simplicity or I'm missing something here.
    But sharing here, if it helps any future viewers.

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

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

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

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

  • @Dg-qc7qm
    @Dg-qc7qm 2 місяці тому

    If we defined N=9 (and we don't subscribe to the - "it's a defined number so it's constant idea"), you are using N^2 memory here.
    it could be done with N with three loops (only the current row/col/sqr must be saved). it's at least worth mentioning in an interview. it does make it much more elegant though

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

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

  • @MK-xl5yo
    @MK-xl5yo Рік тому +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)
    ```

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

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

  • @eulier1
    @eulier1 2 місяці тому

    Representation in Software Engineer is perhaps the hardest part to get along with. In jobs you definitely don't want to over use it or abstractions.

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

    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

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

    Amazing explanation with some really easy and clean code!

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

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

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

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

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

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

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

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

    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

    • @SuubUWU
      @SuubUWU Місяць тому +2

      It's only because the probelm itself constraints rows and cols to exactly 9. Hence iterating every row and column would be 9^2, which is a constant of 81. If however, the interviewer did a follow up question such as an "unknown rows and cols at runtime"; the solution would then be n^2.

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

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

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

    very well explained and very easy and intuitive

  • @ThanhPhan-it5gm
    @ThanhPhan-it5gm 7 місяців тому

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

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

    Brilliant answers and explanations. Thank you very much

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

    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.

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

    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.

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

    such an elegant solution. makes it so easy!

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

    My man recording Leetcode solutions on Fourth of July for us to pass our interviews. What’s your excuse?

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

    u made it look so easy

  • @user-fb4iv4me6g
    @user-fb4iv4me6g Рік тому

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

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

    Excellent explanation for every problem.

  • @gurudatt-shahane
    @gurudatt-shahane Рік тому

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

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

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

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

      Hey bro, do you got any opportunity in maang companies.? In which company are you working at present. I am asking you this because you have started solving problems 3 years ago.

  • @ChanChan-pg4wu
    @ChanChan-pg4wu 2 роки тому +2

    excellent explanation! Thank you Neetcode!

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

      Hey bro, do you got any opportunity in maang companies.? In which company are you working at present. I am asking you this because you have started solving problems 3 years ago.

  • @AlexanderKharitonov-cc1ei
    @AlexanderKharitonov-cc1ei 3 роки тому +2

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

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

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

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

    Do sudoku solver next!

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

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

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

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

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

      Hey bro, do you got any opportunity in maang companies.? In which company are you working at present. I am asking you this because you have started solving problems 3 years ago.

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

    Thank you from Taiwan

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

    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

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

    Amazing explanation. Thank you for the wonderful videos.

  • @DetectiveConan990v3
    @DetectiveConan990v3 17 днів тому

    this solution is so simple once you see it

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

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

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

    the squares divided by 3 is insanely smart holy shit

  • @michadobrzanski2194
    @michadobrzanski2194 3 роки тому +4

    You can optimize it more in terms of space. No need for global Dictionary for Rows. Simple Set is fine. It will be destoryed/cleared after the whole row pass (after for-loop with 'c').

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

      does it matter? the space complexity doesn't even grow with input size.

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

      what is space complexity of this?

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

    This solution is a night mare in java!

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

    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.

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

    Assigning board[r][c] to a variable and using the variable instead, makes the runtime of the program almost 2x faster.

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

    "Runtime: 95 ms, faster than 96.98% of Python3 online submissions" and I still came here to watch the video and still learnt things. That is just how good these videos are.
    Interestingly, checking in order of all rows, all cols, all squares gives the faster time. The test cases much favour some early exits based on rows.

  • @148nihalmorshed2
    @148nihalmorshed2 Рік тому

    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!

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

    The explanation is very good and can be understood easily but I don't know how to code this approach in C++, if some approaches are not possible to code in other languages, suggest what can be in other languages in your upcoming videos :)

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

      It's up to you to learn your target language well enough to understand how to adapt explanations. If you insist on using C++ (a bold choice) consider using unordered_set for storing values you've seen. the rest is just loops and array indices.

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

      i'm quite late but if it helps anyone, this is what i used for cpp
      unordered_map rows,cols;
      map squares;

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

      @@suhaasbadada Why do you use map for squares? Why not both unordered_map? I thought unordered_map is better

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

      @@tsepten7930 u can't use pair as a key in unordered_map

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

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

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

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

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

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

  • @subhajitnaskar6033
    @subhajitnaskar6033 8 місяців тому +1

    Hi..can anyone give a bit context on the defaultdict(set) part?

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

    Thanks - most helpful

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

    This is incredible

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

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

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

    Please do more Linked list problems

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

    Genius solution

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

    simple neat and amazing

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

    Thanks So Much For Explanation!

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

    subscribed and liked, thank you for sharing your knowledge

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

    Beautifully done

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

    boolean arrays instead of set would be much efficient
    boolean[][] squares = new boolean[9][9];
    squares[i / 3 * 3 + j / 3][c]

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

    As a (currently) intermediate Python programmer, I can't understand the 2nd line (everything to the right of IsValidSudoku.) Is there a particular concept in Python that explains what you're doing there? (I've covered OOP.)
    Thanks, love the channel, aiming to soon be good enough to be able to appreciate everything you do here!

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

      If u know oops in python, you will understand that. Those are just arguments, and that bool is the return type of that method

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

      @jon franklin Ah yes, I've seen it's sometimes called "type hints." Thanks!

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

      ​@@jonfranklin9639 its been a long time but i want to ask a question since you could answer. Why space complexity is O(n^2)? I thought its O(n)

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

      @@talhakaraca It's not n square. It is actually n, which is 9 square (4:30)

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

      @@quanghuyluong1249 thanks

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

    "Each row MUST contain the digits 1-9 without repetition", "Each column MUST contain the digits 1-9 without repetition", so we could argue that it is also necessary to validate if there is a number that is not in the range 1 to 9...

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

      Yes, However in the constraint section, they have clearly mentioned this:
      board[i][j] is a digit 1-9 or '.'.

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

    thank you sir

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

    very clean and pythonic code

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

    This was a fun problem!

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

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

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

    great solution

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

    great explanation brother!