Taro Logo

Three Consecutive Odds

Easy
Amazon logo
Amazon
1 view
Topics:
Arrays

Given an integer array arr, determine whether there exist three consecutive odd numbers within the array. Return true if such a sequence exists, and false otherwise.

Examples:

  1. Input: arr = [2, 6, 4, 1] Output: false Explanation: There are no three consecutive odd numbers in the array.

  2. Input: arr = [1, 2, 34, 3, 4, 5, 7, 23, 12] Output: true Explanation: The subsequence [5, 7, 23] consists of three consecutive odd numbers.

Constraints:

  • The array arr will have a length between 1 and 1000 (inclusive).
  • Each element arr[i] in the array will be an integer between 1 and 1000 (inclusive).

How would you approach this problem to efficiently check for the existence of three consecutive odd numbers in the given array?

Solution


Naive Approach

The most straightforward approach is to iterate through the array and check, for each index, if the current element and the next two elements are odd. This method has a time complexity of O(n) because it iterates through the array once.

Code (Naive)

def three_consecutive_odds_naive(arr):
    for i in range(len(arr) - 2):
        if arr[i] % 2 != 0 and arr[i+1] % 2 != 0 and arr[i+2] % 2 != 0:
            return True
    return False

Time and Space Complexity (Naive)

  • Time Complexity: O(n), where n is the length of the array.
  • Space Complexity: O(1), as it uses a constant amount of extra space.

Optimal Approach

An optimized approach improves readability while keeping the time complexity the same. Instead of checking for three consecutive odds in each iteration, we can maintain a counter. Increment the counter if an odd number is found, and reset it if an even number is encountered. If the counter reaches 3, we return true.

Code (Optimal)

def three_consecutive_odds_optimal(arr):
    count = 0
    for num in arr:
        if num % 2 != 0:
            count += 1
            if count == 3:
                return True
        else:
            count = 0
    return False

Time and Space Complexity (Optimal)

  • Time Complexity: O(n), where n is the length of the array.
  • Space Complexity: O(1), as it uses a constant amount of extra space.

Edge Cases

  • Empty array: Should return false since there are no numbers to evaluate.
  • Array with fewer than three elements: Should return false since there can't be three consecutive odd numbers.
  • Array with all even numbers: Should return false.
  • Array with three or more consecutive odd numbers at the beginning, middle, or end: Should return true.
  • Array with mixed odd and even numbers, but no three consecutive odds: Should return false.