Open In App

Check if K Consecutive even numbers present or not

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array, arr[] of integers and an integer K, the task is to print true if there are K consecutive even numbers present else return false.

Input: arr[] = {1, 2, 4, 6, 7, 8}, K = 3
Output: true
Explanation: There are K = 3  consecutive even elements (2, 4, 6) present in the array.

Input: arr[] = {1, 2, 3, 4, 5}, K = 2
Output: false

Approach:  This can be solved with the following idea:

Get the index of all even elements in arr and check if there are increasing consecutive elements (increasing by 1) present at least K times.

Below is the implementation of the above approach:

  • Create a vector index[], and get all indexes of even numbers in it.
  • Then, check if consecutive increasing elements are present in the index[] at least K times.
  • If yes, print “true”, else “false”.

Below is the implementation for the above approach:

C++14




// C++ implementation of the above code
#include <bits/stdc++.h>
using namespace std;
 
// Function to check k consecutive
// elements present or not
void checkConsecutive(int arr[], int n, int k)
{
 
    // Stores index
    vector<int> index;
 
    int i = 0;
    while (i < n) {
 
        // Even element
        if (arr[i] % 2 == 0) {
            index.push_back(i);
        }
        i++;
    }
 
    int count = 1;
    i = 1;
 
    // Count increasing consecutive
    // elements
    while (i < index.size()) {
        if (index[i] == index[i - 1] + 1) {
            count++;
        }
        else {
            count = 1;
        }
 
        // If present atleast k times
        if (count >= k) {
            cout << "true";
            return;
        }
        i++;
    }
 
    // If not present
    cout << "false";
    return;
}
 
// Driver code
int main()
{
    int N = 6;
    int arr[] = { 1, 2, 4, 6, 7, 8 };
    int K = 3;
 
    // Function call
    checkConsecutive(arr, N, K);
    return 0;
}


Java




// Java implementation of the above code
import java.util.*;
 
class GFG {
 
    // Function to check k consecutive
    // elements present or not
    public static void checkConsecutive(int arr[], int n,
                                        int k)
    {
 
        // Stores index
        List<Integer> index = new ArrayList<Integer>();
 
        int i = 0;
        while (i < n) {
 
            // Even element
            if (arr[i] % 2 == 0) {
                index.add(i);
            }
            i++;
        }
 
        int count = 1;
        i = 1;
 
        // Count increasing consecutive
        // elements
        while (i < index.size()) {
            if (index.get(i) == index.get(i - 1) + 1) {
                count++;
            }
            else {
                count = 1;
            }
 
            // If present at least k times
            if (count >= k) {
                System.out.println("true");
                return;
            }
            i++;
        }
 
        // If not present
        System.out.println("false");
        return;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int N = 6;
        int arr[] = { 1, 2, 4, 6, 7, 8 };
        int K = 3;
 
        // Function call
        checkConsecutive(arr, N, K);
    }
}
// This code is contributed by Prasad Kandekar(prasad264)


Python3




# Python3 implementation of the above code
 
# Function to check k consecutive
# elements present or not
def checkConsecutive(arr, n, k):
  # Stores index
  index = []
  i = 0
  while i < n:
      # Even element
      if arr[i] % 2 == 0:
          index.append(i)
      i += 1
 
  count = 1
  i = 1
 
  # Count increasing consecutive elements
  while i < len(index):
      if index[i] == index[i - 1] + 1:
          count += 1
      else:
          count = 1
 
      # If present atleast k times
      if count >= k:
          print("true")
          return
      i += 1
 
  # If not present
  print("false")
  return
 
# Driver code
if __name__ == '__main__':
  N = 6
  arr = [1, 2, 4, 6, 7, 8]
  K = 3
  # Function call
  checkConsecutive(arr, N, K)


Javascript




// JavaScript implementation of the above code
 
// Function to check k consecutive
// elements present or not
function checkConsecutive(arr, n, k)
{
 
    // Stores index
    let index=[];
 
    let i = 0;
    while (i < n) {
 
        // Even element
        if (arr[i] % 2 == 0) {
            index.push(i);
        }
        i++;
    }
 
    let count = 1;
    i = 1;
 
    // Count increasing consecutive
    // elements
    while (i < index.length) {
        if (index[i] == index[i - 1] + 1) {
            count++;
        }
        else {
            count = 1;
        }
 
        // If present atleast k times
        if (count >= k) {
            document.write("true");
            return;
        }
        i++;
    }
 
    // If not present
    document.write("false");
    return;
}
 
// Driver code
let N = 6;
let arr = [ 1, 2, 4, 6, 7, 8 ];
let K = 3;
 
// Function call
checkConsecutive(arr, N, K);


C#




// C# implementation of the above code
 
using System;
using System.Collections.Generic;
 
public class GFG {
 
    // Function to check k consecutive elements present or
    // not
    public static void checkConsecutive(int[] arr, int n,
                                        int k)
    {
 
        // Stores index
        List<int> index = new List<int>();
 
        int i = 0;
        while (i < n) {
 
            // Even element
            if (arr[i] % 2 == 0) {
                index.Add(i);
            }
            i++;
        }
 
        int count = 1;
        i = 1;
 
        // Count increasing consecutive elements
        while (i < index.Count) {
            if (index[i] == index[i - 1] + 1) {
                count++;
            }
            else {
                count = 1;
            }
 
            // If present at least k times
            if (count >= k) {
                Console.WriteLine("true");
                return;
            }
            i++;
        }
 
        // If not present
        Console.WriteLine("false");
        return;
    }
 
