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.
1def threeConsecutiveOdds(arr):
2 count = 0
3 for num in arr:
4 if num % 2 != 0:
5 count += 1
6 if count == 3:
7 return True
8 else:
9 count = 0
10 return False
The Python solution uses a simple for loop to iterate over the list. We check each element to see if it is odd, incrementing our count of consecutive odds. If an even is found, we reset the counter. We return true as soon as three consecutive odds are found.
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
For Java, the approach involves iterating with a window of size three, returning true as soon as three consecutive odds are found within the current window.