Instead of splice, use swap and pop【JavaScript】

Tomoharu Tsutsumi
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!

Feel free to reach out to me on LinkedIn, which you can find below. Looking forward to connecting!

https://www.linkedin.com/in/tomoharu-tsutsumi-56051a126/

--

--

Tomoharu Tsutsumi
Tomoharu Tsutsumi

Written by Tomoharu Tsutsumi

5+ years Full Stack SWE (Ruby, Go, TypeScript, JavaScript) | Former Founding Engineer of AI Startup in Canada

No responses yet