Strictly Increasing Sequence
A sequence is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1].
Problem
We are required to write a JavaScript function that takes in two arrays of numbers, arr1 and arr2 as the first and the second argument respectively.
We can swap any number of elements from arr1 to arr2, that happen to live on the same indices. It means we can swap arr1[i] with arr2[i]. Our function should return the minimum number of swaps to make both sequences strictly increasing.
For example, if the input to the function is
Input
const arr1 = [1, 3, 5, 4]; const arr2 = [1, 2, 3, 7];
Output
const output = 1;
Output Explanation
Because if we swap arr1[3] with arr2[3], both the arrays will become strictly increasing.
Example
Following is the code −
const arr1 = [1, 3, 5, 4]; const arr2 = [1, 2, 3, 7]; const findSwaps = (arr1 = [], arr2 = []) => { let map = { true: 1, false: 0, }; for (let i = 1; i < arr1.length; i++) { const current = { true: Infinity, false: Infinity, } if (arr1[i] > arr2[i - 1] && arr2[i] > arr1[i - 1]) { current.true = Math.min( current.true, map.false + 1, ) current.false = Math.min( current.false, map.true) } if (arr2[i] > arr2[i - 1] && arr1[i] > arr1[i - 1]) { current.true = Math.min( current.true, map.true + 1, ) current.false = Math.min( current.false, map.false) } map = current } return Math.min( map.false, map.true) } console.log(findSwaps(arr1, arr2));
Output
1