Home > Blockchain >  my version of inserting into index of array - without splice
my version of inserting into index of array - without splice

Time:01-29

splice is time complexity O(n); I tried this version instead of splice: which has added space complexity but i think less time complexity.

 let arr = [0,1];

    arr[5] = 5;
     // i need to push numbers into this index only-not to the whole array
     // push wont work on a 1d array but will work on 2d array
    arr[5] = [[], 5];
    // now it is possible to push into this index
    arr[5].push(15,125,1035);
    // remove the unnecessary empty cell []
    arr[5].shift();
    
    console.log(arr) // result [0,1,[5,15,125,1035]]

So is this worse than splice, or better(in terms of time complexity)?

CodePudding user response:

If you want result [5,15,125,1035] with simply this way.

 let arr = [5];
     arr.push(15,125,1035);
    
    console.log(arr)

CodePudding user response:

Javascript leaves the underlying implementation of arrays up to the runtime, so the answer will depend on implementation used: How are JavaScript arrays implemented? but I will assume this array is entirely a flat array.

Pushing to the end of an flat array is only O(1) if the array has space for more elements. Otherwise the array needs to be reallocated which is O(length_of_array). However it should still be faster than splicing on every insertion.

If you want O(1) insertion speed then you could append to the end of a doubly linked list instead, however this is at the cost of space and lookup/iteration speed.

CodePudding user response:

the simpler answer i was looking for is by @Gerardo Furtado

let arr = [0,1,2,3,4,5];

    arr[5] = [5];
    arr[5].push(15,125,1035);
    
    console.log(arr) // result [0,1,[5,15,125,1035]]
  • Related