Problem
Given an integer array arr
, return true
if there are three consecutive odd numbers in the array. Otherwise, return false
.
Examples
Example 1:
Input: arr = [2,6,4,1]
Output: false
Explanation: There are no three consecutive odds.
Example 2:
Input: arr = [1,2,34,3,4,5,7,23,12]
Output: true
Explanation: [5,7,23] are three consecutive odds.
Solution
Method 1 - Simply count and iteration
We can follow following steps:
- Iterates over the array,
- maintaining a counter
cnt
- Reset to
cnt
to 0 whenever an even number is encountered. - If an odd number is found, the counter is incremented.
- If the counter reaches 3, indicating three consecutive odd numbers, the method returns
true
.
- If the counter reaches 3, indicating three consecutive odd numbers, the method returns
- maintaining a counter
- If the loop completes without finding such a sequence, the method returns
false
.
Here is the video explanation:
Code
Java
class Solution {
public boolean threeConsecutiveOdds(int[] arr) {
for (int i = 0, cnt = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
cnt = 0;
} else if (++cnt == 3) {
return true;
}
}
return false;
}
}
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)