The "Check If a Number Is Majority Element in a Sorted Array interview question" asks you to verify if a target number target appears more than times in a given array. The array is guaranteed to be sorted in non-decreasing order. This "Majority Element coding problem" is a variation of the standard majority element task, but the "sorted" property allows for a much faster solution than a simple count.
Salesforce and other companies use this problem to see if a candidate can optimize a search. While a linear scan is , the sorted property should immediately trigger thoughts of Binary Search, which is . It evaluates your ability to find boundaries in an array and use them to calculate frequency.
This problem uses the Binary Search (Find First/Last Occurrence) pattern.
target appears.first_index + n/2.arr[first_index + n/2] is equal to target. Because the array is sorted, if the element at the "halfway jump" from the start is the same, then every element in between must also be the target.Array: [2, 4, 5, 5, 5, 5, 5, 6, 6], Target: 5, .
2.first_index + n/2 = 2 + 4 = 6.arr[6] is 5.
Result: True. (If it were not the majority element, the element at index 6 would have been greater than 5).first_index + n/2 exceeds the array length before accessing it.Whenever you see "Sorted Array" and "Count" or "Search," think Binary Search. Master the ability to find the leftmost and rightmost occurrences of a value, as this is a fundamental "Array interview pattern" skill.