2023-06-10

 10 Jun 2023

Given an Array of Integers, determine whether the Array could become Non-Decreasing

Taken from DailyCodingProblem

Given an array of integers, write a function to determine whether the array could become non-decreasing by modifying at most 1 element.

For example, given the array [10, 5, 7], you should return true, since we can modify the 10 into a 1 to make the array non-decreasing.

Given the array [10, 5, 1], you should return false, since we can’t modify any one element to get a non-decreasing array.

Solution

This is the answer I came up with:

function couldBeNonDecreasing(arr: Array<number>): boolean {
  // As long as the first element is larger than the second,
  // and the second larger than the third, always return false
  if (arr[0] > arr[1] && arr[1] > arr[2]) {
    return false
  }
    
  // Otherwise, return true
  return true
}

If at most one element can be changed, then the maximum array length is always 3. Also, non-decreasing means the array items are less than or equal to each other in ascending order, i.e. arr[0] <= arr[1] && arr[1] <= arr[2]

Testing

Solution tested in REPL:

https://www.typescriptlang.org/play?ssl=10&ssc=2&pln=1&pc=1#code/GYVwdgxgLglg9mABBOIA2ATAQgUwHIIAiOEATjgIYDOMYA5gBQWmkBciAgixQJ4A8YEAFsARjlIA+AJTsRcOGkpIA3gFgAUIkQB6bZyqI0COomqIoACxyJgMUlSiIcioTjCOYBtMzrjzFiiRLayoSBAwAGg0tXVMwDH8QsPjDHz9LQMT-O0jTNAB3XgNyKBBSJGAKNFDoxBhgRCYWAG0ABgBdRAlTFoBGToAyAZ7SZv6ukeaAJnapRDVNLUQSsoqqmsWAX1qtWtiAeWDSfM8cCOWcUvLzUhAcWpXrqFv79W31DRQwKgUcADojIxaih0Nh8EQSORqLRGGNWucAKznfpSc6xSrVV5aEGYXAEMDEMiUGj0BhwxHnADsszRemed0QzQALBTENTgahceCCZDiTCyb1WSjaTcGWNkYh+hzQXiIUToaTmgBOZEAZmRNJ0dJejJVkvVkqZ7WlXPxhKhJNhBsFiA6qK1NnWrykGiAA

Copyright © Paramdeo Singh · All Rights Reserved · Built with Jekyll

This node last updated November 7, 2023 and is permanently morphing...

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems