Stumbled upon this interview question recently,
Given a 2-dimensional array of characters and a dictionary in which a word can be searched in O(1) time. Need to print all the words from array which are present in dictionary. Word can be formed in any direction but has to end at any edge of array.(Need not worry much about the dictionary)
Input:
a f h u n
e t a i r
a e g g o
t r m l p
Output:
after
hate
hair
air
eat
tea
Note: Here “egg” is not a dictionary word because its not ending at the edge of array.
I’ve seen similar questions before, but was never able to think of a good algorithm to solve these kind of problems. Any help on how to approach these kind of problems (forming words from arrays of characters) will be highly helpful.
(The only way I could think of is to find all possible permutations of characters in the 2D array, and check if it ends on the edge of the array, and check if the permutation is a valid word from the dictionary in O(1) time)
Turn the array into a graph so that each cell
[i,j]has an edge shared with each one of its 4 neighbors
[i+1,j], [i-1,j], [i,j+1], [i,j-1].Then run DFS at each array-edge-cell and and keep checking the dictionary whether
the word in reverse is in it.