Common element with least index sum in JavaScript


Problem

We are required to write a JavaScript function that takes in two arrays of literals, arr1 and arr2, as the first and the second argument.

Our function should find out the common element in arr1 and arr2 with the least list index sum. If there is a choice tie between answers, we should output all of them with no order requirement.

For example, if the input to the function is−

 Live Demo

const arr1 = ['a', 'b', 'c', 'd'];
const arr2 = ['d', 'a', 'c'];

Then the output should be −

const output = ['a'];

Output Explanation

Since 'd' and 'a' are common in both the arrays the index sum of 'd' is 3 + 0 = 3 and that of 'a' is 0 + 1 = 1, hence 'a' is the required element.

Example

 Live Demo

Following is the code −

const arr1 = ['a', 'b', 'c', 'd'];
const arr2 = ['d', 'a', 'c'];
const findCommon = (arr1 = [], arr2 = []) => {
   let sum = Infinity
   const map = arr1.reduce((acc, str, index) => {
      acc[str] = index
      return acc
   }, {})
   for (let i = 0; i < arr2.length; i++) {
      const index1 = map[arr2[i]]
      if (index1 >= 0 && index1 + i < sum) {
         sum = index1 + i
      }
   }
   const result = []
   for (let i = 0; i < arr2.length; i++) {
      const index1 = map[arr2[i]]
      if (index1 >= 0 && index1 + i === sum) {
         result.push(arr2[i])
      }
   }
   return result
}
console.log(findCommon(arr1, arr2));

Output

Following is the console output−

['a']

Updated on: 21-Apr-2021

73 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements