What is the best time complexity O(n) of a function that solves boggle, where the boggle board is n by n?
I feel that it's n^2
since for each character we must look at 2(n-1)
other characters. The interviewer argued that it's not n^2
for an O(1)
dictionary look-up.
I finally figured it out. The answer turns out to be exponential in time.
Imagine a 4X4 boggle grid
ABCD
EFGH
IJKL
MNOP
Then for example, any of the ordered subsequences starting with A
in ABCDHGFEIJKLPONM is a potential word; so is any of the ordered subsequences starting with A
in AEIMNOPLHDCBFJKG or AEIMNOPLHGFIK or ABCDHLPONMIEFGKJ. Then we need to look at the potential words starting wiht B, then with C, etc.
Let's look at this another way. Say we only had to consider _ABCD, where _
represents some starting character, say X
; then the potential words belong to the power set are:
XD; XC; XCD; XB; XBD; etc.
Hence, considering only the clockwise spirals starting at each character, we are already looking at n^2*2^(n-1)
. n^2
because the grid is n by n
and so for a 4 by 4
grid there are 16 possible starting characters. And 2^(n-1)
because of the powerset led by each starting character. Of course the clockwise spiral is not the only possible pattern. But we can already see the time complexity with that first pattern: Big-Omega(2^n) which is exponential.