Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Check if all possible Triplet Sum is present in given Array
Next article icon

Check if a key is present in every segment of size k in an array

Last Updated : 15 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] and size of array is n and one another key x, and give you a segment size k. The task is to find that the key x present in every segment of size k in arr[].
Examples: 

Input : 
arr[] = { 3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3} 
x = 3 
k = 3 
Output : Yes 
Explanation: There are 4 non-overlapping segments of size k in the array, {3, 5, 2}, {4, 9, 3}, {1, 7, 3} and {11, 12, 3}. 3 is present all segments.

Input : 
arr[] = { 21, 23, 56, 65, 34, 54, 76, 32, 23, 45, 21, 23, 25} 
x = 23 
k = 5 
Output :Yes 
Explanation: There are three segments and last segment is not full {21, 23, 56, 65, 34}, {54, 76, 32, 23, 45} and {21, 23, 25}. 
23 is present all window.

Input :arr[] = { 5, 8, 7, 12, 14, 3, 9} 
x = 8 
k = 2 
Output : No

Approach:

The idea is simple, we consider every segment of size k and check if x is present in the window or not. We need to carefully handle the last segment.

Algorithm:

 Step 1: Create a function named “findxinkwindowSize” which takes input parameters  “N “- the size of the array, “arr” – the input  array, “x” – the search key, “k” – the segment size.                                                                                                                       
Step 2: Create a boolean variable and initialize it to false                                                                                                                       
Step 3: Traverse i from 0 to N-1 in steps of k.                                                                                                                                        
Step 4:  Now, for each traversed i , iterate j from 0 to k-1 and perform the following:
               a. Check if the (i+j)th element of the array arr is equal to x. If yes, break out of the inner loop.
               b. If j equals k, return false.
               c. If (i+j) is greater than or equal to N, return false.                                                                                                                     
Step 5: Return true if I is more than or equal to N; else, return b’s value.

Below is the implementation of the above approach: 

C++




// C++ code to find the  every segment size of
// array have a search key x
#include <bits/stdc++.h>
using namespace std;
 
bool findxinkwindowSize(int arr[], int x, int k, int n)
{
    int i;
    for (i = 0; i < n; i = i + k) {
 
        // Search x in segment starting
        // from index i.
        int j;
        for (j = 0; j < k; j++)
            if (arr[i + j] == x)
                break;
 
        // If loop didn't break
        if (j == k)
           return false;
    }
 
    // If n is a multiple of k
    if (i == n)
       return true;
 
    // Check in last segment if n
    // is not multiple of k.
    int j;
    for (j=i-k; j<n; j++)
      if (arr[j] == x)
          break;
    if (j == n)
       return false; 
      
    return true;
}
 
// main driver
int main()
{
    int arr[] = { 3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3 };
    int x = 3, k = 3;
    int n = sizeof(arr) / sizeof(arr[0]);
    if (findxinkwindowSize(arr, x, k, n))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    return 0;
}
 
 

Java




