Three Consecutive Odds
Problem
Return true if there are three consecutive odd numbers in arr; else false.
arr = [1,2,34,3,4,5,7,23,12]truedef three_consecutive_odds(arr):
run = 0
for x in arr:
run = run + 1 if x % 2 else 0
if run == 3: return True
return False
function threeConsecutiveOdds(arr) {
let r = 0;
for (const x of arr) { r = (x & 1) ? r + 1 : 0; if (r === 3) return true; }
return false;
}
class Solution {
public boolean threeConsecutiveOdds(int[] arr) {
int r = 0;
for (int x : arr) { r = (x & 1) == 1 ? r + 1 : 0; if (r == 3) return true; }
return false;
}
}
bool threeConsecutiveOdds(vector& arr) {
int r = 0;
for (int x : arr) { r = (x & 1) ? r + 1 : 0; if (r == 3) return true; }
return false;
}
Explanation
We just need to know if three odd numbers in a row appear anywhere. The simplest way is to keep a running counter of how many odds we have seen back to back as we scan once.
The variable run counts the current streak of odds. For each value x, if x is odd we do run + 1; if it is even the streak is broken so we reset run to 0.
The moment run hits 3 we can return True immediately — we have found three consecutive odds and there is no reason to keep looking. If the loop finishes without that happening, we return False.
Resetting on every even is the key: it guarantees the count only ever reflects an unbroken run of odds, not odds scattered around the array.
Example: [1,2,34,3,4,5,7,23,12]. The counter keeps resetting until we reach 5,7,23, where run climbs 1, 2, 3 and we return true.