Given an integer array arr
, determine whether there exist three consecutive odd numbers within the array. Return true
if such a sequence exists, and false
otherwise.
Examples:
Input: arr = [2, 6, 4, 1]
Output: false
Explanation: There are no three consecutive odd numbers in the array.
Input: arr = [1, 2, 34, 3, 4, 5, 7, 23, 12]
Output: true
Explanation: The subsequence [5, 7, 23]
consists of three consecutive odd numbers.
Constraints:
arr
will have a length between 1 and 1000 (inclusive).arr[i]
in the array will be an integer between 1 and 1000 (inclusive).How would you approach this problem to efficiently check for the existence of three consecutive odd numbers in the given array?
The most straightforward approach is to iterate through the array and check, for each index, if the current element and the next two elements are odd. This method has a time complexity of O(n) because it iterates through the array once.
def three_consecutive_odds_naive(arr):
for i in range(len(arr) - 2):
if arr[i] % 2 != 0 and arr[i+1] % 2 != 0 and arr[i+2] % 2 != 0:
return True
return False
An optimized approach improves readability while keeping the time complexity the same. Instead of checking for three consecutive odds in each iteration, we can maintain a counter. Increment the counter if an odd number is found, and reset it if an even number is encountered. If the counter reaches 3, we return true
.
def three_consecutive_odds_optimal(arr):
count = 0
for num in arr:
if num % 2 != 0:
count += 1
if count == 3:
return True
else:
count = 0
return False
false
since there are no numbers to evaluate.false
since there can't be three consecutive odd numbers.false
.true
.false
.