Skip to content

Commit 3a0a820

Browse files
author
Ikboljon Abdurasulov
committed
is sudoku valid problem
1 parent 90b4255 commit 3a0a820

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# LINK: https://leetcode.com/problems/group-anagrams/
2+
# COMPLEXITY: Time complexity: O(1) Space complexity: O(1)
3+
#Explanation: Since the size of the input board is fixed at 9x9,
4+
# the number of iterations in the two loops is constant, which
5+
# means the time complexity is constant. Similarly, the size of the
6+
# data structures used to keep track of the numbers is also fixed at
7+
# 9x9, which means the space complexity is also constant.
8+
import collections
9+
class Solution:
10+
def isValidSudoku(self, board):
11+
cols = collections.defaultdict(set)
12+
rows = collections.defaultdict(set)
13+
squares = collections.defaultdict(set)
14+
15+
for r in range(9):
16+
for c in range(9):
17+
if board[r][c] == '.':
18+
continue
19+
if (board[r][c] in rows[r] or
20+
board[r][c] in cols[c]or
21+
board[r][c] in squares[(r//3,c//3)]):
22+
return False
23+
cols[c].add(board[r][c])
24+
rows[r].add(board[r][c])
25+
squares[(r//3,c//3)].add(board[r][c])
26+
return True
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import pytest
2+
from isValidSudoku import Solution
3+
4+
@pytest.fixture
5+
def inputs():
6+
return [
7+
(
8+
[["5","3",".",".","7",".",".",".","."]
9+
,["6",".",".","1","9","5",".",".","."]
10+
,[".","9","8",".",".",".",".","6","."]
11+
,["8",".",".",".","6",".",".",".","3"]
12+
,["4",".",".","8",".","3",".",".","1"]
13+
,["7",".",".",".","2",".",".",".","6"]
14+
,[".","6",".",".",".",".","2","8","."]
15+
,[".",".",".","4","1","9",".",".","5"]
16+
,[".",".",".",".","8",".",".","7","9"]],
17+
True
18+
),
19+
(
20+
[["8","3",".",".","7",".",".",".","."]
21+
,["6",".",".","1","9","5",".",".","."]
22+
,[".","9","8",".",".",".",".","6","."]
23+
,["8",".",".",".","6",".",".",".","3"]
24+
,["4",".",".","8",".","3",".",".","1"]
25+
,["7",".",".",".","2",".",".",".","6"]
26+
,[".","6",".",".",".",".","2","8","."]
27+
,[".",".",".","4","1","9",".",".","5"]
28+
,[".",".",".",".","8",".",".","7","9"]],
29+
False
30+
),
31+
]
32+
def test_isValidSudoku(inputs):
33+
for board, expected in inputs:
34+
s = Solution()
35+
assert s.isValidSudoku(board) == expected

0 commit comments

Comments
 (0)