Instead of splice, use swap and pop【JavaScript】
1 min readFeb 25, 2024
Hi, I’ve been immersed in leetcoding. Especially, I’m spending a lot of time improving bad code I wrote before. Today, I could improve O(N²) to O(N) and got trick to worth sharing.
First Leet code URL
Originally, I wrote O(N²) code because for statement includes not only indexOf methods but splice(both of them are O(N)). It was too slow(108ms)
Improved Code
This is the improved one. The trick is I used swap and pop (both of them are O(1)), instead of splice. As a result, the time complexity became 47ms!