Back to course home
0% completed
Vote For New Content
Alt solution with only one O(n) pass (TypeScript)
Pavel Kostenko
Jan 28, 2025
Original solution makes 4 passes:
- find min element
- find index of min element
- find max element
- find index of max element
these can be combined into a single pass.
class Solution { /** * Time: O(n) - one pass over each value to find min & max * Space: O(1) - variables does not scale with the input size * @param nums */ minMoves(nums: number[]) { let minIdx = -1; let min = Infinity; let maxIdx = -1; let max = -Infinity; for (let i = 0; i < nums.length; i++) { // Time: O(n) if (nums[i] < min) { min = nums[i]; minIdx = i; } if (nums[i] > max) { max = nums[i]; maxIdx = i; } } // removing from both sides // (smallest index + 1) => total removals from the left // (length - largest index) => total removals from the right const both = Math.min(minIdx, maxIdx) + 1 + (nums.length - Math.max(minIdx, maxIdx)); // Time: O(1) const left = Math.max(minIdx, maxIdx) + 1; // Time: O(1) const right = nums.length - Math.min(minIdx, maxIdx); // Time: O(1); return Math.min(both, left, right); // Time: O(1) } }
0
0
Comments
Comments
On this page