#1287
Element Appearing More Than 25% In Sorted Array
EasyArrayHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Since the array is sorted, we can leverage this property to find the element that appears more than 25% of the time without counting every occurrence. We can check specific intervals based on the sorted nature of the array.
⚙️
Algorithm
4 steps- 1Step 1: Calculate the length of the array.
- 2Step 2: Determine the threshold for 25% of the array length.
- 3Step 3: Check the elements at the start, 25%, 50%, and 75% positions of the array.
- 4Step 4: For each of these positions, verify if the element appears more than the threshold in the surrounding elements.
solution.py6 lines
1def findSpecialInteger(arr):
2 n = len(arr)
3 threshold = n // 4
4 for i in range(0, n, threshold):
5 if i + threshold < n and arr[i] == arr[i + threshold]:
6 return arr[i]ℹ
Complexity note: The time complexity is O(n) because we only traverse the array a constant number of times based on the threshold, making it efficient.
- 1The array is sorted, allowing for efficient checks at specific intervals.
- 2The problem guarantees one element appears more than 25%, simplifying our search.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.