← Back to companies
[ OK ] Loaded —
[ INFO ]
$ cd
$ ls -lt
01
02
03
04
05
$ ls -lt
01
02
03
04
05
user@intervues:~/$
Problem Statement: Design a service that solves crossword puzzles. Given a board with word slots (positions, directions, lengths) and a dictionary of ~1 million words, find any valid assignment of words that satisfies all the constraints.
Examples:
+---+---+---+---+---+---+ | | | | | | | +---+---+---+---+---+---+ | | | | | | | +---+---+---+---+---+---+ | | | | | | | +---+---+---+---+---+---+ | | | | | | | +---+---+---+---+---+---+ | | | | | | | +---+---+---+---+---+---+ | | | | | | | +---+---+---+---+---+---+
Word slots:Dictionary: ["hello", "world", "example", ...]
Output: A valid assignment of words that satisfies all the constraints.
Constraints:
Hints:
Solution:
Preprocess the dictionary:
Define a recursive backtracking function to explore all possible word assignments:
Optimize the backtracking algorithm:
Return the first valid assignment found by the backtracking algorithm.
Example Code:
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_word = True
def search(self, prefix):
node = self.root
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return True
def solve_crossword(board, word_slots, dictionary):
# Preprocess the dictionary
trie = Trie()
for word in dictionary:
trie.insert(word)
# Group words by length
words_by_length = {}
for word in dictionary:
length = len(word)
if length not in words_by_length:
words_by_length[length] = []
words_by_length[length].append(word)
# Backtracking function
def backtrack(board, word_slots, index):
if index == len(word_slots):
return True
slot = word_slots[index]
direction = slot["direction"]
start_pos = slot["start_pos"]
length = slot["length"]
# Try all possible words for the current slot
for word in words_by_length.get(length, []):
if can_place_word(board, word, start_pos, direction):
board[start_pos[0]][start_pos[1]] = word[0]
if backtrack(board, word_slots, index + 1):
return True
board[start_pos[0]][start_pos[1]] = None
return False
def can_place_word(board, word, start_pos, direction):
if direction == "across":
for i in range(len(word)):
if board[start