Three Consecutive Odds Solution in Java

Navigate to Other Solutions

Problem Description

So, you think counting odd numbers is a piece of cake? Well, welcome to the “Three Consecutive Odds” problem on LeetCode, where we take counting to a whole new level! The task is simple: given an array of integers, you need to determine if there are three consecutive odd numbers lurking in there.

Imagine you’re at a party, and you see three friends who are all wearing the same odd socks. You can’t help but wonder if they planned it or if it’s just a coincidence. That’s exactly what we’re doing here—looking for those odd socks (or numbers) in the array!

Code Solution

Here’s the Java solution that will help you find those sneaky odd numbers:


class Solution {
  public boolean threeConsecutiveOdds(int[] arr) {
    int count = 0;
    for (final 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 hit 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 consecutive odds, we return false. Simple, right?

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 our count variable.

Real-World Example

Picture this: you’re at a sports event, and you notice three fans in a row, all wearing the same odd jerseys. You can’t help but think, “What are the odds?” Well, in our case, we want to find out if there are three consecutive odd numbers in an array, just like those fans at the game!

Similar Problems

If you enjoyed this problem, you might want to check out these similar challenges: