EasyNo. 1437

Check If All 1's Are at Least Length K Places Away — LeetCode 1437 Python Solution

Topics
Array
Reading time
2 min

The problem

Given an binary array nums 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.

Python solution

PythonSolution
class Solution:
    def kLengthApart(self, nums: List[int], k: int) -> bool:
        j = -inf
        for i, x in enumerate(nums):
            if x:
                if i - j - 1 < k:
                    return False
                j = i
        return True

Complexity

Time
O(n)where n is the length of the array nums
Space · auxiliary
O(1)

Related problems

Frequently asked questions

How hard is LeetCode 1437. Check If All 1's Are at Least Length K Places Away?

LeetCode 1437. Check If All 1's Are at Least Length K Places Away is rated Easy on LeetCode.

What is the time complexity of LeetCode 1437. Check If All 1's Are at Least Length K Places Away?

The Python solution on this page runs in O(n), where n is the length of the array \textit{nums}.

What is the space complexity of LeetCode 1437. Check If All 1's Are at Least Length K Places Away?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 1437. Check If All 1's Are at Least Length K Places Away cover?

LeetCode 1437. Check If All 1's Are at Least Length K Places Away is tagged Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.