LeetCode 1437: Check If All 1's Are at Least Length K Places Away Solution
Master LeetCode problem 1437 (Check If All 1's Are at Least Length K Places Away), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1437. Check If All 1's Are at Least Length K Places Away
Problem Explanation
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
lastIndexto -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
lastIndexis less thank, return false. - Update
lastIndexto the current index.
- If the difference between the current index and
- 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.
:
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1437 (Check If All 1's Are at Least Length K Places Away)?
This page provides optimized solutions for LeetCode problem 1437 (Check If All 1's Are at Least Length K Places Away) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1437 (Check If All 1's Are at Least Length K Places Away)?
The time complexity for LeetCode 1437 (Check If All 1's Are at Least Length K Places Away) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1437 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1437 in Java, C++, or Python.