Hello World Master

Tutorials, articles and quizzes on Software Development

Algorithms > Articles

Almost increasing sequence problem

The almost increasing sequence problem from code signal wants us to see if an array is ordered in an increasing sequence, as in, value i cannot be equal to or greater than value i+1

If there is an instance where this rule is broken, we can forgive it only one time but no more.

The first thing we want to do is create a counter that increments when array element i is less than i-1.

The next thing we want to do is iterate through our given array

var counter = 0;
for(var i = 0; i < arr.length; i++) {
  
}

Inside this array we’re going check if arr[i-1] is greater or equal to arr[i]

var counter = 0;
for(var i = 0; i < arr.length; i++) {
  if(arr[i-1] >= arr[i]) counter++;
  if(counter > 1) return false;
}

We’re not done yet though, the last thing we want to do is put ourselves in a situation where i doesn’t exist and i-1 doesn’t exist.

If in both of those cases the smaller index has a greater value, then we know this array is not an almost increasing sequence because whether we remove i or i-1 wont make a difference, we would need at least one of these two situations to follow the rules of our sequence for it to potentially be an almost increasing sequence.

Remember, we’re only allowed to remove one element from this array.

var counter = 0;
for(var i = 0; i < arr.length; i++) {
  if(arr[i-1] >= arr[i]) counter++;
  if(counter > 1) return false;
  if(arr[i-2] >= arr[i] && arr[i-1] >= arr[i+1]) return false;
}