Three Consecutive Odds Solution in C++

Navigate to Other Solutions



Problem Description

Welcome to the whimsical world of odd numbers! The problem at hand is to determine if there are three consecutive odd numbers in a given array. Yes, you heard it right! Three odd numbers in a row, like a trio of clowns at a circus, juggling their way through life.

Imagine you’re at a party, and you spot three friends who are all wearing mismatched socks (because who needs matching socks, right?). If you can find these three oddballs in a row, you win the game! But if they’re scattered like confetti, well, better luck next time!

Code Solution


class Solution {
 public:
  bool threeConsecutiveOdds(vector& arr) {
    int count = 0;
    for (const int a : arr) {
      count = a % 2 == 0 ? 0 : count + 1;
      if (count == 3)
        return true;
    }
    return false;
  }
};

Approach

The approach here is as straightforward as counting your fingers. We loop through the array and keep a count of consecutive odd numbers. If we encounter an even number, we reset our count. If our count reaches three, we declare victory and return true. If we finish the loop without hitting three, we return false. Simple, right?

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n), where n is the number of elements in the array. We traverse the array once.
Space Complexity O(1), as we are using a constant amount of space for our count variable.

Real-World Example

Think of a basketball game where players are trying to score three consecutive baskets. If they manage to do so, they get a bonus! But if they miss one, they have to start over. Similarly, in our problem, we are looking for three consecutive odd numbers. If we find them, we win; if not, we keep searching!

Similar Problems

If you enjoyed this problem, you might also like these:

  • Two Sum Solution in C++