Problem
Question
Given an integer array
arr, returntrueif there are three consecutive odd numbers in the array. Otherwise, returnfalse.
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
Solutions
1. Brute force
Time Complexity: | Space Complexity:
To solve the problem, we can check every possible trio of consecutive numbers. If all three numbers in a trio are odd, we return True. To check if a number is odd, we simply check if the remainder when the number is divided by 2 is 1.
class Solution:
def threeConsecutiveOdds(self, arr: List[int]) -> bool:
for i in range(len(arr) - 2):
if arr[i] % 2 == 1 and arr[i+1] % 2 == 1 and arr[i+2] % 2 == 1:
return True
return False
Alternatively, we can check if the product of three consecutive numbers is odd.
class Solution:
def threeConsecutiveOdds(self, arr: List[int]) -> bool:
for i in range(len(arr) - 2):
if (arr[i] * arr[i+1] * arr[i+2]) % 2 == 1:
return True
return False
🏆 2. Counting
Time Complexity: | Space Complexity:
A more optimized solution involves counting the odd numbers as we iterate through the given array. We increment the counter each time we encounter an odd number. If the counter reaches 3, we return True. If a number is not odd, we reset the counter to 0.
class Solution:
def threeConsecutiveOdds(self, arr: List[int]) -> bool:
count = 0
for num in arr:
if num % 2 == 1:
count += 1
if count == 3:
return True
else:
count = 0
return False