![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript One fourth element in array
Problem
JavaScript function that takes in an array of integers sorted in increasing order, arr.
There is exactly one integer in the array that occurs more than one fourth times (25%) of the times, our function should return that number.
For example, if the input to the function is −
const arr = [3, 5, 5, 7, 7, 7, 7, 8, 9];
Then the output should be −
const output = 7;
Example
The code for this will be −
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));
Output
And the output in the console will be −
7
Advertisements