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
Removing already listed intervals in JavaScript
Problem
JavaScript function that takes in a 2-D array, arr, as the first and the only argument.
Each subarray of our input array is an array of exactly two numbers, specifying a time interval.
Our function should remove all intervals that are covered by another interval in the array arr. Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d. Our function should finally return the number of remaining intervals in the array.
For example, if the input to the function is −
const arr = [ [2, 5], [5, 7], [3, 9] ];
Then the output should be −
const output = 2;
Output Explanation:
Interval [5, 7] is covered by [3, 9], therefore it is removed.
Example
The code for this will be −
const arr = [
[2, 5],
[5, 7],
[3, 9]
];
const removeCovered = (arr = []) => {
arr.sort(([a, b], [c, d]) => (a === c ? d - b : a - c));
let last = arr[0];
let count = arr.length;
for(let i = 1; i < arr.length; i++){
const [a, b] = last;
const [c, d] = arr[i];
if(c >= a && d <= b){
count -= 1;
}else{
last = arr[i];
};
};
return count;
};
console.log(removeCovered(arr));
Output
And the output in the console will be −
2
Advertisements