I came across a problem that I learned was a Google interview question. The problem is:
An array is good if every subarray contains at least one element with frequency 1.
Design an algorithm to verify if an array is good in O(nlg^2(n)) time complexity. I assume the algorithm should be deterministic, not randomized.
I thought of using a divide-and-conquer approach:
We split the array into two halves and recursively check if they are good. The base case is when we have an array of size 1, which is always a good subarray. The challenge is how to combine the results of the two subarrays and determine if their concatenation is also good in time o(n^2). This is because we have O(n^2) subarrays to examine in this step. Can we do the combine step in O(nlgn)? If yes, we get the recurrence:
T(n) = 2T(n/2)+O(nlgn)
Then, by applying the Master's Theorem, we can conclude that T(n)=O(nlg^2n).
Divide and conquer seems a good idea, but don't divide in halves. Instead look for a unique element in the array, and use it as division point, while excluding that unique element from both partitions. If multiple unique elements are found, then divide into more partitions (to save some recursion depth), using all unique elements as division points.