The Element Appearing More Than 25% In Sorted Array coding problem asks you to find an integer in a sorted array that occurs more than 25% of the time. Given that the array is sorted, all occurrences of the same number will be contiguous. The problem guarantees that exactly one such element exists.
Companies like Amazon and Microsoft use this array interview pattern to test whether a candidate can leverage the "sorted" property of an array to optimize a search. While a linear scan (O(N)) is easy, the problem can be solved in O(log N) time using binary search, which demonstrates a higher level of algorithmic thinking.
There are two main approaches:
arr[i] == arr[i + span], where span is n / 4. If they are equal, then all elements between them are also the same, meaning the element appears at least span + 1 times.n/4, n/2, or 3n/4. For each of these candidates, use binary search to find its first and last occurrence and calculate the total count.Array: [1, 2, 2, 6, 6, 6, 6, 7, 10], n = 9.
9 / 4 = 2.arr[i] and arr[i+2]:
arr[0]=1, arr[2]=2. Not same.arr[1]=2, arr[3]=6. Not same.arr[2]=2, arr[4]=6. Not same.arr[3]=6, arr[5]=6. Same!
Wait, the span should be n/4. For n=9, span=2. arr[3] to arr[5] is a sequence of 6s. arr[3] to arr[6] is four 6s.
The element is 6.n / 4) is safer for index logic.Whenever you see "Sorted Array" and "Find an element with property X," your mind should immediately jump to Binary Search. Even if O(N) is acceptable, discussing the O(log N) possibility shows you are thinking about scale.