- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript: Check if array has an almost increasing sequence
Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
The sequence a0, a1, ..., an is considered to be a strictly increasing if a0 < a1 < ... < an. Sequence containing only one element is also considered to be strictly increasing.
Example
For sequence = [1, 3, 2, 1], the output should be −
almostIncreasingSequence(sequence) = false.
There is no one element in this array that can be removed in order to get a strictly increasing sequence.
For sequence = [1, 3, 2], the output should be −
almostIncreasingSequence(sequence) = true.
We can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, we can remove 2 to get the strictly increasing sequence [1, 3].
Example
Following is the code −
const arr1 = [3, 5, 67, 98, 3]; const arr2 = [4, 3, 5, 67, 98, 3]; const almostIncreasingSequence = sequence => { let removed = 0; let i = 0; let prev = -Infinity; while(removed < 2 && i < sequence.length) { if(sequence[i] > prev) { prev = sequence[i]; }else{ prev = Math.min(prev, sequence[i]); removed++; } i++; } return removed < 2; }; console.log(almostIncreasingSequence(arr1)); console.log(almostIncreasingSequence(arr2));
Output
This will produce the following output on console −
true false
- Related Articles
- How to get almost increasing sequence of integers in JavaScript ?
- Converting array into increasing sequence in JavaScript
- Strictly increasing sequence JavaScript
- Finding nth element of an increasing sequence using JavaScript
- Check if an Array has fixed size or not in C#
- Removing least number of elements to convert array into increasing sequence using JavaScript
- Finding Fibonacci sequence in an array using JavaScript
- How do we check if an object is an array in Javascript?
- How do I check if an array includes an object in JavaScript?
- Check if given array is almost sorted (elements are at-most one position away) in Python
- Form a sequence out of an array in JavaScript
- How to check if a variable is an array in JavaScript?
- How to check if an array contains integer values in JavaScript ?
- How to create an alternately increasing sequence in R?
- Find an element in an array such that elements form a strictly decreasing and increasing sequence in Python