    static public void Main()
    {
 
        // Code
        int N = 6;
        int[] arr = { 1, 2, 4, 6, 7, 8 };
        int K = 3;
 
        // Function call
        checkConsecutive(arr, N, K);
    }
}
 
// This code is contributed by karthik.


Output

true

Time Complexity: O(N)
Auxiliary Space: O(N)

Efficient Approach:

We can avoid use of extra auxiliary space in the above approach. We can just have a counter of consecutive evens as we are traversing the array. Once there is break in continuity of even numbers, we can reset the counter again to 0 and proceed to next element.

The algorithm will be involving the following steps:

  •    Traverse the array from left to right.
  •    Initialize a counter variable to 0.
  •    For each even element, increment the counter variable.
  •    If an odd element is encountered, reset the counter variable to 0.
  •    Check if the counter variable is equal to k. If it is, return true.
  •    If the end of the array is reached and the counter variable is not equal to k, return false.

Below is the implementation of the above approach:

C++




// C++ program to check if there are K consecutive
// even numbers present in the array
 
#include<bits/stdc++.h>
using namespace std;
 
// Function to check k consecutive
// elements present or not
bool checkConsecutiveEven(int arr[], int n, int k) {
    // Initializing counter to 0
    int count = 0;
 
    // Traversing the array
    for (int i = 0; i < n; i++) {
 
        // If the current element is even
        if (arr[i] % 2 == 0) {
            // Increment the counter
            count++;
 
            // If the counter reaches atleast k
            if (count >= k)
                return true;
        }
        else {
            // Reset the counter
            count = 0;
        }
    }
 
    // If k consecutive even numbers are not present
    return false;
}
 
// Driver code
int main() {
      // Input array
    int arr[] = { 1, 2, 4, 6, 7, 8 };
    int n = sizeof(arr)/sizeof(arr[0]);
    int k = 3;
 
    // Function call
    if (checkConsecutiveEven(arr, n, k))
        cout << "true\n";
    else
        cout << "false\n";
 
    return 0;
}


Java




// Java program to check if there are K consecutive
// even numbers present in the array
 
import java.util.*;
 
public class GFG {
    // Function to check k consecutive
    // elements present or not
    public static boolean checkConsecutiveEven(int arr[],
                                               int n, int k)
    {
        // Initializing counter to 0
        int count = 0;
        // Traversing the array
        for (int i = 0; i < n; i++) {
            // If the current element is even
            if (arr[i] % 2 == 0) {
                // Increment the counter
                count++;
 
                // If the counter reaches atleast k
                if (count >= k)
                    return true;
            }
            else {
                // Reset the counter
                count = 0;
            }
        }
 
        // If k consecutive even numbers are not present
        return false;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        // Input array
        int arr[] = { 1, 2, 4, 6, 7, 8 };
        int n = arr.length;
        int k = 3;
 
        // Function call
        if (checkConsecutiveEven(arr, n, k))
            System.out.println("true");
        else
            System.out.println("false");
    }
}


Python3




# Function to check k consecutive elements present or not
def checkConsecutiveEven(arr, n, k):
    # Initializing counter to 0
    count = 0
    # Traversing the array
    for i in range(n):
        # If the current element is even
        if arr[i] % 2 == 0:
            # Increment the counter
            count += 1
 
            # If the counter reaches atleast k
            if count >= k:
                return True
        else:
            # Reset the counter
            count = 0
 
    # If k consecutive even numbers are not present
    return False
 
# Driver code
arr = [1, 2, 4, 6, 7, 8]
n = len(arr)
k = 3
 
# Function call
if checkConsecutiveEven(arr, n, k):
    print("true")
else:
    print("false")
# This Code is Contributed by Vikas Bishnoi


C#




// C# program to check if there are K consecutive
// even numbers present in the array
 
using System;
 
class GFG {
    // Function to check k consecutive
    // elements present or not
    static bool CheckConsecutiveEven(int[] arr, int n,
                                     int k) {
        // Initializing counter to 0
        int count = 0;
        // Traversing the array
        for (int i = 0; i < n; i++) {
            // If the current element is even
            if (arr[i] % 2 == 0) {
                // Increment the counter
                count++;
 
                // If the counter reaches atleast k
                if (count >= k)
                    return true;
            }
            else {
                // Reset the counter
                count = 0;
            }
        }
 
        // If k consecutive even numbers are not present
        return false;
    }
 
    // Driver code
    static void Main(string[] args) {
        // Input array
        int[] arr = { 1, 2, 4, 6, 7, 8 };
        int n = arr.Length;
        int k = 3;
 
        // Function call
        if (CheckConsecutiveEven(arr, n, k))
            Console.WriteLine("true");
        else
            Console.WriteLine("false");
    }
}


Javascript




function checkConsecutiveEven(arr, n, k) {
    // Initializing counter to 0
    let count = 0;
    // Traversing the array
    for (let i = 0; i < n; i++) {
        // If the current element is even
        if (arr[i] % 2 === 0) {
            // Increment the counter
            count++;
 
            // If the counter reaches atleast k
            if (count >= k) {
                return true;
            }
        } else {
            // Reset the counter
            count = 0;
        }
    }
 
    // If k consecutive even numbers are not present
    return false;
}
 
// Driver code
let arr = [1, 2, 4, 6, 7, 8];
let n = arr.length;
let k = 3;
 
// Function call
if (checkConsecutiveEven(arr, n, k)) {
    console.log("true");
} else {
    console.log("false");
}


Output

true

Time Complexity: O(N) where N is the size of array.
Auxiliary Space: O(1) as no extra space has been used.



Last Updated : 20 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads