Check If All 1's Are at Least Length K Places Away — LeetCode 1437 Python Solution
EasyArray
- Problem
- #1437
- Reading time
- 2 min
- Source
- leetcode.com
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
Python
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 TrueComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array \textit{nums} |
| Space | O(1) auxiliary |
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.