EasyNo. 1437
Check If All 1's Are at Least Length K Places Away — LeetCode 1437 Python Solution
- Topics
- Array
- 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
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
- Time
- O(n)where n is the length of the array nums
- Space · auxiliary
- O(1)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1431 | Kids With the Greatest Number of Candies | Easy |
| 0057 | Insert Interval | Medium |
| 0228 | Summary Ranges | Easy |
| 0485 | Max Consecutive Ones | Easy |
| 0665 | Non-decreasing Array | Medium |
| 0674 | Longest Continuous Increasing Subsequence | Easy |
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.