DEV Community

Ruairí O'Brien
Ruairí O'Brien

Posted on

1

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

The Problem

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 1:

Alt Text

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.
Enter fullscreen mode Exit fullscreen mode

Example 2:

Alt Text

Input: nums = [1,0,0,1,0,1], k = 2
Output: false
Explanation: The second 1 and third 1 are only one apart from each other.
Enter fullscreen mode Exit fullscreen mode

Example 3:

Input: nums = [1,1,1,1,1], k = 0
Output: true
Enter fullscreen mode Exit fullscreen mode

Example 4:

Input: nums = [0,1,0,1], k = 1
Output: true
Enter fullscreen mode Exit fullscreen mode

Constraints:

  • 1 <= nums.length <= 10^5
  • 0 <= k <= nums.length
  • nums[i] is 0 or 1

Tests

import pytest
from .Day25_CheckIfAll1sAreAtLeastLengthKPlacesAway import Solution

s = Solution()


@pytest.mark.parametrize(
    "nums,k,expected",
    [
        ([1,0,0,0,1,0,0,1], 2, True),
        ([1,0,0,1,0,1], 2, False),
        ([1,1,1,1,1], 0, True),
        ([0,1,0,1], 1, True)
    ],
)
def test_k_length_apart(nums, k, expected):
    assert s.kLengthApart(nums, k) == expected
Enter fullscreen mode Exit fullscreen mode

Solution

from typing import List


class Solution:
    def kLengthApart(self, nums: List[int], k: int) -> bool:
        current_dist = k
        for n in nums:
            if n == 1:
                if current_dist < k:
                    return False
                current_dist = 0
            else:
                current_dist += 1

        return True
Enter fullscreen mode Exit fullscreen mode

Analysis

Alt Text

Commentary

That one was easy. A little too easy....

Alt Text

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay