Three Consecutive Odds - Problem

Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false.

An odd number is any integer that is not divisible by 2.

Input & Output

Example 1 — Basic Case
$ Input: arr = [2,1,3,5,8]
Output: true
💡 Note: The elements at indices 1, 2, and 3 are [1,3,5] which are three consecutive odd numbers
Example 2 — No Three Consecutive
$ Input: arr = [1,2,3,4,5]
Output: false
💡 Note: No three consecutive elements are all odd. We have [1,2,3] but 2 is even
Example 3 — All Odds
$ Input: arr = [1,3,5,7,9]
Output: true
💡 Note: The first three elements [1,3,5] are all odd and consecutive

Constraints

  • 1 ≤ arr.length ≤ 1000
  • -1000 ≤ arr[i] ≤ 1000

Visualization

Tap to expand
Three Consecutive Odds INPUT arr = [2, 1, 3, 5, 8] 2 i=0 1 i=1 3 i=2 5 i=3 8 i=4 EVEN ODD ODD ODD EVEN 3 consecutive odds! Find if array has 3 consecutive odd numbers ALGORITHM STEPS 1 Initialize counter = 0 Track consecutive odds 2 Loop through array Check each element 3 If odd: counter++ If even: counter = 0 4 If counter == 3 Return true Counter Trace: 0 2 1 1 2 3 3 5 -- 8 Counter reached 3 at index 3! FINAL RESULT true Found! Consecutive Odds Found: 1 3 5 At indices [1, 2, 3] 1 % 2 = 1 (odd) OK 3 % 2 = 1 (odd) OK 5 % 2 = 1 (odd) OK Key Insight: The Counter Approach uses O(1) space by maintaining a running count of consecutive odd numbers. When an even number is encountered, the counter resets to 0. If counter reaches 3, we found our answer. Time Complexity: O(n) | Space Complexity: O(1) TutorialsPoint - Three Consecutive Odds | Counter Approach
Asked in
Amazon 25 Apple 15
23.5K Views
Medium Frequency
~10 min Avg. Time
842 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen