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
.
arr
?arr
contain?Based on the standard problem statement, we’ll assume:
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));
}
}
consecutiveOdds
to keep track of consecutive odd numbers.num % 2 != 0
), increment the counter.true
.false
.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.
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?