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 <= 1000
1 <= arr[i] <= 1000
Approach 01:
-
C++
-
Python
#include <bits/stdc++.h> using namespace std; class Solution { public: bool threeConsecutiveOdds(vector<int>& arr) { int result = 0; for(int i=0; i < arr.size(); i++){ int n = arr[i]; if(n%2 != 0){ result++; } else{ result = 0; } if(result == 3){ return true; } } return false; } };
from typing import * class Solution: def threeConsecutiveOdds(self, arr: List[int]) -> bool: result = 0 for n in arr: if(n%2 != 0): result += 1 else: result = 0 if(result == 3): return True return False
Time Complexity
- The function
threeConsecutiveOdds
iterates through the arrayarr
exactly once. - The main operations inside the loop include:
- Checking if a number is odd.
- Incrementing or resetting the
result
counter. - Checking if
result
equals 3.
- Each of these operations takes constant time,
O(1)
. - Since the loop runs for
n
iterations, wheren
is the size of the arrayarr
, the time complexity isO(n)
.
Space Complexity
- The space complexity is determined by the amount of extra space used relative to the input size.
- The
result
variable is an integer that takes constant space,O(1)
. - The function does not use any additional data structures whose size depends on the input size; it only uses a few variables.
- Therefore, the space complexity is
O(1)
.