Solving Leetcode’s (1437): Check If All 1’s Are at Least Length K Places Away

  • The 1 in position 0, and the next 1 in position 4, are 3 positions apart…
  • The 1 in position 4, and the next one in position 7, are 2 positions apart…
  • And the 1 in position 0 and 7 are 6 places apart.
function checkOnes(nums, k) {
let onesPositions = [];
}
function checkOnes(nums, k) {
let onesPositions = [];
for (let i = 0; i < nums.length; i++) {
if (nums[i] === 1) {
onesPositions.push(i);
}
}
}
function checkOnes(nums, k) {
let onesPositions = [];
for (let i = 0; i < nums.length; i++) {
if (nums[i] === 1) {
onesPositions.push(i);
}
}
const largestDistance =
Math.abs(onesPositions[0] - onesPositions[onesPositions.length - 1]) - 1;
}
function checkOnes(nums, k) {
let onesPositions = [];
let results = [];
for (let i = 0; i < nums.length; i++) {
if (nums[i] === 1) {
onesPositions.push(i);
}
}
const largestDistance =
Math.abs(onesPositions[0] - onesPositions[onesPositions.length - 1]) - 1;

for (let i = 0; i < onesPositions.length - 1; i++) {
let currentDistance = Math.abs(onesPositions[i] - onesPositions[i + 1]) - 1;
if (largestDistance && currentDistance >= k) {
results.push(true);
} else {
results.push(false);
}
}
}
return results.every((val) => val === true);
function checkOnes(nums, k) {
let onesPositions = [];
let results = [];
for (let i = 0; i < nums.length; i++) {
if (nums[i] === 1) {
onesPositions.push(i);
}
}
const largestDistance =
Math.abs(onesPositions[0] - onesPositions[onesPositions.length - 1]) - 1;

for (let i = 0; i < onesPositions.length - 1; i++) {
let currentDistance = Math.abs(onesPositions[i] - onesPositions[i + 1]) - 1;
if (largestDistance && currentDistance >= k) {
results.push(true);
} else {
results.push(false);
}
}
return results.every((val) => val === true);
}

--

--

--

Always learning.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

7 Topmost and Admiring Frontend JavaScript Frameworks

Debugging

Functional vs Class Components in React

Visualising large spatiotemporal data in web applications

Accessibility and SEO optimizations in Next.js app

print from javascript/jquery

What is Node?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Saul Feliz

Saul Feliz

Always learning.

More from Medium

AlphaCamp Leetcode 訓練營 01. 搜尋與分類

Leetcode Problem 3 — Longest substring without repeating characters

114. Flatten Binary Tree to Linked List 🚀

Leetcode #845 — Longest Mountain In Array