Valid Sudoku - Amazon Interview Question - Leetcode 36 - Python

  Рет қаралды 269,515

NeetCode

NeetCode

Күн бұрын

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

Пікірлер: 218
@NeetCode
@NeetCode 2 жыл бұрын
🚀 neetcode.io/ - I created a FREE site to make interview prep a lot easier, hope it helps! ❤
@ashtag4043
@ashtag4043 Жыл бұрын
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 Жыл бұрын
Agreed that is an elegant solution - what I have trouble with is getting to that kind of approach on my own!
@Cruzylife
@Cruzylife Жыл бұрын
@@Flite999 you dont, you pick up patterns and practice similar problems.
@pinakadhara7650
@pinakadhara7650 Жыл бұрын
​@@Flite999 Apart from practice, getting good in maths.
@henryfeng6300
@henryfeng6300 Жыл бұрын
I used "Math.floor(r/ 3) * 3 + Math.floor(c / 3)" to get the index of sub-box
@rohitchand3853
@rohitchand3853 Жыл бұрын
Sigma solution🤕
@jesuscruz8008
@jesuscruz8008 Жыл бұрын
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 10 ай бұрын
You mean, it's so "neet" ;)
@dhavallimdiwala
@dhavallimdiwala 8 ай бұрын
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 жыл бұрын
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!!
@mehdiezatabadi
@mehdiezatabadi 2 жыл бұрын
This guy is more than just a legend :) He is THE legend!
@chaitanyasharma6270
@chaitanyasharma6270 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
@choiiohc1
@choiiohc1 Жыл бұрын
I never thought in this question that tuple (r//3, c//3) could be keys for defaultdict. Amazing!
@rishabhsetty3109
@rishabhsetty3109 Жыл бұрын
keys for a dictionary have to be immutable so tuples work
@pahehepaa4182
@pahehepaa4182 Жыл бұрын
Same man. 2 years as a python developer still this popped
@MP-ny3ep
@MP-ny3ep 2 жыл бұрын
This is the best channel in the whole of KZbin🔥
@Hys-01
@Hys-01 3 ай бұрын
this is the first medium problem that ive done myself which aligns exactly with the optimal solution, i feel accomplished 😅
@AkshithaKukudala
@AkshithaKukudala Жыл бұрын
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!!!!!
@dnguyendev
@dnguyendev 2 жыл бұрын
The way you explain this problem is brilliant man! So glad I found your channel
@syafzal273
@syafzal273 6 ай бұрын
The implementation for the squares with floor division and using a tuple as the key is simply amazing!
@sayaksengupta4335
@sayaksengupta4335 Жыл бұрын
This solution is simply beautiful. You have my respect, Neetcode.
@NeetCode
@NeetCode Жыл бұрын
Glad it was helpful!
@ramsesD925
@ramsesD925 Жыл бұрын
Mind blown when you said you recorded on 4th of July!! It's been exactly one year! Thanks for everything you do
@ChanChan-pg4wu
@ChanChan-pg4wu 2 жыл бұрын
excellent explanation! Thank you Neetcode!
@user-wt2jd2qc3m
@user-wt2jd2qc3m 6 ай бұрын
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.
@hunterzhang9489
@hunterzhang9489 Жыл бұрын
This is the definition of NEAT CODE
@EagerEggplant
@EagerEggplant 2 жыл бұрын
Sets in side of hashes with with the row/column as the key... that's pretty awesome!
@vamseekotha
@vamseekotha 11 ай бұрын
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.
@tiennguyenthuy7563
@tiennguyenthuy7563 2 жыл бұрын
Brilliant answers and explanations. Thank you very much
@zainrab8629
@zainrab8629 Жыл бұрын
Amazing explanation with some really easy and clean code!
@rahulsbhatt
@rahulsbhatt Жыл бұрын
Your way of explaining things and implementation is neet. Thanks for posting this!
@varunajmera
@varunajmera 2 жыл бұрын
very well explained and very easy and intuitive
@Wanderor1
@Wanderor1 2 жыл бұрын
Amazing! Simply Amazing! Going to join your channel to help support the channel. Keep the videos coming.!
@aakashgyl
@aakashgyl 6 ай бұрын
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.
@gianniprocida3332
@gianniprocida3332 2 жыл бұрын
Excellent explanation for every problem.
@theartvillebyjessica
@theartvillebyjessica 2 жыл бұрын
Amazing explanation. Thank you for the wonderful videos.
@ngndnd
@ngndnd 7 ай бұрын
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
@dataman4503
@dataman4503 2 жыл бұрын
It's actually much easier to call them 3 - NxN matrices instead of 3 hash sets each of size NxN.
@fahimahyder2394
@fahimahyder2394 2 жыл бұрын
Beautifully done
@Moch117
@Moch117 11 ай бұрын
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
@Myshio
@Myshio 9 ай бұрын
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.
@gogolaygo1903
@gogolaygo1903 5 ай бұрын
Idk how i'd ever figure this one out without watching a video. As always, thanks!
@Cocamo1337
@Cocamo1337 Жыл бұрын
Thank you! Just used this method to solve the problem in C#
@gurudatt-shahane
@gurudatt-shahane Жыл бұрын
Thanks for making this video. It's a simple and intuitive explanation 🙏
@c0dertang
@c0dertang 2 жыл бұрын
I hard coded the squares XD. This really opened my eyes. Thanks!
@akagamishanks7991
@akagamishanks7991 9 ай бұрын
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!!!
@hamzaehsankhan
@hamzaehsankhan 11 ай бұрын
This makes my solution look like a crayon drawing of a 2-year-old. Awesome solution and well explained.
@ruicheng1241
@ruicheng1241 2 жыл бұрын
Thanks So Much For Explanation!
@aboronilov
@aboronilov 2 жыл бұрын
Bro you are awesome. I hope you have a huge salary and you are working on some top IT company!
@AlexanderKharitonov-cc1ei
@AlexanderKharitonov-cc1ei 3 жыл бұрын
Wonderful explanation! Could you please do 229 Majority Element 2? I am interested in algorithm with O(n) time complexity and O(1) space.
@the_hasnat
@the_hasnat 9 ай бұрын
such an elegant solution. makes it so easy!
@ThanhPhan-it5gm
@ThanhPhan-it5gm 3 ай бұрын
thanks a lot. What you've done is truly delightful
@gottuparthiharichandana3381
@gottuparthiharichandana3381 Жыл бұрын
You are awesome! The code very neat and understandable!! Thanks alot
@georgeli6820
@georgeli6820 2 жыл бұрын
great explanation brother!
@Cruzylife
@Cruzylife Жыл бұрын
preparing for doordash technical rounds, thanks neet
@uberwebd9824
@uberwebd9824 2 жыл бұрын
very clean and pythonic code
@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.
@codingtriangle
@codingtriangle Жыл бұрын
Thanks sir...before watching your solution when i solved this question my time complexity was like O(9^4) ....
@GoziePO
@GoziePO Жыл бұрын
Funny you recorded this on the 4th of July.! I'm watching it on the 4th of July 2023
@slava_xd
@slava_xd 5 ай бұрын
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
@davidbuderim2395
@davidbuderim2395 Жыл бұрын
Thanks - most helpful
@serhiiDev
@serhiiDev 8 ай бұрын
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.
@arjunprasad1071
@arjunprasad1071 Жыл бұрын
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
@wildinsights5033
@wildinsights5033 Жыл бұрын
subscribed and liked, thank you for sharing your knowledge
@lizgarcia4626
@lizgarcia4626 8 ай бұрын
This is incredible
@symbol767
@symbol767 2 жыл бұрын
Thanks man, liked
@shantipriya370
@shantipriya370 2 ай бұрын
simple neat and amazing
@m_elhosseiny
@m_elhosseiny Жыл бұрын
awesome as usual! :)
@MrShihab100
@MrShihab100 10 күн бұрын
Thanks a lot for your videos :)
@lifeanddatingadvice1711
@lifeanddatingadvice1711 3 жыл бұрын
Do sudoku solver next!
@mingzhejan3906
@mingzhejan3906 Жыл бұрын
Thank you from Taiwan
@heyasobi
@heyasobi 3 жыл бұрын
Can you do LC 1048 Longest String Chain? Watched a few other vids but can't quite wrap my head around it.
@piyushpawar4815
@piyushpawar4815 Жыл бұрын
You are awesome!!
@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.
@_dion_
@_dion_ 6 ай бұрын
this problem should have been in the hard category instead of medium. but u explained it really well as always. thanks.
@rahuljain281
@rahuljain281 2 жыл бұрын
Please make a video for leetcode 37 Sudoku Solver... Big Fan❤️
@servantofthelord8147
@servantofthelord8147 10 ай бұрын
Thank you, sir :)
@sanooosai
@sanooosai 7 ай бұрын
thank you sir
@brindhadhinakaran9672
@brindhadhinakaran9672 Жыл бұрын
Thanks !!!
@ljason6361
@ljason6361 9 ай бұрын
great solution
@diwasmainali1
@diwasmainali1 6 ай бұрын
Genius solution
@MK-xl5yo
@MK-xl5yo Жыл бұрын
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) ```
@Fauna.Fantastica
@Fauna.Fantastica 6 ай бұрын
you are the goat
@servantofthelord8147
@servantofthelord8147 Ай бұрын
This was a fun problem!
@amynguy
@amynguy 5 ай бұрын
can use a single hash map and append the identity [Row/Col/SubBox]
@lancetv4826
@lancetv4826 Ай бұрын
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
@aboutvenice
@aboutvenice Жыл бұрын
You are good!
@jonaskhanwald566
@jonaskhanwald566 3 жыл бұрын
Please do more Linked list problems
@mohammadsaudkhan8186
@mohammadsaudkhan8186 Ай бұрын
That's why he's the goat.......THE GOAT!!!
@sammyapsel1443
@sammyapsel1443 5 ай бұрын
can you explain the initialilzations of the sets? can't i just initialize them with : rows= {} ?
@cortisol_induced_coma
@cortisol_induced_coma 8 ай бұрын
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.
@ThamaraiselvamT
@ThamaraiselvamT 2 жыл бұрын
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.
@ritwik121
@ritwik121 2 жыл бұрын
@neetcode ... how to come up with own testcases ?
@148nihalmorshed2
@148nihalmorshed2 8 ай бұрын
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!
@kokob5715
@kokob5715 2 жыл бұрын
How do you get yourself to approach a given problem this way?
@naimeimran3247
@naimeimran3247 2 жыл бұрын
Thanks,
@hwang1607
@hwang1607 9 ай бұрын
the (row, col):set() default dictionary is insane
@robr4501
@robr4501 2 жыл бұрын
holy shit, this question become so easy!!!! genius
@amansaxena4446
@amansaxena4446 Жыл бұрын
how much time it took to get good level grasp on DSA? when u were able to solve quesitons in half hour
@alittlecoding
@alittlecoding 2 жыл бұрын
awesome
@Kitsune_Dev
@Kitsune_Dev 3 ай бұрын
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
@user-fb4iv4me6g
@user-fb4iv4me6g 8 ай бұрын
The operations of a HashSet are not O(1), they are O(n). A HashMap has a bound of O(1)
@josephjoestar4318
@josephjoestar4318 8 ай бұрын
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 8 ай бұрын
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
@bpsupergirl
@bpsupergirl 2 жыл бұрын
I have an interview in 3 weeks and...how the hell am I supposed to figure this out 😂
@harishdukkipati8921
@harishdukkipati8921 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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
@jerrykuo8736
@jerrykuo8736 2 жыл бұрын
My man recording Leetcode solutions on Fourth of July for us to pass our interviews. What’s your excuse?
@saurabhchopra
@saurabhchopra 2 жыл бұрын
Assigning board[r][c] to a variable and using the variable instead, makes the runtime of the program almost 2x faster.
@c0dertang
@c0dertang 2 жыл бұрын
hey it's technically O(1)! thats cool
@chaitanyanimma2939
@chaitanyanimma2939 3 жыл бұрын
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 жыл бұрын
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 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 Жыл бұрын
@@tsepten7930 u can't use pair as a key in unordered_map
Spiral Matrix - Microsoft Interview Question - Leetcode 54
16:46
Python Sudoku Solver - Computerphile
10:53
Computerphile
Рет қаралды 1,1 МЛН
Can You Draw A PERFECTLY Dotted Line?
00:55
Stokes Twins
Рет қаралды 99 МЛН
Каха ограбил банк
01:00
К-Media
Рет қаралды 11 МЛН
Мы никогда не были так напуганы!
00:15
Аришнев
Рет қаралды 6 МЛН
World’s Deadliest Obstacle Course!
28:25
MrBeast
Рет қаралды 159 МЛН
Product of Array Except Self - Leetcode 238 - Python
11:54
NeetCode
Рет қаралды 529 М.
LeetCode 36. Valid Sudoku (Algorithm Explained)
11:33
Nick White
Рет қаралды 97 М.
I Solved 1583 Leetcode Questions  Here's What I Learned
20:37
ThePrimeTime
Рет қаралды 559 М.
I quit Amazon after two months
10:09
NeetCode
Рет қаралды 578 М.
Coin Change - Dynamic Programming Bottom Up - Leetcode 322
19:23
Valid Sudoku - Leetcode 36 - Hashmaps & Sets (Python)
5:10
Greg Hogg
Рет қаралды 3,1 М.
Jump Game - Greedy - Leetcode 55
16:28
NeetCode
Рет қаралды 216 М.
Pass Your Next Tech Interview With Valid Sudoku
6:42
Chris Courses
Рет қаралды 17 М.
L15. Sudoko Solver | Backtracking
26:10
take U forward
Рет қаралды 245 М.
How to Solve ANY LeetCode Problem (Step-by-Step)
12:37
Codebagel
Рет қаралды 125 М.
Самый дорогой кабель Apple
0:37
Romancev768
Рет қаралды 291 М.
1$ vs 500$ ВИРТУАЛЬНАЯ РЕАЛЬНОСТЬ !
23:20
GoldenBurst
Рет қаралды 1,6 МЛН
iPhone 16 с инновационным аккумулятором
0:45
ÉЖИ АКСЁНОВ
Рет қаралды 7 МЛН
Blue Mobile 📲 Best For Long Audio Call 📞 💙
0:41
Tech Official
Рет қаралды 1 МЛН