Program to check whether list is alternating increase and decrease or not in Python

Suppose we have a list of numbers called nums. We have to check whether the list alternates starting from strictly increasing then strictly decreasing and then strictly increasing and so on. If the list is only strictly increasing, it will also be considered valid.

So, if the input is like nums = [2, 4, 8, 7, 5, 1, 5, 7, 2, 1], then the output will be True, because [2,4,8] are increasing, then [7,5,1] is decreasing, then again [5,7] is increasing and [2,1] is decreasing.

Algorithm

To solve this, we will follow these steps ?

  • If nums[1] <= nums[0], then return False (must start increasing)
  • For each element in the list, check if any two consecutive elements are equal
  • If any consecutive elements are equal, return False
  • Otherwise, return True

Implementation

Let us see the following implementation to get better understanding ?

def solve(nums):
    if nums[1] <= nums[0]:
        return False
    
    for i in range(len(nums)):
        if i - 1 >= 0:
            if nums[i] == nums[i - 1]:
                return False
    
    return True

nums = [2, 4, 8, 7, 5, 1, 5, 7, 2, 1]
print(solve(nums))
True

How It Works

The algorithm works by ensuring two key conditions ?

  • Starting condition: The sequence must begin with an increasing pattern
  • No duplicates: No two consecutive elements can be equal for strict alternation

Additional Examples

Let's test with different cases ?

def solve(nums):
    if nums[1] <= nums[0]:
        return False
    
    for i in range(len(nums)):
        if i - 1 >= 0:
            if nums[i] == nums[i - 1]:
                return False
    
    return True

# Test cases
test1 = [1, 3, 2, 4]  # Valid alternating
test2 = [1, 2, 3, 4]  # Valid strictly increasing
test3 = [4, 3, 2, 1]  # Invalid (starts decreasing)
test4 = [1, 3, 3, 2]  # Invalid (has duplicates)

print(f"[1, 3, 2, 4]: {solve(test1)}")
print(f"[1, 2, 3, 4]: {solve(test2)}")
print(f"[4, 3, 2, 1]: {solve(test3)}")
print(f"[1, 3, 3, 2]: {solve(test4)}")
[1, 3, 2, 4]: True
[1, 2, 3, 4]: True
[4, 3, 2, 1]: False
[1, 3, 3, 2]: False

Conclusion

This algorithm efficiently checks for alternating increase−decrease patterns by ensuring the sequence starts increasing and contains no consecutive equal elements. The solution works for both strictly increasing sequences and proper alternating patterns.

Updated on: 2026-03-26T16:38:24+05:30

900 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements