- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If All 1's Are at Least Length K Places Away in C++
Suppose we have an array nums of 0s and 1s and an integer k, we have to check whether all 1's are at least k places away from each other, otherwise, return False.
So, if the input is like nums = [1,0,0,0,1,0,0,1], k = 2, then the output will be true, as each of the 1s are at least 2 places away from each other.
To solve this, we will follow these steps −
last := -1
for initialize i := 0, when i < size of nums, update (increase i by 1), do −
if nums[i] is same as 1, then −
if last is same as -1 or (i - last - 1) >= k, then −
last := i
Otherwise
return false
return true
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: bool kLengthApart(vector<int>& nums, int k) { int last = -1; for (int i = 0; i < nums.size(); i++) { if (nums[i] == 1) { if (last == -1 || (i - last - 1) >= k) last = i; else return false; } } return true; } }; main(){ Solution ob; vector<int> v = {1,0,0,0,1,0,0,1}; cout << (ob.kLengthApart(v, 2)); }
Input
{1,0,0,0,1,0,0,1}
Output
1
- Related Articles
- C# program to check if there are K consecutive 1’s in a binary number
- Convert a number of length N such that it contains any one digit at least 'K' times in C++
- Check if a binary string contains all permutations of length k in C++
- Program to check whether we can stand at least k distance away from the closest contacts in Python
- Python program to check if there are K consecutive 1’s in a binary number?
- Maximum value K such that array has at-least K elements that are >= K in C++
- Design a DFA of a string with at least two 0’s and at least two 1’s
- Design NFA with Σ = {0, 1} and accept all string of length at least 2.
- Shortest Subarray with Sum at Least K in C++
- Match any string containing a sequence of at least two p's.
- Longest Substring with At Least K Repeating Characters in C++
- Largest sum subarray with at-least k numbers in C++
- C# program to check if two lists have at-least one element common
- Count all elements in the array which appears at least K times after their first occurrence in C++
- Maximum sum subsequence with at-least k distant elements in C++

Advertisements