Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Maximum absolute difference of the length of strings from two arrays in JavaScript
Problem
We are required to write a JavaScript function that takes in two arrays, a1 and a2 of strings. Each string is composed with letters from a to z. Let x be any string in the first array and y be any string in the second array.
Our function should find the value of ?
max(abs(length(x) ? length(y)))
Approach
To find the maximum absolute difference, we need to:
- Find the longest string from both arrays
- Find the shortest string from both arrays
- Calculate the absolute difference between max and min lengths
Example
Following is the code ?
const arr1 = ["hoqq", "bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"];
const arr2 = ["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"];
const findMaxAbsDiff = (arr1 = [], arr2 = []) => {
if(arr1.length === 0 || arr2.length === 0){
return -1;
};
let l1 = arr1.map(str => str.length)
let l2 = arr2.map(str => str.length)
return Math.max(Math.max(...l1) - Math.min(...l2), Math.max(...l2) - Math.min(...l1));
};
console.log(findMaxAbsDiff(arr1, arr2));
Output
13
How It Works
The function works by:
- First checking if either array is empty and returning -1
- Converting both arrays to arrays of string lengths using
map() - Finding maximum and minimum lengths from both arrays
- Calculating two possible differences: max(arr1) - min(arr2) and max(arr2) - min(arr1)
- Returning the maximum of these two differences
Step-by-Step Calculation
const arr1 = ["hoqq", "bbllkw", "oox"];
const arr2 = ["cccooommaaqqoxii", "ggg"];
// Array 1 lengths: [4, 6, 3] ? max: 6, min: 3
// Array 2 lengths: [16, 3] ? max: 16, min: 3
// Two possible differences:
// max(arr1) - min(arr2) = 6 - 3 = 3
// max(arr2) - min(arr1) = 16 - 3 = 13
console.log("Array 1 lengths:", arr1.map(s => s.length));
console.log("Array 2 lengths:", arr2.map(s => s.length));
console.log("Maximum absolute difference:", Math.max(6 - 3, 16 - 3));
Array 1 lengths: [ 4, 6, 3 ] Array 2 lengths: [ 16, 3 ] Maximum absolute difference: 13
Conclusion
The maximum absolute difference is found by comparing the longest string from one array with the shortest from the other. This approach ensures we capture the greatest possible length difference between any two strings from the different arrays.
Advertisements
