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

Given an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False.

Example:

Input: nums = [1,0,0,0,1,0,0,1], k = 2
Output: true
Explanation: Each of the 1s are at least 2 places away from each other.

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

bool kLengthApart(vector<int&numsint k)
{

    int n = nums.size();

    int i = 0;
    while (i < n)
    {
        int cnt = 0;
        while (i < n && nums[i] == 0)
        {
            i++;
        }
        if (i == n)
            return true;
        i++;
        if (i == n)
            return true;
        while (i < n && nums[i] == 0)
        {
            cnt++;
            i++;
        }
        if (i == n)
            return true;
        if (cnt < k)
            return false;
    }
    return true;
}

int main()
{
    vector<int> nums = {10001001};
    int k = 2;

    if (kLengthApart(nums, k))
    {
        cout << "true";
    }
    else
        cout << "false";

    return 0;
}


No comments:

Post a Comment