Three Consecutive Odds Solution in Python


Problem Description

Welcome to the world of odd numbers! The problem at hand is to determine if there are three consecutive odd numbers in a given array. Imagine you’re at a party, and you see three of your friends who are all wearing the same quirky hat. You’d definitely want to take a picture, right? Similarly, we want to find those odd numbers that are hanging out together in the array!

Code Solution


class Solution:
    def threeConsecutiveOdds(self, arr: list[int]) -> bool:
        count = 0
        for a in arr:
            count = 0 if a % 2 == 0 else count + 1
            if count == 3:
                return True
        return False
    

Approach

The approach taken in this code is straightforward. We iterate through the array and maintain a count of consecutive odd numbers. If we encounter an even number, we reset the count to zero. If the count reaches three, we return True, indicating that we found our trio of odd friends. If we finish checking the array without finding three consecutive odds, we return False.

Time and Space Complexity

Time Complexity: O(n), where n is the length of the array. We traverse the array once.

Space Complexity: O(1), as we are using a constant amount of space for the count variable.

Real-World Example

Imagine you’re at a concert, and you see three people in a row dancing like nobody’s watching. You can’t help but take a video of them! In this scenario, the three dancers represent the three consecutive odd numbers. If they were to be interrupted by someone who can’t dance (an even number), you’d have to start looking again.