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 K consecutive palindrome numbers are present in the Array
Next article icon

Check if every pair of 1 in the array is at least K length apart from each other

Last Updated : 27 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 least K distance apart from each other.

Input: arr= [1, 0, 1, 0, 1, 1], K = 1 
Output: False 
Explanation: 
The fifth 1 and sixth 1 are not apart from each other. Hence, the output is false. 

 

Approach:
To solve the problem mentioned above we have to check the distance between each pair of adjacent 1. Find the first position of 1 then iterate through the rest of the array and increment distance if it’s 0 otherwise perform a check operation if the distance is less than k and reset the count to 0 again.
Below is the implementation of the above approach:
 

C++




// C++ implementation to Check if every pair of 1 in
// the array is at least K length from each other
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check distance
bool kLengthApart(vector<int>& nums, int k)
{
    // Find first position of 1
    int pos = 0, count = 0;
 
    while (pos < nums.size() && nums[pos] == 0)
        pos++;
 
    // Iterate through the rest of array
    for (int i = pos + 1; i < nums.size(); i++) {
        // Increment distance if its 0
        if (nums[i] == 0)
            count++;
 
        // Check if the distance is less than k
        else {
            if (count < k)
                return false;
 
            // Reset count to 0
            count = 0;
        }
    }
 
    // Return the result
    return true;
}
 
// Driver code
int main()
{
    vector<int> nums = { 1, 0, 0, 0, 1, 0, 0, 1, 0, 0 };
    int k = 2;
 
    bool ans = kLengthApart(nums, k);
    if (ans == 1)
        cout << "True" << endl;
 
    else
        cout << "False" << endl;
 
    return 0;
}
 
 

Java




// Java implementation to check if
// every pair of 1 in the array is
// at least K length from each other
class Main{
     
// Function to check distance
public static boolean kLengthApart(int[] nums,
                                   int k)
{
     
    // Find first position of 1
    int pos = 0, count = 0;
 
    while (pos < nums.length && nums[pos] == 0)
        pos++;
 
    // Iterate through the rest of array
    for(int i = pos + 1; i < nums.length; i++)
    {
         
       // Increment distance if its 0
       if (nums[i] == 0)
           count++;
            
       // Check if the distance is less than k
       else
       {
           if (count < k)
               return false;
                
           // Reset count to 0
           count = 0;
       }
    }
     
    // Return the result
    return true;
}
 
// Driver Code
public static void main(String[] args)
{
    int[] nums = { 1, 0, 0, 0, 1,
                   0, 0, 1, 0, 0 };
    int k = 2;
    boolean ans = kLengthApart(nums, k);
     
    if (ans)
        System.out.println("True");
 
    else
        System.out.println("False");
}
}
 
// This code is contributed by divyeshrabadiya07
 
 

Python3




# Python3 implementation to check if
# every pair of 1 in the array is
# at least K length from each other
 
# Function to check distance
def kLengthApart(nums, k):
     
    # Find first position of 1
    pos = 0
    count = 0
     
    while (pos < len(nums) and nums[pos] == 0):
        pos += 1
         
    # Iterate through the rest of list
    for i in range(pos + 1, len(nums)):
         
        # Increment distance if its 0
        if nums[i] == 0:
            count += 1
             
        # Check if the distance is less than k
        else :
            if count < k:
                return False
                 
            # Reset count to 0
            count = 0
             
        # Return the result
    return True
     
# Driver Code
if __name__ == "__main__":
      
    nums = [ 1, 0, 0, 0, 1, 0, 0, 1, 0, 0 ]
    k = 2
     
    print(kLengthApart(nums, k))
 
# This code is contributed by rutvik_56
 
 

C#




// C# implementation to check if
// every pair of 1 in the array is
// at least K length from each other
using System;
 
class GFG{
     
// Function to check distance
public static bool kLengthApart(int[] nums,
                                int k)
{
     
    // Find first position of 1
    int pos = 0, count = 0;
 
    while (pos < nums.Length && nums[pos] == 0)
        pos++;
 
    // Iterate through the rest of array
    for(int i = pos + 1; i < nums.Length; i++)
    {
        
       // Increment distance if its 0
       if (nums[i] == 0)
           count++;
            
       // Check if the distance is
       // less than k
       else
       {
           if (count < k)
               return false;
            
           // Reset count to 0
           count = 0;
       }
    }
     
    // Return the result
    return true;
}
 
// Driver Code
public static void Main()
{
    int[] nums = { 1, 0, 0, 0, 1,
                   0, 0, 1, 0, 0 };
    int k = 2;
    bool ans = kLengthApart(nums, k);
     
    if (ans)
        Console.Write("True");
    else
        Console.Write("False");
}
}
 
