Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an m x n matrix board, representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells.
A word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if:
'#'.' ' (empty) or match the letter already on the board.' ' or other lowercase letters directly left or right of the word if the word was placed horizontally.' ' or other lowercase letters directly above or below the word if the word was placed vertically.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" can be placed as shown above (top to bottom).
Example 2:
Input: board = [[" ", "#", "a"], [" ", "#", "c"], [" ", "#", "a"]], word = "ac" Output: false Explanation: It is impossible to place the word because there will always be a space/letter above or below it.
Example 3:
Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", " ", "c"]], word = "ca" Output: true Explanation: The word "ca" can be placed as shown above (right to left).
Constraints:
m == board.lengthn == board[i].length1 <= m * n <= 2 * 105board[i][j] will be ' ', '#', or a lowercase English letter.1 <= word.length <= max(m, n)word will contain only lowercase English letters.Problem summary: You are given an m x n matrix board, representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells. A word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if: It does not occupy a cell containing the character '#'. The cell each letter is placed in must either be ' ' (empty) or match the letter already on the board. There must not be any empty cells ' ' or other lowercase letters directly left or right of the word if the word was placed horizontally. There must not be any empty cells ' ' or other lowercase letters directly above or below the word if the word was placed vertically. Given a string word, return true if word can be placed in board, or false otherwise.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[["#"," ","#"],[" "," ","#"],["#","c"," "]] "abc"
[[" ","#","a"],[" ","#", "c"],[" ","#","a"]] "ac"
[["#"," ","#"],[" "," ","#"],["#"," ","c"]] "ca"
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2018: Check if Word Can Be Placed In Crossword
class Solution {
private int m;
private int n;
private char[][] board;
private String word;
private int k;
public boolean placeWordInCrossword(char[][] board, String word) {
m = board.length;
n = board[0].length;
this.board = board;
this.word = word;
k = word.length();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
boolean leftToRight = (j == 0 || board[i][j - 1] == '#') && check(i, j, 0, 1);
boolean rightToLeft = (j == n - 1 || board[i][j + 1] == '#') && check(i, j, 0, -1);
boolean upToDown = (i == 0 || board[i - 1][j] == '#') && check(i, j, 1, 0);
boolean downToUp = (i == m - 1 || board[i + 1][j] == '#') && check(i, j, -1, 0);
if (leftToRight || rightToLeft || upToDown || downToUp) {
return true;
}
}
}
return false;
}
private boolean check(int i, int j, int a, int b) {
int x = i + a * k, y = j + b * k;
if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] != '#') {
return false;
}
for (int p = 0; p < k; ++p) {
if (i < 0 || i >= m || j < 0 || j >= n
|| (board[i][j] != ' ' && board[i][j] != word.charAt(p))) {
return false;
}
i += a;
j += b;
}
return true;
}
}
// Accepted solution for LeetCode #2018: Check if Word Can Be Placed In Crossword
func placeWordInCrossword(board [][]byte, word string) bool {
m, n := len(board), len(board[0])
k := len(word)
check := func(i, j, a, b int) bool {
x, y := i+a*k, j+b*k
if x >= 0 && x < m && y >= 0 && y < n && board[x][y] != '#' {
return false
}
for _, c := range word {
if i < 0 || i >= m || j < 0 || j >= n || (board[i][j] != ' ' && board[i][j] != byte(c)) {
return false
}
i, j = i+a, j+b
}
return true
}
for i := range board {
for j := range board[i] {
leftToRight := (j == 0 || board[i][j-1] == '#') && check(i, j, 0, 1)
rightToLeft := (j == n-1 || board[i][j+1] == '#') && check(i, j, 0, -1)
upToDown := (i == 0 || board[i-1][j] == '#') && check(i, j, 1, 0)
downToUp := (i == m-1 || board[i+1][j] == '#') && check(i, j, -1, 0)
if leftToRight || rightToLeft || upToDown || downToUp {
return true
}
}
}
return false
}
# Accepted solution for LeetCode #2018: Check if Word Can Be Placed In Crossword
class Solution:
def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
def check(i, j, a, b):
x, y = i + a * k, j + b * k
if 0 <= x < m and 0 <= y < n and board[x][y] != '#':
return False
for c in word:
if (
i < 0
or i >= m
or j < 0
or j >= n
or (board[i][j] != ' ' and board[i][j] != c)
):
return False
i, j = i + a, j + b
return True
m, n = len(board), len(board[0])
k = len(word)
for i in range(m):
for j in range(n):
left_to_right = (j == 0 or board[i][j - 1] == '#') and check(i, j, 0, 1)
right_to_left = (j == n - 1 or board[i][j + 1] == '#') and check(
i, j, 0, -1
)
up_to_down = (i == 0 or board[i - 1][j] == '#') and check(i, j, 1, 0)
down_to_up = (i == m - 1 or board[i + 1][j] == '#') and check(
i, j, -1, 0
)
if left_to_right or right_to_left or up_to_down or down_to_up:
return True
return False
// Accepted solution for LeetCode #2018: Check if Word Can Be Placed In Crossword
/**
* [2018] Check if Word Can Be Placed In Crossword
*
* You are given an m x n matrix board, representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells.
* A word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if:
*
* It does not occupy a cell containing the character '#'.
* The cell each letter is placed in must either be ' ' (empty) or match the letter already on the board.
* There must not be any empty cells ' ' or other lowercase letters directly left or right of the word if the word was placed horizontally.
* There must not be any empty cells ' ' or other lowercase letters directly above or below the word if the word was placed vertically.
*
* Given a string word, return true if word can be placed in board, or false otherwise.
*
* Example 1:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/10/04/crossword-ex1-1.png" style="width: 478px; height: 180px;" />
* Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", "c", " "]], word = "abc"
* Output: true
* Explanation: The word "abc" can be placed as shown above (top to bottom).
*
* Example 2:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/10/04/crossword-ex2-1.png" style="width: 180px; height: 180px;" />
* Input: board = [[" ", "#", "a"], [" ", "#", "c"], [" ", "#", "a"]], word = "ac"
* Output: false
* Explanation: It is impossible to place the word because there will always be a space/letter above or below it.
* Example 3:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/10/04/crossword-ex3-1.png" style="width: 478px; height: 180px;" />
* Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", " ", "c"]], word = "ca"
* Output: true
* Explanation: The word "ca" can be placed as shown above (right to left).
*
*
* Constraints:
*
* m == board.length
* n == board[i].length
* 1 <= m * n <= 2 * 10^5
* board[i][j] will be ' ', '#', or a lowercase English letter.
* 1 <= word.length <= max(m, n)
* word will contain only lowercase English letters.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/
// discuss: https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn place_word_in_crossword(board: Vec<Vec<char>>, word: String) -> bool {
false
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_2018_example_1() {
let board = vec![
vec!['#', ' ', '#'],
vec![' ', ' ', '#'],
vec!['#', 'c', ' '],
];
let word = "abc".to_string();
let result = true;
assert_eq!(Solution::place_word_in_crossword(board, word), result);
}
#[test]
#[ignore]
fn test_2018_example_2() {
let board = vec![
vec![' ', '#', 'a'],
vec![' ', '#', 'c'],
vec![' ', '#', 'a'],
];
let word = "ac".to_string();
let result = false;
assert_eq!(Solution::place_word_in_crossword(board, word), result);
}
#[test]
#[ignore]
fn test_2018_example_3() {
let board = vec![
vec!['#', ' ', '#'],
vec![' ', ' ', '#'],
vec!['#', ' ', 'c'],
];
let word = "ca".to_string();
let result = true;
assert_eq!(Solution::place_word_in_crossword(board, word), result);
}
}
// Accepted solution for LeetCode #2018: Check if Word Can Be Placed In Crossword
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #2018: Check if Word Can Be Placed In Crossword
// class Solution {
// private int m;
// private int n;
// private char[][] board;
// private String word;
// private int k;
//
// public boolean placeWordInCrossword(char[][] board, String word) {
// m = board.length;
// n = board[0].length;
// this.board = board;
// this.word = word;
// k = word.length();
// for (int i = 0; i < m; ++i) {
// for (int j = 0; j < n; ++j) {
// boolean leftToRight = (j == 0 || board[i][j - 1] == '#') && check(i, j, 0, 1);
// boolean rightToLeft = (j == n - 1 || board[i][j + 1] == '#') && check(i, j, 0, -1);
// boolean upToDown = (i == 0 || board[i - 1][j] == '#') && check(i, j, 1, 0);
// boolean downToUp = (i == m - 1 || board[i + 1][j] == '#') && check(i, j, -1, 0);
// if (leftToRight || rightToLeft || upToDown || downToUp) {
// return true;
// }
// }
// }
// return false;
// }
//
// private boolean check(int i, int j, int a, int b) {
// int x = i + a * k, y = j + b * k;
// if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] != '#') {
// return false;
// }
// for (int p = 0; p < k; ++p) {
// if (i < 0 || i >= m || j < 0 || j >= n
// || (board[i][j] != ' ' && board[i][j] != word.charAt(p))) {
// return false;
// }
// i += a;
// j += b;
// }
// return true;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.