LeetCode 1550. Three Consecutive Odds Java Solution

·

1 min read

Problem Description

  • Problem: Check if there are three consecutive odd numbers in the given integer array. If the three consecutive odd numbers exist, return true, otherwise, return false.

  • Description: Each number in the array is positive, and the array length is up to 1000.

Approach

  • Idea: Iterate through the array, checking each element to see if it is odd, and count consecutive odd numbers. If the count of consecutive odd numbers reaches 3, return true; otherwise, return false.

  • Algorithm:

    1. Iterate through the array, checking if each element is odd.

    2. If the element is odd, increment the count of consecutive odd numbers; if not, reset the count.

    3. If the count of consecutive odd numbers reaches 3, return true.

    4. If the end of the array is reached without finding three consecutive odd numbers, return false.

Code

class Solution {
    public boolean threeConsecutiveOdds(int[] arr) {
        int count=0;

        for(int val : arr){
            if(val %2 != 0) count++;
            else count=0;

            if(count==3) return true;
        }
        return false;
    }
}

Conclusion

  • Time Complexity: The time complexity is O(n) because the array is traversed once. Here, n is the length of the array.

  • Space Complexity: The space complexity is O(1) because no additional space is used.