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.
Input: arr = [1, 0, 0, 0, 1, 0, 0, 1, 0, 0], K = 2.
Every 1 in the array is at least K distance apart from each other.
Input: [1, 0, 1, 0, 1, 1], K = 1
The fifth 1 and sixth 1 are not apart from each other. Hence, the output is false.
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:
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.
- Minimum Sum of a pair at least K distance apart from an Array
- Count of 0s to be flipped to make any two adjacent 1s at least K 0s apart
- Length of array pair formed where one contains all distinct elements and other all same elements
- Maximum subsequence sum such that all elements are K distance apart
- Check if minimum element in array is less than or equals half of every other element
- Check if a given array contains duplicate elements within k distance from each other
- Check if all the pairs of an array are coprime with each other
- Count pairs (p, q) such that p occurs in array at least q times and q occurs at least p times
- Check if product of every pair exists in an array
- Check if any permutation of array contains sum of every adjacent pair not divisible by 3
- Divide every element of one array by other array elements
- Length of longest subarray of length at least 2 with maximum GCD
- Check if an array has some palindromic subsequence of length at least 3
- Maximum in array which is at-least twice of other elements
- Print array elements that are divisible by at-least one other
- Number of indices pair such that element pair sum from first Array is greater than second Array
- Check if two arrays are permutations of each other
- Check if two arrays are permutations of each other using Mathematical Operation
- Find K for every Array element such that at least K prefixes are ≥ K
- Closest pair in an Array such that one number is multiple of the other
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.