Arrays: Check if 3 consecutive odds exist

Problem Statement:

You are given an array, you need to check if there are 3 consecutive odds exist. If exist then return true else false.

Example

Input: arr = [2,6,4,1]
Output: false

Solution

The solution is very simple.

Just iterate throught the array and check if the element is odd, then increment the odd variable.

If the element is not odd, then reset the odd variable to 0.

At the end check if odd variable is equal to 3 and get the result

Solution in C++

#include <algorithm>  
#include <iostream>    
#include <string>
#include <stack>
#include <vector>
#include <unordered_map> 
#include <queue> 

using namespace std;

bool three_consecutive_odds(vector<int>& arr) 
{
    int odds = 0;
    for (auto i = 0; i < arr.size() && odds < 3; ++i)
        odds = arr[i] % 2 ? odds + 1 : 0;
    return odds == 3;
}

int main()
{
  vector<int> arr = {10, 2, 5, 3, 9};

  if(three_consecutive_odds(arr))
  {
    cout<<"There are 3 consecutive odds exist"<<endl;
  }
  else 
  {
    cout<<"There are no 3 consecutive odds exist"<<endl;
  }

  return 0;

}

Output:

There are 3 consecutive odds exist

 

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *