#2018

Check if Word Can Be Placed In Crossword

Medium
ArrayMatrixEnumerationEnumerationMatrix Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(m * n * k)
O(m * n)
Space
O(1)
O(1)
💡

Intuition

Time O(m * n)Space O(1)

The optimal solution uses a systematic approach to identify all possible placements for the word in one pass. By checking the boundaries and conditions before attempting to place the word, we minimize unnecessary checks.

⚙️

Algorithm

3 steps
  1. 1Step 1: Iterate through each cell in the board to find potential starting points for the word.
  2. 2Step 2: For each starting point, check if the word can fit horizontally and vertically using helper functions.
  3. 3Step 3: Ensure that the placement does not violate any rules regarding adjacent cells.
solution.py23 lines
1def canPlaceWord(board, word):
2    m, n = len(board), len(board[0])
3    word_len = len(word)
4    def canPlaceHorizontally(i, j):
5        if j > 0 and board[i][j - 1] != '#': return False
6        if j + word_len < n and board[i][j + word_len] != '#': return False
7        for k in range(word_len):
8            if board[i][j + k] != ' ' and board[i][j + k] != word[k]:
9                return False
10        return True
11    def canPlaceVertically(i, j):
12        if i > 0 and board[i - 1][j] != '#': return False
13        if i + word_len < m and board[i + word_len][j] != '#': return False
14        for k in range(word_len):
15            if board[i + k][j] != ' ' and board[i + k][j] != word[k]:
16                return False
17        return True
18    for i in range(m):
19        for j in range(n):
20            if board[i][j] == ' ' or board[i][j] == word[0]:
21                if canPlaceHorizontally(i, j) or canPlaceVertically(i, j):
22                    return True
23    return False

Complexity note: We only traverse the board once, checking each cell and its possible placements, leading to O(m * n).

  • 1Identify potential starting points for the word.
  • 2Check boundaries to avoid out-of-bounds errors.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.