Insert Element in Array

Inserting an element into an array is a common operation in programming. This looks simple but has its own challenges due to the fixed size nature of arrays in many programming languages.

We are going to learn it best way possible with clear explanations and code examples in multiple programming languages.

🛠️ Ways to Insert an Element into an Array

Inserting an element into an array depends on the position where you want to insert it. Here are some common methods:

  1. Insert at the Start
  2. Insert at a Specific Position
  3. Insert at the End

1️⃣ Insert an element at the Start of an Array

To insert an element at the start of an array, we need to shift all existing elements one position to the right to make space for the new element at index 0.

Steps to insert an element at the start of an array

Before we write code, we should first understand the steps involved in insertion.

  1. Declare two global variables:

    • size → tracks the current number of elements
    • capacity → tracks the maximum size of the array
  2. Create a function insertAtStart(array, element).

  3. Inside insertAtStart:

    • Check if the array is full (size == capacity).
    • If full, print an error and return.
    • If not full, Run a loop from size - 1 to 0 to shift elements one position to the right using: array[i] = array[i - 1]
    • Now index 0 is free.
    • Insert the new element at index 0.
    • Increment size by 1.
  4. Inside the main function:

    • Create an array with a fixed capacity.
    • Call insertAtStart for each insertion.
    • Print the array after each insertion.

Why Size and Capacity declared as Global Variables?

  • Capacity: Capacity is fixed for the array and does not change during insertions. So we can declare it as a global variable.
  • Size: Size changes with each insertion. We need to maintain it externally or else we will need to traverse the entire array to calculate size every time we want to insert an element which will increase time complexity of insertion operation.

Size should be maintained externally

Its always better to maintain size of the array externally rather than calculating it inside the function.

Code Examples to Insert Element at Start of Array

Now lets see how to implement this in different programming languages.

Select your preferred programming language for code examples: Language

Program to insert element at start of array in Python

InsertAtStart.py
# Declare global variables for size and capacity
size = 0
capacity = 4
def insert_at_start(arr, element):
global size
global capacity
# If array is full, return error that element cannot be inserted
if size == capacity:
print("Array is full. Cannot insert element.")
return arr
# Shift elements to the right
arr.append(0) # Increase size of array
for i in range(size, 0, -1):
arr[i] = arr[i - 1]
# Insert element at index 0
arr[0] = element
size += 1
return arr
def main():
# Hardcoded values to insert (instead of taking user input)
inputs = [10, 20, 30, 40, 50, 60]
arr = []
# Insert elements
for element in inputs:
print(f"Inserting {element} at start")
arr = insert_at_start(arr, element)
print("Current array:", arr)
if __name__ == "__main__":
main()

The output of the above code will be:

Inserting 10 at start
Current array: [10]
Inserting 20 at start
Current array: [20, 10]
Inserting 30 at start
Current array: [30, 20, 10]
Inserting 40 at start
Current array: [40, 30, 20, 10]
Inserting 50 at start
Array is full. Cannot insert element.
Current array: [40, 30, 20, 10]
Inserting 60 at start
Array is full. Cannot insert element.
Current array: [40, 30, 20, 10]

Complexity Analysis for Insertion at Start of Array

Time Complexity:

  • O(n) - In the worst case, we need to shift all existing elements one position to the right, which takes linear time. Space Complexity:
  • O(1) - We are not using any extra space that grows with input size; we are only using a fixed amount of space for variables.

2️⃣ Insert at a Specific Position

To insert an element at a specific position in an array, we need to shift all existing elements from that position onwards one position to the right to make space for the new element.

Steps to insert an element at a specific position

As usual we should first understand the steps involved in insertion.

  1. Declare two global variables:
    • size → tracks the current number of elements
    • capacity → tracks the maximum size of the array
  2. Create a function insertAtPosition(array, element, position).
  3. Inside insertAtPosition:
    • Check if the array is full (size == capacity).
    • If full, print an error and return.
    • Check if the position is valid (0 <= position <= size).
    • If invalid, print an error and return.
    • Run a loop from size - 1 to position to shift elements one position to the right using: array[i] = array[i - 1]
    • Now index position is free.
    • Insert the new element at index position.
    • Increment size by 1.
  4. Inside the main function:
    • Create an array with a fixed capacity.
    • Call insertAtPosition for each insertion.
    • Print the array after each insertion.

Why Size and Capacity declared as Global Variables?

  • Capacity: Capacity is fixed for the array and does not change during insertions. So we can declare it as a global variable.
  • Size: Size changes with each insertion. We need to maintain it externally or else we will need to traverse the entire array to calculate size every time we want to insert an element which will increase time complexity of insertion operation.

Size should be maintained externally

Its always better to maintain size of the array externally rather than calculating it inside the function.

Code Examples to Insert Element at Specific Position in Array

Now lets see how to implement this in different programming languages.

Select your preferred programming language for code examples: Language

Program to insert element at specific position of array in Python

