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] <= 1000This approach involves iterating through the array and counting how many consecutive numbers are odd. If we reach a count of three consecutive odds, we return true immediately. If we finish scanning the array without finding three consecutive odd numbers, we return false.
This C solution iterates through the array with a simple loop. We maintain a count of how many consecutive elements are odd. If the count reaches three, we return true. Otherwise, we reset the count whenever an even number appears. This efficiently determines if there are three consecutive odd numbers.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the array. Space Complexity: O(1) as we use only a constant amount of auxiliary space.
A slightly different approach is using a sliding window of fixed size three. As we move the window along the array, we check if all numbers in the current window are odd, which allows us to efficiently determine if there are three consecutive odds.
This C solution implements a sliding window technique by checking non-overlapping windows of three elements to see if all elements are odd. This allows us to handle the problem in a clean and concise manner.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the array since each element is traversed once. Space Complexity: O(1).
| Approach | Complexity |
|---|---|
| Iterative Approach | Time Complexity: O(n), where n is the length of the array. Space Complexity: O(1) as we use only a constant amount of auxiliary space. |
| Sliding Window Approach | Time Complexity: O(n), where n is the length of the array since each element is traversed once. Space Complexity: O(1). |
Leetcode | 1550. Three Consecutive Odds | Easy | Java Solution • Developer Docs • 1,061 views views
Watch 9 more video solutions →Practice Three Consecutive Odds with our built-in code editor and test cases.
Practice on FleetCode