Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript One fourth element in array
In JavaScript, finding an element that occurs more than one-fourth (25%) of the time in a sorted array is a common algorithmic problem. This requires checking specific positions and using binary search for efficiency.
Problem Statement
Given a sorted array of integers in increasing order, find the integer that appears more than 25% of the time. There is exactly one such element in the array.
For example, in the array [3, 5, 5, 7, 7, 7, 7, 8, 9], the number 7 appears 4 times out of 9 elements (44%), which is more than 25%.
Algorithm Approach
Since the array is sorted, we can use binary search to find the first and last occurrence of potential candidates. We check elements at positions that are multiples of one-fourth of the array length.
Implementation
const arr = [3, 5, 5, 7, 7, 7, 7, 8, 9];
const oneFourthElement = (arr = []) => {
const len = arr.length / 4;
const search = (left, right, target, direction = 'left') => {
let index = -1;
while (left <= right) {
const middle = Math.floor(left + (right - left) / 2);
if (arr[middle] === target) {
index = middle;
if (direction === 'left') {
right = middle - 1;
} else {
left = middle + 1;
}
} else if (arr[middle] < target) {
left = middle + 1;
} else {
right = middle - 1;
}
}
return index;
};
for (let i = 1; i <= 3; i++) {
const index = Math.floor(len * i);
const num = arr[index];
const loIndex = search(0, index, num, 'left');
const hiIndex = search(index, arr.length - 1, num, 'right');
if (hiIndex - loIndex + 1 > len) {
return num;
}
}
};
console.log(oneFourthElement(arr));
7
How It Works
The algorithm works by:
- Candidate Selection: Check elements at positions len/4, len/2, and 3*len/4
- Binary Search: For each candidate, find its first and last occurrence
- Count Verification: If the count exceeds 25% of array length, return the element
Alternative Simple Approach
For smaller arrays, a frequency counting approach can also work:
const arr2 = [1, 2, 2, 6, 6, 6, 6, 7, 10];
const oneFourthElementSimple = (arr) => {
const threshold = arr.length / 4;
const frequency = {};
for (const num of arr) {
frequency[num] = (frequency[num] || 0) + 1;
if (frequency[num] > threshold) {
return num;
}
}
};
console.log(oneFourthElementSimple(arr2));
6
Performance Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Binary Search | O(log n) | O(1) | Large sorted arrays |
| Frequency Count | O(n) | O(n) | Small arrays or unsorted data |
Conclusion
The binary search approach efficiently finds elements occurring more than 25% of the time in sorted arrays. Use frequency counting for simpler cases or when the array isn't sorted.
