LeetCode 1437: Check If All 1's Are at Least Length K Places Away

Array

Problem Description

Explanation:

To solve this problem, we can iterate over the binary array nums and keep track of the last index where we encountered a 1. If we encounter a 1 at index i, we check if the distance between the current index i and the last index of 1 is less than k. If it is, then we return false, as the 1's are not at least k places away. If we reach the end of the loop without finding any violations, we return true.

  • Initialize a variable lastIndex to -1 to keep track of the last index where a 1 was found.
  • Iterate over the array nums.
  • If the current element is 1:
    • If the difference between the current index and lastIndex is less than k, return false.
    • Update lastIndex to the current index.
  • If no violations were found, return true.

Time Complexity:

The time complexity of this solution is O(n), where n is the length of the input array nums.

Space Complexity:

The space complexity is O(1) as we are using only a constant amount of extra space.

:

Solutions

class Solution {
    public boolean kLengthApart(int[] nums, int k) {
        int lastIndex = -1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 1) {
                if (lastIndex != -1 && i - lastIndex <= k) {
                    return false;
                }
                lastIndex = i;
            }
        }
        return true;
    }
}

Loading editor...