Three Consecutive Odds Problem
#1550
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1550.
Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false.
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.
Constraints:
1 <= arr.length <= 10001 <= arr[i] <= 1000
Solution
Approach: Count the Current Run of Odds
Walk through the array once and keep run, the number of odd values in a row that end at the current position:
- If
xis odd,rungrows by one. - If
xis even, the run is broken andrungoes back to0.
As soon as run reaches 3, three consecutive odd numbers have been found and we can return true right away. If the loop ends without that, the answer is false.
Complexity: O(n) time and O(1) extra space.
class Solution:
def threeConsecutiveOdds(self, arr: List[int]) -> bool:
run = 0 # length of the run of odd numbers that ends here
for x in arr:
run = run + 1 if x % 2 == 1 else 0
if run == 3:
return True
return False