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.


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]


Solution tested in REPL:


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