Finding minimum time difference in an array in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of 24-hour clock time points in "Hour:Minutes" format. Our function should find the minimum minutes difference between any two time points in the array.

For example, if the input to the function is −

const arr = ["23:59","00:00"];

Then the output should be −

const output = 1;

Because the minimum difference between the times is 1 minute

Example

Following is the code −

 Live Demo

const arr = ["23:59","00:00"];
const findMinDifference = (arr = []) => {
   const find = (str = '') => str.split(':').map(time => parseInt(time, 10))
   const mapped = arr.map((time) => {
      const [hour1, minute1] = find(time)
      return hour1 * 60 + minute1
   });
   const sorted = []
   let isrepeating = false
   mapped.forEach((time) => {
      if (sorted[time] !== undefined || sorted[time + 24 * 60] !== undefined) {
      isrepeating = true
   }
      sorted[time] = time
      sorted[time + 24 * 60] = time + 24 * 60
   })
   if (isrepeating) {
      return 0
   }
   let min = Infinity
   let prev = null
   for (let i = 0; i < sorted.length; i++) {
      if (sorted[i] !== undefined) {
         if (prev) {
            min = Math.min(min, sorted[i] - prev)
         }
         prev = sorted[i]
      }
   }
   return min
};
console.log(findMinDifference(arr));

Output

Following is the console output −

1

Updated on: 21-Apr-2021

270 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements