- 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
Determine whether there is a pair of values in the array where the average of the pair equals to the target average in JavaScript
We are required to write a JavaScript function that takes in an array of sorted integers and a target average as first and second arguments.
The function should determine whether there is a pair of values in the array where the average of the pair equals to the target average.
There's a solution with O(1) additional space complexity and O(n) time complexity. Since an array is sorted, it makes sense to have two indices: one going from begin to end (say y), another from end to begin of an array (say x).
Example
The code for this will be −
const arr = [1, 2, 4, 6, 7, 9, 11]; const averagePair = (arr = [], target = 1) => { let x = arr.length − 1; for (let y = 0; y < x; y++) { while (y < x && arr[x] + arr[y] > 2*target) { x−−; }; if (x !== y && arr[x] + arr[y] === 2 * target) { return true; }; }; return false; }; console.log(averagePair(arr, 6.5));
Output
And the output in the console will be −
true
Advertisements
To Continue Learning Please Login
Login with Google