algoadvance

Leetcode 1550. Three Consecutive Odds

Problem Statement

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

Clarifying Questions

  1. Input Constraints:
    • What is the size range of the array arr?
    • What range of integers does the array arr contain?
  2. Behavioral Questions:
    • Should the function handle an empty array or arrays with less than three elements?

Based on the standard problem statement, we’ll assume:

Code

Here is the Java code to solve the problem:

public class Solution {
    public boolean threeConsecutiveOdds(int[] arr) {
        int consecutiveOdds = 0;
        
        for (int num : arr) {
            if (num % 2 != 0) {
                consecutiveOdds++;
                if (consecutiveOdds == 3) {
                    return true;
                }
            } else {
                consecutiveOdds = 0;
            }
        }
        
        return false;
    }
    
    public static void main(String[] args) {
        Solution sol = new Solution();
        
        int[] arr1 = {2, 6, 4, 1};        // false
        int[] arr2 = {1, 3, 5, 7};        // true
        int[] arr3 = {1, 2, 3, 5, 7};     // false
        int[] arr4 = {1, 3, 5};           // true
        int[] arr5 = {};                  // false
        
        System.out.println(sol.threeConsecutiveOdds(arr1));
        System.out.println(sol.threeConsecutiveOdds(arr2));
        System.out.println(sol.threeConsecutiveOdds(arr3));
        System.out.println(sol.threeConsecutiveOdds(arr4));
        System.out.println(sol.threeConsecutiveOdds(arr5));
    }
}

Strategy

  1. Initialize a counter consecutiveOdds to keep track of consecutive odd numbers.
  2. Iterate over each element in the array:
    • If the current element is odd (num % 2 != 0), increment the counter.
    • If the counter reaches 3, return true.
    • If the current element is even, reset the counter to 0.
  3. If the loop completes without finding three consecutive odd numbers, return false.

Time Complexity

The time complexity of this solution is O(n), where n is the length of the array. This is because we need to traverse the array once to check for the condition. The space complexity is O(1) since we are only using a few fixed-size variables regardless of the array size.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI