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);
}

--

--

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