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.
1function threeConsecutiveOdds(arr) {
2 let count = 0;
3 for (let num of arr) {
4 if (num % 2 !== 0) {
5 count++;
6 if (count === 3) return true;
7 } else {
8 count = 0;
9 }
10 }
11 return false;
12}
In JavaScript, we use a for-of loop to iterate through the array, checking each number to see if it's odd. The counter increases for each odd number found in a sequence and resets on evens. We return true as soon as the counter reaches three.
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 public bool ThreeConsecutiveOdds(int[] arr) {
for (int i = 0; i <= arr.Length - 3; i++) {
if (arr[i] % 2 != 0 && arr[i+1] % 2 != 0 && arr[i+2] % 2 != 0) {
return true;
}
}
return false;
}
}
With C#, this solution utilizes a for loop, moving a window of size three across the array, checking for three consecutive odds in each pass.