// Java code to find the every
// segment size of array have
// a search key x
import java.util.*;
class GFG {
    static boolean findxinkwindowSize(int N, int[] arr,
                                     int x, int k)
    {
        int i;
        boolean b = false;
       
        // Iterate from 0 to N - 1
        for (i = 0; i < N; i = i + k) {
           
            // Iterate from 0 to k - 1
            for (int j = 0; j < k; j++) {
                if (i + j < N && arr[i + j] == x)
                    break;
 
                if (j == k)
                    return false;
                if (i + j >= N)
                    return false;
            }
        }
        if (i >= N)
            return true;
        else
            return b;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int arr[] = new int[] { 3, 5, 2, 4,  9,  3,
                                1, 7, 3, 11, 12, 3 };
        int x = 3, k = 3;
        int n = arr.length;
        if (findxinkwindowSize(n, arr, x, k))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by Vivek258709
 
 

Python 3




# Python 3 program to find
# the every segment size of
# array have a search key x
 
def findxinkwindowSize(arr, x, k, n) :
 
    i = 0
    while i < n :
 
        j = 0
         
        # Search x in segment
        # starting from index i
        while j < k :
             
            if arr[i + j] == x :
                break
             
            j += 1
 
        # If loop didn't break
        if j == k :
            return False
 
        i += k
         
    # If n is a multiple of k    
    if i == n :
        return True
 
    j = i - k
     
    # Check in last segment if n
    # is not multiple of k.
    while j < n :
        if arr[j] == x :
            break
 
        j += 1
 
    if j == n :
        return False
 
    return True
 
# Driver Code
if __name__ == "__main__" :
 
    arr = [ 3, 5, 2, 4, 9, 3,
            1, 7, 3, 11, 12, 3 ]
    x, k = 3, 3
    n = len(arr)
     
    if (findxinkwindowSize(arr, x, k, n)) :
        print("Yes")
    else :
        print("No")
         
# This code is contributed
# by ANKITRAI1
 
 

C#




// C# code to find the every
// segment size of array have
// a search key x
using System;
 
class GFG
{
static bool findxinkwindowSize(int[] arr, int x,
                              int k, int n)
{
    int i;
    for (i = 0; i < n; i = i + k)
    {
 
        // Search x in segment
        // starting from index i.
        int j;
        for (j = 0; j < k; j++)
            if (arr[i + j] == x)
                break;
 
        // If loop didn't break
        if (j == k)
        return false;
    }
 
    // If n is a multiple of k
    if (i == n)
    return true;
 
    // Check in last segment if
    // n is not multiple of k.
    int l;
    for (l = i - k; l < n; l++)
    if (arr[l] == x)
        break;
    if (l == n)
    return false;
     
    return true;
}
 
// Driver Code
public static void Main()
{
    int[] arr = new int[] {3, 5, 2, 4, 9, 3,
                         1, 7, 3, 11, 12, 3};
    int x = 3, k = 3;
    int n = arr.Length;
    if (findxinkwindowSize(arr, x, k, n))
        Console.Write("Yes");
    else
        Console.Write("No");
}
}
 
// This code is contributed by ChitraNayal
 
 

PHP




<?php
// PHP code to find the every
// segment size of array have
// a search key x
 
function findxinkwindowSize(&$arr, $x,
                            $k, $n)
{
    for ($i = 0;
         $i < $n; $i = $i + $k)
    {
 
        // Search x in segment
        // starting from index i.
        for ($j = 0; $j < $k; $j++)
            if ($arr[$i + $j] == $x)
                break;
 
        // If loop didn't break
        if ($j == $k)
        return false;
    }
 
    // If n is a multiple of k
    if ($i == $n)
    return true;
 
    // Check in last segment if n
    // is not multiple of k.
    for ($j = $i - $k; $j < $n; $j++)
    if ($arr[$j] == $x)
        break;
    if ($j == $n)
    return false;
     
    return true;
}
 
// Driver Code
$arr = array(3, 5, 2, 4, 9, 3, 1,
             7, 3, 11, 12, 3);
$x = 3;
$k = 3;
$n = sizeof($arr);
if (findxinkwindowSize($arr, $x, $k, $n))
    echo "Yes" ;
else
    echo "No" ;
 
// This code is contributed
// by Shivi_Aggarwal
?>
 
 

Javascript




<script>
 
// JavaScript code to find the  every segment size of
// array have a search key x
 
function findxinkwindowSize( arr,  x,  k,  n)
{
    let i;
    for (i = 0; i < n; i = i + k) {
 
        // Search x in segment starting
        // from index i.
        let j;
        for (j = 0; j < k; j++)
            if (arr[i + j] == x)
                break;
 
        // If loop didn't break
        if (j == k)
           return false;
    }
 
    // If n is a multiple of k
    if (i == n)
       return true;
 
    // Check in last segment if n
    // is not multiple of k.
    let j;
    for (j=i-k; j<n; j++)
      if (arr[j] == x)
          break;
    if (j == n)
       return false; 
      
    return true;
}
 
// main driver
  let arr = [ 3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3 ];
    let x = 3, k = 3;
    let n = arr.length;
    if (findxinkwindowSize(arr, x, k, n))
        document.write("Yes");
    else
        document.write("No");
         
// This code contributed by aashish1995
 
</script>
 
 
Output: 
Yes

 

Time Complexity: O(N), where N is the size of the given array.
Auxiliary Space: O(1) as constant space is being used.



Next Article
Check if all possible Triplet Sum is present in given Array

R

Rajput-Ji
Improve
Article Tags :
  • Arrays
  • DSA
  • Searching
Practice Tags :
  • Arrays
  • Searching

Similar Reads

  • Check whether K times of a element is present in array
    Given an array arr[] and an integer K, the task is to check whether K times of any element are also present in the array. Examples : Input: arr[] = {10, 14, 8, 13, 5}, K = 2 Output: Yes Explanation: K times of 5 is also present in an array, i.e. 10. Input: arr[] = {7, 8, 5, 9, 11}, K = 3 Output: No
    8 min read
  • Check if all possible Triplet Sum is present in given Array
    Given an array arr[] of size N, the task is to check if for all distinct triplets of indices i, j, k, [ 0 ≤ i < j < k ≤ N-1 ] the sum arr[i]+arr[j]+arr[k] is present in the array. Examples: Input: arr[] = {-1, 0, 0, 1}Output: TrueExplanation: For index 0, 1, 2: arr[i]+arr[j]+arr[k] = -1 + 0 +
    9 min read
  • Check if all array elements are present in a given stack or not
    Given a stack of integers S and an array of integers arr[], the task is to check if all the array elements are present in the stack or not. Examples: Input: S = {10, 20, 30, 40, 50}, arr[] = {20, 30}Output: YesExplanation:Elements 20 and 30 are present in the stack. Input: S = {50, 60}, arr[] = {60,
    5 min read
  • Check if a key is present in a C++ map or unordered_map
    A C++ map and unordered_map are initialized to some keys and their respective mapped values. Examples: Input : Map : 1 -> 4, 2 -> 6, 4 -> 6Check1 : 5, Check2 : 4Output : 5 : Not present, 4 : PresentC++ implementation : [GFGTABS] map // CPP code to check if a // key is present in a map #incl
    3 min read
  • Check if an encoding represents a unique binary string
    Given an encoding of a binary string of length k, the task is to find if the given encoding uniquely identifies a binary string or not. The encoding has counts of contiguous 1s (separated by 0s). For example, encoding of 11111 is {5}, encoding of 01101010 is {2, 1, 1} and encoding of 111011 is {3, 2
    6 min read
  • Check if every pair of 1 in the array is at least K length apart from each other
    Given a binary array and an integer K, check if every pair of 1 in the array is at least K length apart from each other. Return true if the condition holds, otherwise return false. Examples: Input: arr = [1, 0, 0, 0, 1, 0, 0, 1, 0, 0], K = 2. Output: True Explanation: Every 1 in the array is at leas
    5 min read
  • Check if a sorted array can be divided in pairs whose sum is k
    Given a sorted array of integers and a number k, write a function that returns true if given array can be divided into pairs such that sum of every pair k.Expected time complexity O(n) and extra space O(1). This problem is a variation of below problem, but has a different interesting solution that r
    11 min read
  • Sum of all elements repeating 'k' times in an array
    Given an array, we have to find the sum of all the elements repeating k times in an array. We need to consider every repeating element just once in the sum. Examples: Input : arr[] = {2, 3, 9, 9} k = 1 Output : 5 2 + 3 = 5 Input : arr[] = {9, 8, 8, 8, 10, 4} k = 3 Output : 8 One simple solution is t
    8 min read
  • Check whether for all pair (X, Y) of given Array floor of X/Y is also present
    Given an array arr[] of size N and an integer K, denoting the maximum value an array element can have, the task is to check if for all possible pairs of elements (X, Y) where X≥Y, ⌊X/Y⌋ (X divided by Y with rounding down) is also present in this array. Examples: Input: N = 3, K = 5, arr[]={1, 2, 5}O
    10 min read
  • Count of elements in Array which are present K times & their double isn't present
    Given an array arr[] of N integers, the task is to find the count of elements in the array that are present K times and their double are not present in the array.  Examples: Input: arr[] = {10, 6, 12, 8, 10, 8}, K = 2Output: 2Explanation: 10 is a valid number since it appears exactly two times and 2
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences