If I remove one element from an array using splice() like so:
arr.splice(i, 1);
Will this be O(n) in the worst case because it shifts all the elements after i? Or is it constant time, with some linked list magic underneath?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Worst case should be
O(n)(copying alln-1elements to new array).A linked list would be
O(1)for a single deletion.For those interested I’ve made this lazily-crafted benchmark. (Please don’t run on Windows XP/Vista).
As you can see from this though, it looks fairly constant (i.e.O(1)), so who knows what they’re doing behind the scenes to make this crazy-fast. Note that regardless, the actualspliceis VERY fast.Rerunning an extended benchmark directly in the V8 shell that suggest
O(n). Note though that you need huge array sizes to get a runtime that’s likely to affect your code. This should be expected as if you look at the V8 code it usesmemmoveto create the new array.