commit 352293fa5bbbb722eea3825fced7fd00234a33e8
parent 83ac5443079442d4f30dfad82e1a03153148a423
Author: Jack Sangdahl <jack@pngu.org>
Date: Sun, 16 Nov 2025 19:20:37 -0700
1437. check if all 1's are at least length k places away
Diffstat:
3 files changed, 53 insertions(+), 0 deletions(-)
diff --git a/check_1s_k_place_away.c b/check_1s_k_place_away.c
@@ -0,0 +1,25 @@
+// 1437. Check If All 1's Are at Least Length K Places Away
+#include "leetcode.h"
+
+/*
+ * given a binary array 'nums' and an integer 'k', return true if all 1s are at
+ * least 'k' places away from eachother, otherwise return false.
+ */
+
+bool kLengthApart(int *nums, int numsSize, int k) {
+ int prev = -1;
+ for (int i = 0; i < numsSize; i++) {
+ if (nums[i] == 1) {
+ if (prev != -1 && (i - prev - 1) < k)
+ return false;
+ prev = i;
+ }
+ }
+ return true;
+}
+
+int main() {
+ int n1[] = {1, 0, 0, 0, 1, 0, 0, 1}, n2[] = {1, 0, 0, 1, 0, 1};
+ printf("%d\n", kLengthApart(n1, ARRAY_SIZE(n1), 2)); // expect: 1
+ printf("%d\n", kLengthApart(n2, ARRAY_SIZE(n2), 2)); // expect: 0
+}
diff --git a/check_1s_k_place_away.py b/check_1s_k_place_away.py
@@ -0,0 +1,28 @@
+# 1437. Check If All 1's Are at Least Length K Places Away
+
+"""
+given a binary array 'nums' and an integer 'k', return true if all 1s are at
+least 'k' places away from eachother, otherwise return false.
+"""
+
+
+class Solution(object):
+ def kLengthApart(self, nums, k):
+ """
+ :type nums: List[int]
+ :type k: int
+ :rtype: bool
+ """
+ prev = None
+ for i, j in enumerate(nums):
+ if j == 1:
+ if prev is not None and i - prev <= k:
+ return False
+ prev = i
+ return True
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.kLengthApart(nums=[1, 0, 0, 0, 1, 0, 0, 1], k=2))
+ print(obj.kLengthApart(nums=[1, 0, 0, 1, 0, 1], k=2))
diff --git a/check_1s_k_place_away.{c,py b/check_1s_k_place_away.{c,py