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.

Example

Constraints


Clarifying Questions

  1. Q: Can the input array contain negative numbers? A: No, based on the constraints, the values range from 1 to 1000.
  2. Q: Is the array guaranteed to have at least three elements? A: No, the length of the array can be as short as 1.

Strategy

  1. Iterate through the array: We will use a loop to go through each element of the array.
  2. Check for three consecutive odd numbers: Use a sliding window of three elements to check if they are all odd. If they are, return true.
  3. Return false if no such triplet is found: If the loop completes without finding three consecutive odd numbers, return false.

Code

#include <vector>
using namespace std;

class Solution {
public:
    bool threeConsecutiveOdds(vector<int>& arr) {
        // We need to check if there are at least three elements
        if (arr.size() < 3) {
            return false;
        }
        
        // Iterate through the array with a window of size 3
        for (int i = 0; i < arr.size() - 2; ++i) {
            if (arr[i] % 2 != 0 && arr[i + 1] % 2 != 0 && arr[i + 2] % 2 != 0) {
                return true;
            }
        }
        
        // If no triplet of consecutive odd numbers is found, return false
        return false;
    }
};

Time Complexity

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