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.
1#include <stdbool.h>
2
3bool threeConsecutiveOdds(int* arr, int arrSize) {
4 int count = 0;
5 for (int i = 0; i < arrSize; i++) {
6 if (arr[i] % 2 != 0) {
7 count++;
8 if (count == 3) return true;
9 } else {
10 count = 0;
11 }
12 }
13 return false;
14}
This C solution iterates through the array with a simple loop. We maintain a count of how many consecutive elements are odd. If the count reaches three, we return true. Otherwise, we reset the count whenever an even number appears. This efficiently determines if there are three consecutive odd numbers.
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#include <vector>
2using namespace std;
bool threeConsecutiveOdds(vector<int>& arr) {
for (int i = 0; i <= arr.size() - 3; i++) {
if (arr[i] % 2 != 0 && arr[i+1] % 2 != 0 && arr[i+2] % 2 != 0) {
return true;
}
}
return false;
}
In C++, we use a simple for loop iterating over possible starting points of our windows and check for three consecutive odds in each window. The condition ensures we do not overshoot the array bounds.