// This code is contributed by chitranayal
 
 

Javascript




<script>
 
// JavaScript implementation to
// Check if every pair of 1 in
// the array is at least K length
// from each other
 
// Function to check distance
function kLengthApart(nums, k)
{
    // Find first position of 1
    var pos = 0, count = 0;
    var i;
    while (pos < nums.length && nums[pos] == 0)
        pos++;
 
    // Iterate through the rest of array
    for (i = pos + 1; i < nums.length; i++) {
        // Increment distance if its 0
        if (nums[i] == 0)
            count++;
 
        // Check if the distance is less than k
        else {
            if (count < k)
                return false;
 
            // Reset count to 0
            count = 0;
        }
    }
 
    // Return the result
    return true;
}
 
// Driver code
    var nums = [1, 0, 0, 0, 1, 0, 0, 1, 0, 0];
    var k = 2;
 
    var ans = kLengthApart(nums, k);
    if (ans == 1)
        document.write("True");
 
    else
        document.write("False");
 
</script>
 
 
Output: 
True

 

Time Complexity: O(n) 
Auxiliary Space: O(1)



Next Article
Check if K consecutive palindrome numbers are present in the Array
author
coder001
Improve
Article Tags :
  • Arrays
  • DSA
  • Write From Home
  • binary-representation
Practice Tags :
  • Arrays

Similar Reads

  • Minimum Sum of a pair at least K distance apart from an Array
    Given an array of integers A[] of size N, the task is to find the minimum sum that can be obtained by any pair of array elements that are at least K indices apart from each other. Examples: Input: A[] = {1, 2, 3, 4, 5, 6}, K = 2 Output: 4 Explanation: The minimum sum that can be obtained is by addin
    10 min read
  • Check if any subarray of length M repeats at least K times consecutively or not
    Given an array arr[] consisting of N integers and two positive integers M and K, the task is to check if there exists any subarray of length M that repeats consecutively at least K times. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: arr[] = {2, 1, 2, 1, 1, 1, 3}, M
    12 min read
  • Check if a key is present in every segment of size k in an array
    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-ove
    8 min read
  • Check if frequency of each element in given array is unique or not
    Given an array arr[] of N positive integers where the integers are in the range from 1 to N, the task is to check whether the frequency of the elements in the array is unique or not. If all the frequency is unique then print "Yes", else print "No". Examples: Input: N = 5, arr[] = {1, 1, 2, 5, 5}Outp
    15 min read
  • Check if K consecutive palindrome numbers are present in the Array
    Given an array, arr[], and an integer K, the task is to check whether K consecutive palindrome numbers are present or not. Examples: Input: arr[] = {15, 7, 11, 151, 23, 1}, K = 3Output: trueExplanation: There are 3 consecutive palindromes numbers (7, 11, 151). Input : arr[] = {19, 37, 51, 42}, K = 1
    6 min read
  • Sort integers in array according to their distance from the element K
    Given an array arr[] of N integers and an integer K, the task is to sort these integers according to their distance from given integer K. If more than 1 element is at the same distance, print them in increasing order.Note: Distance between two elements in the array is measured as the difference betw
    8 min read
  • Check whether a given array is a k sorted array or not
    Given an array of n distinct elements. Check whether the given array is a k sorted array or not. A k sorted array is an array where each element is at most k distances away from its target position in the sorted array. For example, let us consider k is 2, an element at index 7 in the sorted array, c
    12 min read
  • 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
  • Count of pairs of Array elements with average at least K
    Given an array A[] of size N consisting of N integers, the task is to count the number of pairs such that their average is greater or equal to K. Example: Input: N = 4, K = 3, A = {5, 1, 3, 4}Output: 4Explanation: (5, 1), (5, 3), (5, 4) and (3, 4) are the required pairs with average greater or equal
    11 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
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