InsertAtPosition.py
# Declare global variables for size and capacity
size = 0
capacity = 5
def insert_at_position(arr, element, position):
global size
global capacity
# If array is full, return error that element cannot be inserted
if size == capacity:
print("Array is full. Cannot insert element.")
return arr
# Check for valid position
if position < 0 or position > size:
print("Invalid position. Cannot insert element.")
return arr
# Shift elements to the right
arr.append(0) # Increase size of array
for i in range(size, position, -1):
arr[i] = arr[i - 1]
# Insert element at specified position
arr[position] = element
size += 1
return arr
def main():
# Hardcoded values to insert (instead of taking user input)
inputs = [(10, 0), (20, 1), (30, 1), (40, 0), (50, 2), (60, 3)]
arr = []
# Insert elements
for element, position in inputs:
print(f"Inserting {element} at position {position}")
arr = insert_at_position(arr, element, position)
print("Current array:", arr)
if __name__ == "__main__":
main()

The output of the above code will be:

Inserting 10 at position 0
Current array: [10]
Inserting 20 at position 1
Current array: [10, 20]
Inserting 30 at position 1
Current array: [10, 30, 20]
Inserting 40 at position 0
Current array: [40, 10, 30, 20]
Inserting 50 at position 2
Current array: [40, 10, 50, 30, 20]
Inserting 60 at position 3
Array is full. Cannot insert element.
Current array: [40, 10, 50, 30, 20]

Complexity Analysis for Insertion at Specific Position of Array

Time Complexity:

  • O(n) - In the worst case, we may need to shift all existing elements one position to the right, which takes linear time. Space Complexity:
  • O(1) - We are not using any extra space that grows with input size; we are only using a fixed amount of space for variables.

3️⃣ Insert an element at the End of an Array

To insert an element at the end of an array, we simply place the new element at the index equal to the current size of the array.

Steps to insert an element at the end of an array

As usual we should first understand the steps involved in insertion.

  1. Declare two global variables:
    • size → tracks the current number of elements
    • capacity → tracks the maximum size of the array
  2. Create a function insertAtEnd(array, element).
  3. Inside insertAtEnd:
    • Check if the array is full (size == capacity).
    • If full, print an error and return.
    • Insert the new element at index size.
    • Increment size by 1.
  4. Inside the main function:
    • Create an array with a fixed capacity.
    • Call insertAtEnd for each insertion.
    • Print the array after each insertion.

Why Size and Capacity declared as Global Variables?

  • Capacity: Capacity is fixed for the array and does not change during insertions. So we can declare it as a global variable.
  • Size: Size changes with each insertion. We need to maintain it externally or else we will need to traverse the entire array to calculate size every time we want to insert an element which will increase time complexity of insertion operation.

Size should be maintained externally

Its always better to maintain size of the array externally rather than calculating it inside the function.

Code Examples to Insert Element at End of Array

Now lets see how to implement this in different programming languages.

Select your preferred programming language for code examples: Language

Program to insert element at end of array in Python

InsertAtEnd.py
# Declare global variables for size and capacity
size = 0
capacity = 4
def insert_at_end(arr, element):
global size
global capacity
# If array is full, return error that element cannot be inserted
if size == capacity:
print("Array is full. Cannot insert element.")
return arr
# Insert element at index size
arr.append(element)
size += 1
return arr
def main():
# Hardcoded values to insert (instead of taking user input)
inputs = [10, 20, 30, 40, 50, 60]
arr = []
# Insert elements
for element in inputs:
print(f"Inserting {element} at end")
arr = insert_at_end(arr, element)
print("Current array:", arr)
if __name__ == "__main__":
main()

The output of the above code will be:

Inserting 10 at end
Current array: [10]
Inserting 20 at end
Current array: [10, 20]
Inserting 30 at end
Current array: [10, 20, 30]
Inserting 40 at end
Current array: [10, 20, 30, 40]
Inserting 50 at end
Array is full. Cannot insert element.
Current array: [10, 20, 30, 40]
Inserting 60 at end
Array is full. Cannot insert element.
Current array: [10, 20, 30, 40]

Complexity Analysis for Insertion at End of Array

Time Complexity:

  • O(1) - Inserting an element at the end of the array takes constant time as no shifting of elements is required. Space Complexity:
  • O(1) - We are not using any extra space that grows with input size; we are only using a fixed amount of space for variables.

Time and Space Complexity Table for Insertion in Array

Insertion Type Time Complexity Space Complexity
Insert at Start O(n) O(1)
Insert at Specific Position O(n) O(1)
Insert at End O(1) O(1)

Summary

In this tutorial, we have explored:

  • Inserting an element at the start of an array
  • Inserting an element at a specific position in an array
  • Inserting an element at the end of an array
  • The time and space complexity for each insertion method
  • Code examples in C, C++, Java, Python, and JavaScript for each insertion method
  • Why size and capacity are maintained as global variables

Share & Connect