'Stuck at Python Solution for AlmostIncreasingSequence (CodeSignal)
I was working on this particular task given by CodeSignal which had the purpose of creating a program that would go through a given list with numbers and check if the numbers were increasing and/or "almost increasing". What this means is that, for example, if the list was (1, 3, 2, 1) then the program should return false due to the fact that, while it does appear to increase, it also takes a dip back to 1, returning false. Getting true on the output would require the list incrementing up normally, or almost incrementing up like (1, 3, 2, 4).
I created a code for this through research and Youtube videos, and I actually understood how the code worked and tried it out on Python, however only getting 12/19 correct. I did think this code would go through and ace all the 19 tests but it turns out it had an issue within it and would like to know how I could fix this. The code:
def almostIncreasingSequence(sequence):
count = 0
for i in range(0, len(sequence)-1):
if sequence[i] <= sequence[i-1]:
count +=1
if sequence[i] <= sequence[i-2] and sequence[i+1] <= sequence[i-1]:
return False
return count <= 1
The outputs:
Solution 1:[1]
I have tried to give the best solution possible with me but unfortunately ended up with time limit exceeded for last 4 test cases.
Explanation each time I tried with excepting one element from an array and checked if it is in sorted order or not and thus i continued it until last if i did not found any such possible arrays i returned false
def solution(sequence):
if sorted(set(sequence)) == sequence :
return True
for i in range(len(sequence)):
temp = sequence[:i]+sequence[i+1:]
if sorted(set(temp)) == temp :
return True
return False
Solution 2:[2]
def isIncreasing(sequence):
return sorted(set(sequence)) == sequence
def isAlmostIncreasing(sequence):
#(optional)
#if isIncreasing(sequence) :
# return True
for i in range(len(sequence) - 1):
if sequence[i] >= sequence[i+1]:
temp, temp2 = sequence[:], sequence[:]
del temp[i]
del temp2[i+1]
return isIncreasing(temp) or isIncreasing(temp2)
return True
First, if sequence is already
IncreasingSequencethen no need to check individual data.(optional)but if it's not:
- find first wrong pair at index
i&i+1. (if no wrong pair found, then sequence has no issue.) - if we remove one of them, check will we get proper result in remaining sequence?
- find first wrong pair at index
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bharadwaz Bairu |
| Solution 2 | b m gevariya |


