Optimizing Array Operations in TypeScript
Today, I explore a Daily Leetcode problem number 2640. Apply Operations to an Array
using TypeScript that modifies an array based on specific rules:
- If two consecutive elements are equal, double the first and set the second to 0.
- After processing the array, move all zeroes to the end while keeping the relative order of other elements.
Let’s break it down step by step.
Understanding the Code
Function Definition
function applyOperations(nums: number[]): number[] {
The function takes an array of numbers (nums
) as input.
Step 1: Iterating Through the Array
for (let i = 0; i < nums.length - 1; i++) {
We use a for
loop to iterate from index 0
to second-last element (nums.length - 1
). This ensures that we check each element and its next neighbor.
Step 2: Doubling Consecutive Equal Elements
if (nums[i] == nums[i + 1]) {
nums[i] *= 2;
nums[i + 1] = 0;
}
If two consecutive elements are equal, we:
-
Double the first element (
nums[i] *= 2
) -
Set the second element to
0
(nums[i + 1] = 0
)
Example Transformation:
Input: [2, 2, 3, 3, 4]
Step 1: [4, 0, 3, 3, 4] // (2+2 → 4, set next to 0)
Step 2: [4, 0, 6, 0, 4] // (3+3 → 6, set next to 0)
Step 3: Moving Zeroes to the End
return nums.filter(Boolean).concat(nums.filter((num) => !num));
}
- We use
.filter(Boolean)
to remove0
s and keep non-zero values. - We use
.filter(num => !num)
to extract all zeroes.
Finally, we concatenate the two arrays to place zeroes at the end.
Example Output:
applyOperations([2, 2, 3, 3, 4]);
// Step 1: [4, 0, 6, 0, 4]
// Step 2: Remove zeros -> [4, 6, 4]
// Step 3: Add zeros at the end -> [4, 6, 4, 0, 0]
Final Optimized Code
function applyOperations(nums: number[]): number[] {
for (let i = 0; i < nums.length - 1; i++) {
if (nums[i] == nums[i + 1]) {
nums[i] *= 2;
nums[i + 1] = 0;
}
}
return nums.filter(Boolean).concat(nums.filter((num) => !num));
}
Time & Space Complexity Analysis
- Loop through the array →
O(n)
- Filtering & concatenation →
O(n)
- Overall Complexity:
O(n)
(linear time complexity)
Conclusion
This function efficiently:
- Modifies the array in place.
- Moves all zeroes to the end after processing.
- Runs in O(n) time complexity, making it optimal for large inputs.
Top comments (0)