Data Structures · Visualization
Insert at Index
Array
Inserting into an array means placing a new value at a chosen position while keeping every other value in order. Time: O(n) worst case (inserting near the start shifts almost everything). Space: O(1) extra space (in-place, ignoring possible resize).
Big-O: Random access O(1); insert/delete in the middle O(n).
Insert at Index
ArrayInserting into an array means placing a new value at a chosen position while keeping every other value in order. Since array slots are packed tightly with no gaps, making room for a new item means physically sliding every element after that position one slot to the right first.
How Insert at Index Works
- Make sure there is enough space at the end of the array (grow it if needed).
- Starting from the last element, shift each element one position to the right, working backward toward the target index.
- Stop shifting once you reach the target index, leaving it empty.
- Place the new value into the now-empty target index.
Insert at Index Worked Example
Input: Insert 40 at index 2 into [10, 20, 30, 50]
- Shift 50 from index 3 to index 4: [10, 20, 30, 50, 50]
- Shift 30 from index 2 to index 3: [10, 20, 30, 30, 50]
- Index 2 is now free — place 40 there: [10, 20, 40, 30, 50]
Output: [10, 20, 40, 30, 50]
Press ▶ Run to watch it step by step.
def insert_at(arr, index, value):
arr.append(0) # grow by one
for i in range(len(arr) - 1, index, -1):
arr[i] = arr[i - 1] # shift right
arr[index] = value
return arr
a = [10, 20, 30, 50]
insert_at(a, 2, 99) # [1, 2, 99, 3, 4]
# example: insert 40 at index 2 on [10, 20, 30, 50]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Insert at Index Time & Space Complexity
When to Use Insert at Index
- Keeping a sorted list of scores or leaderboard entries in order
- Inserting a task at a specific priority position in a to-do list
- Placing an element mid-sequence while preserving order, e.g. a playlist
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.