Converting array into increasing sequence in JavaScript


Increasing Sequence

We define an array as increasing if arr[i] <= arr[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).

Problem

We are required to write a JavaScript function that takes in an array of integers, arr, as the first and the only argument.

Our function should determine whether we can convert this array into an increasing array by modifying at most one element of the array.

If we can do so we should return true, false otherwise.

For example, if the input to the function is

Input

const arr = [8, 3, 3, 7, 9];

Output

const output = true;

Output Explanation

Because we can replace the 8 at index 0 with 1 or 2 to get the desired array.

Example

Following is the code −

 Live Demo

const arr = [8, 3, 3, 7, 9];
   const canConvert = (arr = []) => {
      const find = () => {
         for (let i = 1; i < arr.length; i++) {
            if (arr[i] < arr[i - 1]) {
               return false
            }
         }
         return true
      }
      for (let i = 0; i < arr.length; i++) {
         if (arr[i] < arr[i - 1]) {
            const temp = arr[i]
            arr[i] = arr[i - 1]
            if (find(arr)) {
               return true
            }
            arr[i] = temp
            arr[i - 1] = arr[i]
            return find(arr)
      }
   }
   return true
}
console.log(canConvert(arr));

Output

true

Updated on: 24-Apr-2021

132 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements