Yet another interview question asked me to find the maximum possible subarray of repeated values given a sorted array in shortest computational time possible.
Let input array be A[1 ... n]
Find an array B of consecutive integers in A such that:
for x in range(len(B)-1):
B[x] == B[x+1]
I believe that the best algorithm is dividing the array in half and going from the middle outwards and comparing from the middle the integers with one another and finding the longest strain of the same integers from the middle. Then I would call the method recursively by dividing the array in half and calling the method on the two halves.
My interviewer said my algorithm is good but my analysis that the algorithm is O(logn) is incorrect but never got around to telling me what the correct answer is. My first question is what is the Big-O analysis of this algorithm? (Show as much work as possible please! Big-O is not my forte.) And my second question is purely for my curiosity whether there is an even more time efficient algorithm?
The best you can do for this problem is an
O(n)solution, so your algorithm cannot possibly be both correct andO(lg n).Consider for example, the case where the array contains no repeated elements. To determine this, one needs to examine every element, and examining every element is
O(n).This is a simple algorithm that will find the longest subsequence of a repeated element:
If you have reason to believe the subsequence will be long, you can set the initial value of
maxLengthto some heuristically selected value to speed things along, and then only look for shorter sequences if you don’t find one (i.e. you end up withend == 0after the first pass.)