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
Then for example, any of the ordered subsequences starting with
Ain ABCDHGFEIJKLPONM is a potential word; so is any of the ordered subsequences starting withAin 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, sayX; then the potential words belong to the power set are:Hence, considering only the clockwise spirals starting at each character, we are already looking at
n^2*2^(n-1).n^2because the grid isn by nand so for a4 by 4grid there are 16 possible starting characters. And2^(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.