Three Consecutive Odds — Solution in Python, Java & C++
Three Consecutive Odds solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on arrays.
Three Consecutive Odds is an easy coding problem on arrays, asked in Amazon and TCS interviews.
- Difficulty: Easy
- Topics: Arrays
- Asked at: Amazon, TCS
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given an integer array arr, return true if there are three consecutive odd numbers in the array.
Example 1
Input: arr = [2,6,4,1]
Output: false
Example 2
Input: arr = [1,2,34,3,4,5,7,23,12]
Output: true
Explanation: The run 5, 7, 23 is three odds in a row.
Example 3
Input: arr = [1,1,1]
Output: true
Constraints
1 <= arr.length <= 401 <= arr[i] <= 1000
Hints for Three Consecutive Odds
Hint 1
Carry a run length that grows on an odd number and resets to zero on an even one.
Hint 2
Return as soon as the run reaches three.
How to solve Three Consecutive Odds
Track the length of the current run of odd numbers and return as soon as it reaches three.
Approach
- Set
run = 0. - For each
x:run = run + 1if odd else0; returntruewhenrun >= 3. - Return
false.
Why it works
A run counter resets on any even value, so reaching three certifies three consecutive odds.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- Use
x % 2 != 0so negative odds count.
Reference solution
Python
def threeConsecutiveOdds(arr) -> bool:
run = 0
for x in arr:
run = run + 1 if x % 2 else 0
if run >= 3:
return True
return FalseJava
public static boolean threeConsecutiveOdds(int[] arr) {
int run = 0;
for (int x : arr) {
run = x % 2 != 0 ? run + 1 : 0;
if (run >= 3) return true;
}
return false;
}C++
bool threeConsecutiveOdds(vector<int>& arr) {
int run = 0;
for (int x : arr) {
run = x % 2 != 0 ? run + 1 : 0;
if (run >= 3) return true;
}
return false;
}JavaScript
var threeConsecutiveOdds = function(arr) {
let run = 0;
for (let i = 0; i < arr.length; i++) {
run = arr[i] % 2 !== 0 ? run + 1 : 0;
if (run >= 3) return true;
}
return false;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 1199 arrays problems · the whole catalogue
Learn the technique: Arrays