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

Input: [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 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output:

True

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.