Check If All 1's Are at Least Length K Places Away in C++

C++Server Side ProgrammingProgramming

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 −

 Live Demo

#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
raja
Published on 17-Nov-2020 16:45:55
Advertisements