Word Search dfs solution complexity evaluation

Whaddup to the sub,

I'm requesting feedback on a complexity evaluation of my solution to Word Search. I implemented a dfs approach and my code is at the bottom. I think my time complexity is O(m * n * 4^w ) and space complexity is O(4^w ) where w == len(word).

Does that seem correct?

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        def dfs(i: int, j: int, n: int) -> bool:
            # Escapes
            if n == len(word):
                return True
            if (i < 0 or i >= len(board) or j < 0 or j >= len(board[0])
                or word[n] != board[i][j]
                or (i, j) in path
               ):
                return False

            path.add((i, j))
            res = (dfs(i + 1, j, n + 1)
                  or dfs(i - 1, j, n + 1)
                  or dfs(i, j + 1, n + 1)
                  or dfs(i, j - 1, n + 1)
                  )
            path.remove((i, j))

            return res

        path = set()
        for i in range(len(board)):
            for j in range(len(board[0])):
                if dfs(i, j, 0):
                    return True
        return False

    # O(m ⋅ n ⋅ o) where m ⋅ n is area of board and w is the dfs operation.
    #        o == O(branches^depth) == O(4^len(word)) == O(4^w)
    # O(m ⋅ n ⋅ 4^w) time where w == len(word)
    # O(4^w) space

Posted May 4, 2022, 1:57 AM UTC

52
Loading comments…