𝗟𝗲𝗲𝘁𝗰𝗼𝗱𝗲 𝟭𝟱𝟬 | 𝗗𝗮𝘆 𝟮: 𝗥𝗲𝗺𝗼𝘃𝗲 𝗘𝗹𝗲𝗺𝗲𝗻𝘁
You need to remove a value from an array.
Way 1: The Naive Way Use a for loop and splice. Splice removes an item and shifts the rest. You must subtract 1 from your index to avoid skipping items.
- Time: O(n^2)
- Space: O(1)
Way 2: The Fast Way Use two pointers. One pointer moves fast to find values you want. One pointer moves slow to place those values.
- Time: O(n)
- Space: O(1)
Which one wins? The first way is easy to read. It cleans the array. It is slow. The second way is fast. It handles large data. It leaves old data at the end.
Use the two-pointer method for better performance.
Source: https://dev.to/afuji/leetcode-150-day-2-remove-element-naive-vs-optimized-3557