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 <vector>
2using namespace std;
3
4bool threeConsecutiveOdds(vector<int>& arr) {
5 int count = 0;
6 for (int num : arr) {
7 if (num % 2 != 0) {
8 count++;
9 if (count == 3) return true;
10 } else {
11 count = 0;
12 }
13 }
14 return false;
15}
The C++ solution follows the same logic as its C counterpart. It uses a range-based for loop to iterate over the array, keeping a count of consecutive odd numbers and resetting it upon encountering an even number.
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.