We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Three Consecutive Odds

Number: 1293

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given an integer array arr, determine if there exist three consecutive odd numbers in the array. Return true if such a sequence exists and false otherwise.


Key Insights

  • Iterate through the array while counting consecutive odd numbers.
  • Reset the count if an even number is encountered.
  • Return true as soon as the count reaches three.
  • Use a single pass through the array (O(n) time complexity).

Space and Time Complexity

Time Complexity: O(n) - Each element in the array is visited only once. Space Complexity: O(1) - Only a few extra variables are used regardless of input size.


Solution

We traverse the array with a simple loop. A counter is maintained to track consecutive odd numbers. For every odd number encountered, we increment the counter; if an even number is encountered, the counter is reset to zero. If the counter reaches three at any point, we immediately return true. If we complete the loop without the counter reaching three, we return false. The approach uses constant extra space and a single loop, ensuring optimal performance.


Code Solutions

# Define a function to check three consecutive odds
def threeConsecutiveOdds(arr):
    # Initialize the counter for consecutive odds
    consecutive_odd_count = 0
    # Loop through each number in the array
    for num in arr:
        # Check if the current number is odd
        if num % 2 == 1:
            # Increment the counter
            consecutive_odd_count += 1
            # If three consecutive odds are found, return True
            if consecutive_odd_count == 3:
                return True
        else:
            # Reset counter when the number is even
            consecutive_odd_count = 0
    # Return False if no three consecutive odds were found
    return False

# Example usage:
# print(threeConsecutiveOdds([1, 2, 34, 3, 4, 5, 7, 23, 12]))  # Output: True
← Back to All Questions