Amazon Interview Question
Software Engineer / DevelopersCreating the array of first and last chars is O(n)
Now matching the two arrays is O(n^2).
So total complexity is O(n^2)
Creating two arrays with the first char & the last char = O(n) (Both arrays can be built at the same time by loading the first & the last char of every string. Do this for every string. This is proportional to the number of strings & hence O(n)).
Comparing the two arrays if exactly n-1 matches are present is again O(n). We dont need 2 loops. We can compare both arrays in a single step index-by-index. Hence, this is O(n).
So, total complexity is O(n) + O(n) = O(n).
O(n) is defenitely better than O(n^2). But, I'm not sure about the time complexity of Hamiltonian circuits.
The question does not say "find the path". Check if it is possible to do it. Create one array of the first characters and another of the last characters in the string. If there are n-1 matches (one character in the first and one character in the last need not match), then we can do the same. Simple!
- G May 15, 2009