Amazon Interview Question
SDE1sCountry: India
Interview Type: In-Person
I'm not really sure where you are going with this, but it appears to be a very brute force. While DP does not need to be recursive, you still appear to check every character for every slot in the NxN character matrix.
forward means right (x+1,y)
down mean (x,y+1)
diagonal means (x+1,y+1)
it can be done with BFS. {search the no. of occurance of a given word example "sachin" in the whole NxN matrix}
w | s | r | t | g | g|
a | a | c | h | i | n |
k | c | h | u | j | j |
o | h | i | n | y | q |
in this sachin can be found out 3 times.
if the word is given, a brute force solution is check each point(i,j) in the matrix, and if m[i][j]=word[0],then check three directions with length equals word.length(). this is a O(mnk) complexity, where m,n is matrix size, k is word size.
if the word finding process will execute multi times,then maybe generate all prefix of rows,cols,dialogues of the matrix, and use trie is a better idea.
The question isn't exactly clear, what is forward, which diagonal and whether we need to find the number of occurrences of a given word(s) or the occurrences of all possible words.
Anyway, I'll assume the following:
1. We're counting the number of occurrences of a given word.
2. Forward means right.
3. Diagonally means right and down.
My approach is to use dynamic programming and basically count the number of occurrences of every suffix beginning from every array element. This solution (and there probably are better ones) has O(k*n^2) run-time and space complexity (k is the length of the input string).
- EulGam05 December 15, 2013