JSFiddle - React, Tailwind, and code Playground
by saidulu401
JavaScript
function findLastElement(arr) {
let left = 0;
let right = arr.length - 1;
let removeFromStart = true; // Start by removing from the start
while (left < right) {
if (removeFromStart) {
// Remove every second element from the start
for (let i = left; i <= right; i++) {
if ((i - left) % 2 === 1) {
arr.splice(i, 1);
right--; // Adjust right index since we removed an element
i--; // Adjust i to check the next element
}
}
} else {
// Remove every second element from the end
for (let i = right; i >= left; i--) {
if ((right - i) % 2 === 1) {
arr.splice(i, 1);
right--; // Adjust right index since we removed an element
i++; // Adjust i to check the previous element
}
}
}
removeFromStart = !removeFromStart; // Alternate direction
}
return arr[left]; // Return the last remaining element
}
// Example usage:
const inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9,10];
const lastElement = findLastElement(inputArray);
console.log(lastElement); // Output: the last remaining element