Sponsored
Sponsored
This approach involves iterating through the array and counting how many consecutive numbers are odd. If we reach a count of three consecutive odds, we return true immediately. If we finish scanning the array without finding three consecutive odd numbers, we return false.
Time Complexity: O(n), where n is the length of the array. Space Complexity: O(1) as we use only a constant amount of auxiliary space.
1class Solution {
2 public boolean threeConsecutiveOdds(int[] arr) {
3 int count = 0;
4 for (int num : arr) {
5 if (num % 2 != 0) {
6 count++;
7 if (count == 3) return true;
8 } else {
9 count = 0;
10 }
11 }
12 return false;
13 }
14}
In Java, we iterate over the array using an enhanced for-loop, checking if each number is odd and maintaining a count of consecutive odd numbers. An even number resets the count, and we return early if we find three odd numbers in a row.
A slightly different approach is using a sliding window of fixed size three. As we move the window along the array, we check if all numbers in the current window are odd, which allows us to efficiently determine if there are three consecutive odds.
Time Complexity: O(n), where n is the length of the array since each element is traversed once. Space Complexity: O(1).
1
In Python, this approach involves checking each possible triplet (or window of size three) as we move through the array, returning true if we hit a triplet of odd numbers.