Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding special kind of elements with in an array in JavaScript
We are required to write a JavaScript function that takes in three arguments, namely −
arr --> an array of integers m --> a positive integer n --> a positive integer
The task of our function is to find out whether there exists two such elements (lets call them a1 and a2) such that −
The absolute difference between a1 and a2 is at most m
The absolute difference between the indices of a1 and a2 is at most n
Example
Following is the code −
const arr = [1, 2, 3, 1, 7, 8];
const findSpecialElements = (arr = [], m, n) => {
const map = arr
.map((el, ind) => ({ el, ind }))
.sort((a, b) => a.el - b.el);
let left = 0;
let right = 1;
while (right < map.length) {
const diff = Math.abs(map[right].el - map[left].el);
const range = Math.abs(map[right].ind - map[left].ind);
if (diff <= n && range <= m){
return true
}else if (diff > n){
left++;
}else if (range > m){
right++;
};
if (left === right){
right++;
};
};
return false;
};
console.log(findSpecialElements(arr, 3, 0));
Output
Following is the console output −
true
Advertisements