- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements