algoadvance

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,3,5,7]
Output: true
Explanation: [1, 3, 5] are three consecutive odds.

Example 3:

Input: arr = [1, 2, 34, 3, 4, 5, 7, 23, 12]
Output: true
Explanation: [5, 7, 23] are three consecutive odds.

Clarifying Questions

  1. Is the input array always non-empty?
  2. What is the size range of the input array?
  3. Can the input array contain negative numbers?

Assuming general constraints of LeetCode problems:

Strategy

  1. Traverse through the array while checking each number to see if it is odd.
  2. Maintain a counter that counts consecutive odd numbers.
  3. Reset the counter to zero whenever an even number is encountered.
  4. If the counter reaches 3 at any point, return true.
  5. If the entire array is traversed and no three consecutive odd numbers are found, return false.

Code

Let’s implement this strategy in Python.

def three_consecutive_odds(arr):
    count = 0
    for num in arr:
        if num % 2 != 0:  # Check if the number is odd
            count += 1
            if count == 3:
                return True
        else:
            count = 0  # Reset the counter if the number is even
    return False

# Test examples
print(three_consecutive_odds([2,6,4,1]))  # Output: False
print(three_consecutive_odds([1,3,5,7]))  # Output: True
print(three_consecutive_odds([1, 2, 34, 3, 4, 5, 7, 23, 12]))  # Output: True

Time Complexity

This solution efficiently checks for three consecutive odd numbers in the array within linear time.

Try our interview co-pilot at AlgoAdvance.com