15% off all plans & roadmaps Use code

See plans

Check if Word Can Be Placed In Crossword

Updated

TL;DR: You must decide whether the word fits exactly into one slot, where a slot is a run of non-blocked cells in a row or column. Split every row and column at each `#`. Then match the runs of exactly the word's length against the word and its reverse.

Problem

You get an m x n matrix board that shows the current state of a crossword puzzle. Each cell holds a lowercase letter from a solved word, a space ' ' for an empty cell, or '#' for a blocked cell.

A word can go horizontally, left to right or right to left, or vertically, top to bottom or bottom to top. A placement is valid when all of these hold:

  • The word does not cover any '#' cell.
  • Each cell the word covers is either empty or already holds the same letter.
  • The cell directly before the word and the cell directly after it, along the word's direction, are each '#' or off the board. No empty cell or other letter may sit next to the word.

Given a string word, return true if word can be placed in board, or false otherwise.

Example 1

Input: board = [['#', ' ', '#'], [' ', ' ', '#'], ['#', 'c', ' ']], word = 'abc'
Output: true
Explanation: The word abc fills column 1 from top to bottom.

Example 2

Input: board = [[' ', '#', 'a'], [' ', '#', 'c'], [' ', '#', 'a']], word = 'ac'
Output: false
Explanation: The word cannot be placed, since a space or a letter always sits above or below any spot where it could go.

Example 3

Input: board = [['#', ' ', '#'], [' ', ' ', '#'], ['#', ' ', 'c']], word = 'ca'
Output: true
Explanation: The word ca fits in row 1 when read from right to left.

Constraints

  • m == board.length
  • n == board[i].length
  • 1 <= m * n <= 2 * 10^5
  • board[i][j] is ' ', '#', or a lowercase English letter.
  • 1 <= word.length <= max(m, n)
  • word contains only lowercase English letters.

Constraints that matter

  • m * n up to 2 * 10^5 rules out trying every placement with a long scan from each cell. The solution must touch each cell only a few times.
  • word.length can be as large as max(m, n), so the brute force costs up to m * n * max(m, n) in the worst case. The scan approach avoids that factor.
  • Each slot must match the word length exactly. A longer run lets the word float inside it, which the rules forbid, so you must compare lengths for equality.
  • Letters can be placed in either direction, so every slot must be checked against the word and its reverse.

View on LeetCode

Hints

Hint 1

The word must fill a slot that is closed on both ends.

Hint 2

The naive check treats every cell as a possible first letter of the word.

Solution

Intuition

The word must fill a slot that is closed on both ends. A closed slot is a maximal run of non-blocked cells along one row or one column. Its two ends are either a # or the edge of the board. The rule that the neighbours must be blocked is then satisfied by construction.

It is like tearing a long strip of paper at every black mark, then looking for a torn piece exactly as long as the word card. Each torn piece is one maximal run, and the black marks are the # cells.

The grid breaks into independent lines, and each line breaks again at every blocked cell. Once you think in runs instead of starting cells, the search becomes one pass over each line. The site files this problem under backtracking word search. The optimal solution needs no recursion and no undo step, because the word never branches.

The work for a run is a short comparison. Each empty cell accepts any letter, and each letter cell must equal the word letter at the same index. Reading the run backwards covers the right-to-left and bottom-to-top placements, so each run gets two comparisons.

Watch the pattern animation

Worked example

Input: board = [['#', '#', '#'], ['#', ' ', '#'], ['#', '#', '#']], word = 'a'
Output: true
Explanation: The board has one empty cell in the middle, surrounded by blocks. A one-letter word fits that cell exactly. The cells beside it are all blocked or off the board.

The Word Search / Path Finding in Grid infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Word Search / Path Finding in Grid

Part of Backtracking Patterns

Approach 1: Brute forceWord Search / Path Finding in Grid

The naive check treats every cell as a possible first letter of the word. From each start, it tries the four directions and compares the word letter by letter. It also checks the two cells outside the word, because the rules require them to be blocked or off the board. Nothing is shared between attempts, so the same cells are re-read again and again.

Steps

  1. Loop over every cell (r, c) in the board.
  2. For each of the four directions (dr, dc), check the cell before the start, at (r - dr, c - dc). If it is on the board and not '#', skip this direction.
  3. Check the cell right after the end, at (r + L * dr, c + L * dc). If it is on the board and not '#', skip this direction.
  4. For i from 0 to L - 1, the cell (r + i * dr, c + i * dc) must be on the board, not '#', and either empty or equal to word[i]. If one check fails, skip this direction.
  5. If all L cells pass, return true.
  6. When every start and direction has failed, return false.

Dry run

The word has length 1, so the four directions behave the same. Cells (0, 0) through (0, 2), (1, 0), (1, 2), and (2, 0) through (2, 2) are all '#'. Each one fails at i = 0 in every direction, because the cell itself is blocked.

At (1, 1) the cell is empty. Take the direction (0, 1). The cell before, (1, 0), is '#', and the cell after, (1, 2), is '#'. The single cell is empty, so it accepts a, and the function returns true.

Complexity

TimeO(m * n * L)
SpaceO(1)

Let N = m * n be the number of cells and L the word length. The loops try each cell in four directions, which is 4N attempts. Each attempt does two boundary checks and at most L letter checks, so the work is O(N * L). That is at most O(m * n * max(m, n)). The loops keep only indices, so the extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
        m, n = len(board), len(board[0])
        L = len(word)

        def inside(r: int, c: int) -> bool:
            return 0 <= r < m and 0 <= c < n

        for r in range(m):
            for c in range(n):
                for dr, dc in ((0, 1), (0, -1), (1, 0), (-1, 0)):
                    # The cells just outside the word must be '#' or off the board
                    if inside(r - dr, c - dc) and board[r - dr][c - dc] != '#':
                        continue
                    if inside(r + L * dr, c + L * dc) and board[r + L * dr][c + L * dc] != '#':
                        continue
                    fits = True
                    for i in range(L):
                        rr, cc = r + i * dr, c + i * dc
                        if not inside(rr, cc) or board[rr][cc] == '#':
                            fits = False
                            break
                        if board[rr][cc] != ' ' and board[rr][cc] != word[i]:
                            fits = False
                            break
                    if fits:
                        return True
        return False

Approach 2: One pass over maximal segmentsOptimal

What is slow: the brute force restarts from every cell, and each restart re-reads cells that earlier starts already read. Most of those starts cannot work, because a slot must start right after a blocked cell or the board edge.

The insight that fixes it: a line only changes slot at its # cells. Split each row and each column at every #, and each piece is a maximal run. Only runs of exactly L cells can hold the word. Their ends are already closed, so the exact-fit rule holds by construction.

Each run of length L is compared against the word and its reverse in one linear pass. Every cell is read a constant number of times, so the whole board costs O(m * n).

Why it is correct. Any valid placement is a block of L non-blocked cells in one line, with both ends closed. Such a block can never cross a #, so it always lies inside one maximal run of exactly L cells. The check tests every such run in both directions, so no valid placement is ever skipped.

Steps

  1. Let L be the length of word, and build the reversed word once.
  2. For each row, read its cells from left to right as one line.
  3. For each column, read its cells from top to bottom as one line.
  4. Split each line at every '#'. Each piece is a maximal run of non-blocked cells.
  5. Skip every piece whose length is not exactly L.
  6. For each piece of length L, check that every cell is empty or equal to the word letter at the same index. If that fails, check the reversed word the same way.
  7. Return true on the first piece that passes. Return false after all lines.

Dry run

The word is a, so L = 1 and the reversed word is also a. The board has one empty cell at row 1, column 1.

StepLine readPieces after splitting on #Piece of length 1?Fits a?Result
1row 0: ###empty, empty, empty, emptynonokeep going
2row 1: # #empty, , emptyyes, the piece yes, an empty cell accepts areturn true

The scan stops at step 2, so the columns are never read. The function returns true, which matches the expected output.

Complexity

TimeO(m * n)
SpaceO(m + n)

Let N = m * n. Reading all rows and all columns touches each cell twice, which is O(N). Splitting each line walks its characters once, which adds O(N) more. A run of length L is compared at most twice. Runs in one line never overlap, so the comparisons per line are bounded by the line length. The total is O(N).

The space is one line at a time, which has at most max(m, n) cells, plus the reversed word of length L. Python, JavaScript and Go build each line as a string or array, so they use O(m + n). Java, C++ and C# can read cells by index and use only O(1) extra space.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
        m, n = len(board), len(board[0])
        L = len(word)
        rev = word[::-1]
        # Rows first, then columns. Each line becomes one string of cells.
        for k in range(m + n):
            if k < m:
                line = ''.join(board[k])
            else:
                line = ''.join(board[r][k - m] for r in range(m))
            # Splitting at '#' gives the maximal runs of this line
            for seg in line.split('#'):
                if len(seg) != L:
                    continue
                if all(s == ' ' or s == w for s, w in zip(seg, word)):
                    return True
                if all(s == ' ' or s == w for s, w in zip(seg, rev)):
                    return True
        return False

Common mistakes

  • if len(seg) >= L in place of len(seg) != L: a longer run lets the word float inside it. Require an exact length match, because the neighbours must be blocked or off the board.
  • Testing only word and never its reverse, so ca in a row is missed when it should read right to left. Compare each run against both the word and the reversed word.
  • Treating ' ' as a mismatch, for example if s != word[i] with no empty-cell case. An empty cell must accept any letter, so write s == ' ' or s == word[i].
  • Splitting on spaces instead of '#', which turns every empty cell into a wall. Blank cells are part of a slot. Split only at blocked cells.
  • Building the column with board[c][r] or reusing the row index for both loops. Column j reads board[i][j] for each row i, and the bug only shows when m is not n.
  • In the brute force, checking the letters but skipping board[r - dr][c - dc] and board[r + L * dr][c + L * dc]. Without those two checks, a longer slot passes as a fit.

Edge cases

  • A 1 x 1 board holding '#' with word a: return false, because the only cell is blocked.
  • A 1 x 1 board holding a space with word a: return true, because one empty cell is a slot of length 1 that accepts the letter.
  • A row x a a with word aa, where x is a letter: return false, because the run is three cells long and the word cannot be placed exactly.
  • A run c a with word ac: return true through the reversed check, because the word read right to left matches the run.
  • A run of exact length that conflicts in one cell, such as a b with word ac: return false, because the middle cell holds a letter that differs from the word.
  • A board of only blocks except one full row of spaces with length equal to max(m, n) and word of the same length: return true, which confirms the maximum-size path works.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Check if Word Can Be Placed In Crossword, with how to answer them.

Unlock the follow-ups

Check if Word Can Be Placed In Crossword FAQ

What is the time complexity of Check if Word Can Be Placed In Crossword?

The optimal segment scan runs in O(m * n) time, because each cell is read a constant number of times. The brute force runs in O(m * n * L), where L is the word length. Since L is at most max(m, n), the brute force is also bounded by O(m * n * max(m, n)).

Why use maximal segments for Check if Word Can Be Placed In Crossword?

Blocked cells and the board edges define the only possible slots. A word can only fill a run that is closed on both ends and has exactly its length. Splitting each line at # produces exactly those runs, so the search checks only valid slots.

Can Check if Word Can Be Placed In Crossword be solved in O(1) extra space?

Yes, for the index-based versions in Java, C++ and C#. They walk the grid directly and never store a line. Python, JavaScript and Go build each line as a string or array, which costs O(m + n) extra space.

Is Check if Word Can Be Placed In Crossword a backtracking problem?

The site files it under backtracking word search, but the optimal solution does not backtrack. The word never branches, so there is no choice to undo. A single linear scan of each line is enough.

Why does the reversed word need its own check?

A placement can read right to left or bottom to top. Those placements read the same cells in the opposite order, so a run that matches the reversed word is a valid slot. Checking both the word and its reverse covers all four directions.

Asked at

See which companies ask this — Pro

Practise it