Problem Description
Given a binary array nums and an integer k, determine whether all 1's in the array are at least k places apart from each other. If they are, return true; otherwise, return false.
Key Insights
- Iterate through the array while keeping track of the index of the last encountered 1.
- For every new 1, check if the distance from the previous 1 is at least k + 1.
- If the gap is too small, immediately return false.
- A single sweep of the array is sufficient (O(n) time complexity).
Space and Time Complexity
Time Complexity: O(n) Space Complexity: O(1)
Solution
We solve this problem by traversing the array once and using a variable to store the index of the last seen 1. When a 1 is found, if there was a previous 1, we check if the current index minus the previous index is less than k + 1. If so, we return false immediately. If no violations are found after processing the entire array, we return true. This approach uses a simple iteration with an integer variable for tracking, leading to O(n) time and O(1) space complexity.