This post is completed by 5 users
|
Add to List |
535. Find Three Consecutive Odd Numbers in an array
GIven an array of numbers, find out if array contains three consecutive odd numbers
Example:
[2, 4, 1, 3, 4, 1, 3, 6] Three consecutive odds: false [2, 4, 1, 3, 4, 1, 3, 6] Three consecutive odds: true [2, 4, 1, 3, 4, 1, 3, 6] Three consecutive odds: true
Solution:
Initialize count = 0. Now iterate the array from left to right and for each element if the element is odd then increment the count by 1 else if the element is even then reset the count to 0. So during iteration if any time count becomes 3 that means there are three consecutive elements that are odd else count would have been set to 0. If iteration gets completed that means no we have not found three consecutive odd elements, so return false.
Output:
[2, 4, 1, 3, 4, 1, 3, 6], three consecutive odds: false [2, 4, 1, 3, 4, 1, 3, 6], three consecutive odds: true [2, 4, 1, 3, 4, 1, 3, 6], three consecutive odds: true
Reference: Leetcode