Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions NQueens.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Time Complexity : O(n * n!)
# Space Complexity : O( n^2 ) for the board + O( n ) recursive stack space
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : We’re placing queens row by row and checking if each placement is safe.
# If it's valid, we place it and move to the next row recursively.
# When all rows are filled, we convert the board to a list and store it in the result.

class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
self.res = []
board = [[False]*n for _ in range(n)]
self.helper(board, 0, n)
return self.res

def helper(self, board, row, n):
if row == n:
temp = []
for i in range(n):
sb = []
for j in range(n):
if board[i][j]:
sb.append("Q")
else:
sb.append(".")
temp.append("".join(sb))
self.res.append(temp)
return

for j in range(n):
if self.isValid(board, row, j, n):
board[row][j] = True
self.helper(board, row+1, n)
board[row][j] = False

def isValid(self, board, i, j, n):
r,c = i, j
while r >= 0:
if board[r][c]:
return False
r -= 1

r,c = i, j
while r >= 0 and c >= 0:
if board[r][c]:
return False
r -= 1
c -= 1

r,c = i, j
while r >= 0 and c < n:
if board[r][c]:
return False
r -= 1
c += 1

return True




44 changes: 44 additions & 0 deletions WordSearch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Time Complexity : O(m * n * 4^L) where L = word.length()
# Space Complexity : O(L) recursion stack in the worst case.
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : We go cell by cell and start DFS if the first character matches.
# We mark visited cells as # to avoid reuse during the same path.
# If we match all characters, we return true, else we backtrack.

class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
self.dirs = [[0,-1], [0, 1], [-1, 0], [1,0]]
self.rows, self.cols = len(board), len(board[0])

for i in range(self.rows):
for j in range(self.cols):
if self.dfs(board, i, j, word, 0):
return True
return False


def dfs(self, board: List[List[str]], i: int, j: int, word: str, idx: int) -> bool:
if idx == len(word):
return True

if i < 0 or j < 0 or i == self.rows or j == self.cols or board[i][j] == '#':
return False

if board[i][j] != word[idx]:
return False

board[i][j] = "#"

for dx, dy in self.dirs:
r = dx + i
c = dy + j

if self.dfs(board, r, c, word, idx + 1):
return True

board[i][j] = word[idx]

return False