How can we insert an item into an array efficiently?

Ahmed ElgendyAhmed Elgendy
1 min read

Sometimes we have to insert items to the first indices of the array

The easiest solution can be:

  var array = [1,2,3,4,5,6,7,8,9]
  array.insert(0, at: 0)
  print(array)

this solution is going to work, but is it efficient?

Looking into the Apple Documentation of the insert function you can see the complexity of the insert function is O(n) which means all elements of the array will be shifted to insert the item to index 0

So the solution is not efficient, so how can we improve it?

One possible solution is using reverse function whose complexity is O(1) so it's very efficient

  1. First, reverse the array
  2. Then append the item to the array
  3. Then reverse the array again
    var array = [1,2,3,4,5,6,7,8,9]
    array.reverse()
    array.append(0)
    array.reverse()
    print(array)
    
    That is it!
1
Subscribe to my newsletter

Read articles from Ahmed Elgendy directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ahmed Elgendy
Ahmed Elgendy

iOS Software Engineer (Swift, SwiftUI) with +4 years of experience working with international teams and clients, Published +10 apps, seeking to build world-class apps