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,3,5,7]
Output: true
Explanation: [1, 3, 5] are three consecutive odds.
Example 3:
Input: arr = [1, 2, 34, 3, 4, 5, 7, 23, 12]
Output: true
Explanation: [5, 7, 23] are three consecutive odds.
Assuming general constraints of LeetCode problems:
true
.false
.Let’s implement this strategy in Python.
def three_consecutive_odds(arr):
count = 0
for num in arr:
if num % 2 != 0: # Check if the number is odd
count += 1
if count == 3:
return True
else:
count = 0 # Reset the counter if the number is even
return False
# Test examples
print(three_consecutive_odds([2,6,4,1])) # Output: False
print(three_consecutive_odds([1,3,5,7])) # Output: True
print(three_consecutive_odds([1, 2, 34, 3, 4, 5, 7, 23, 12])) # Output: True
This solution efficiently checks for three consecutive odd numbers in the array within linear time.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?