Program to check all 1s are present one after another or not in Python

Suppose we have a list of numbers called nums that contains at least one element whose value is 1. We have to check whether all the 1s appear consecutively or not.

So, if the input is like nums = [8, 2, 1, 1, 1, 3, 5], then the output will be True.

Algorithm

To solve this, we will follow these steps −

  • visited := 0

  • for each x in nums, do

    • if x is same as 1, then

      • if visited is same as 2, then

        • return False

      • visited := 1

    • otherwise when visited is non-zero, then

      • visited := 2

  • return True

Example

Let us see the following implementation to get better understanding ?

def solve(nums):
    visited = 0
    for x in nums:
        if x == 1:
            if visited == 2:
                return False
            visited = 1
        elif visited:
            visited = 2
    return True

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

How It Works

The algorithm uses a state variable visited to track three states:

  • 0: Haven't encountered any 1s yet

  • 1: Currently in a sequence of 1s

  • 2: Already finished a sequence of 1s

If we encounter a 1 after state 2, it means we have non-consecutive 1s, so we return False.

Testing with Different Cases

def solve(nums):
    visited = 0
    for x in nums:
        if x == 1:
            if visited == 2:
                return False
            visited = 1
        elif visited:
            visited = 2
    return True

# Test cases
test_cases = [
    [8, 2, 1, 1, 1, 3, 5],    # True - consecutive 1s
    [1, 1, 2, 1, 1],          # False - non-consecutive 1s
    [1, 1, 1, 1],             # True - all consecutive 1s
    [2, 3, 1, 4, 5]           # True - single 1
]

for i, nums in enumerate(test_cases, 1):
    result = solve(nums)
    print(f"Test {i}: {nums} ? {result}")
Test 1: [8, 2, 1, 1, 1, 3, 5] ? True
Test 2: [1, 1, 2, 1, 1] ? False
Test 3: [1, 1, 1, 1] ? True
Test 4: [2, 3, 1, 4, 5] ? True

Conclusion

This solution efficiently checks if all 1s appear consecutively using a simple state machine approach. The algorithm runs in O(n) time with O(1) space complexity.

Updated on: 2026-03-26T15:10:38+05:30

207 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements