#1437
Check If All 1's Are at Least Length K Places Away
EasyArrayArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a single pass through the array to track the last position of '1'. This reduces the time complexity significantly.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a variable to track the last index of '1' found.
- 2Step 2: Loop through the array. When a '1' is found, check the distance from the last '1'.
- 3Step 3: If the distance is less than 'k', return false. Update the last index of '1'.
- 4Step 4: If the loop completes without returning false, return true.
solution.py10 lines
1# Full working Python code
2
3def k_length_apart(nums, k):
4 last_index = -1
5 for i in range(len(nums)):
6 if nums[i] == 1:
7 if last_index != -1 and i - last_index < k:
8 return False
9 last_index = i
10 return Trueℹ
Complexity note: The time complexity is O(n) because we only loop through the array once. The space complexity is O(1) since we only use a few variables for tracking.
- 1Using a single pass reduces time complexity significantly.
- 2Tracking the last index of '1' helps avoid unnecessary comparisons.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.