Leetcode – 79. Word Search

Reading Time: 3 minutes

In this problem, we are given a two dimensional board of characters and we have to check if the word can be found in the board by checking adjacent cells only.

A basic strategy to solve this problem would be to start walking down the board until the first character is found. Once the first character is found, look at the character one row above, below, one column to the left and only column to the right to see if the second character in the string can be matched. If the second character is found, we look around that position and we go on and on if the characters are found. Before we go on exploring surrounding cells, we need to make sure that we have not visited it before and if we have, we just skip it. We can maintain a [[Bool]] to help us keep track of visited and unvisited cells.

This brings us to implementing a recursive strategy and if you think about it, it is pretty similar to Depth First Search.

There are some base cases that need to be handled like if the numRows and numCols are zero and if the search term is empty. Perhaps a base case that I totally missed and helps us completely avoid going into the recursion is checking if the size of the search term is greater than the product of the numRows and numCols, because if it is then there is no sense in proceeding.

The code for this as shown:

The time complexity is O(N) where N is the length of the search term as we only have to enter recursion if all characters until i-1 in the search term have been matched. There could be a situation in which the first character is never found while iterating through the board and in that case the time complexity is O(RC) in terms of the rows and columns.

The space complexity is O(RC) in terms of the rows and columns in the board as we maintain an additional two dimensional array to maintain the visited states.

The problem is taken from Leetcode.

The code is hosted on Github.

Mohit AthwaniLeetcode – 79. Word Search

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.