Leetcode 1550. Three Consecutive Odds
Given an integer array arr
, return true
if there are three consecutive odd numbers in the array. Otherwise, return false
.
Input: arr = [2,6,4,1]
Output: false
Explanation: There are no three consecutive odds.
Input: arr = [1,2,34,3,4,5,7,23,12]
Output: true
Explanation: [5, 7, 23] are three consecutive odd numbers.
1 <= arr.length <= 1000
1 <= arr[i] <= 1000
true
.false
if no such triplet is found: If the loop completes without finding three consecutive odd numbers, return false
.#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;
}
};
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?