Search for a “needle” in a two-difference “haystack”

I think this is one of the most frequently asked interview questions, but I cannot solve it effectively (effective value means less time complexity and using an appropriate data structure). The problem is this: If there are m x n matrixcharacters (say, hay) and a given string of charlength k (needle). Write a program to check if the haystack contains a needle. Please note that we need to search for a haystack only from top to bottom or from left to right. for instance

Haystack

ahydsfd
sdflddl
dfdfd
dfdl
uifddffdhc

Needle:
hdffi

Output:
Yes Found!!
+5
source share
3 answers

Naive brute force is O (m * n * k). Here are some ideas for optimization.


, , , . , , , . , , .


, , , . . , , , .


, Knuth-Morris-Pratt. , . , , , O (m * n).


, . , , "" , , , .

+8

m * n. , , .

0

You can limit the search for the first char columns to nk and mk rows. After detection, the response requires 2 (k-1).

0
source

All Articles