Bird
Raised Fist0
DSA Goprogramming

Array Insertion at Middle Index in DSA Go

Choose your learning style10 modes available
Mental Model
To insert a new value in the middle of an array, we shift all elements from that position to the right by one place to make space.
Analogy: Imagine a row of chairs where you want to add a new person in the middle. Everyone from that spot onward must stand up and move one chair to the right to make room.
Index:  0   1   2   3   4
Array: [1]->[2]->[3]->[4]->[5]
Insert at index 2 (middle)
Dry Run Walkthrough
Input: array: [1, 2, 3, 4, 5], insert value 99 at index 2
Goal: Insert 99 at index 2 and shift elements right to keep order
Step 1: Start shifting elements from the last index to index 2 one position to the right
[1] -> [2] -> [3] -> [4] -> [5] -> null (before shift)
Why: We need to make space at index 2 by moving elements right
Step 2: Move element at index 4 (5) to index 5
[1] -> [2] -> [3] -> [4] -> [5] -> [5] -> null
Why: Shift last element right to free index 4
Step 3: Move element at index 3 (4) to index 4
[1] -> [2] -> [3] -> [4] -> [4] -> [5] -> null
Why: Shift element at index 3 right to free index 3
Step 4: Move element at index 2 (3) to index 3
[1] -> [2] -> [3] -> [3] -> [4] -> [5] -> null
Why: Shift element at index 2 right to free index 2
Step 5: Insert 99 at index 2
[1] -> [2] -> [99] -> [3] -> [4] -> [5] -> null
Why: Place new value in the freed space
Result:
[1] -> [2] -> [99] -> [3] -> [4] -> [5] -> null
Annotated Code
DSA Go
package main

import "fmt"

func insertAtMiddle(arr []int, val int, index int) []int {
	// Increase slice size by 1 to hold new element
	arr = append(arr, 0)
	// Shift elements right from the end to index
	for i := len(arr) - 2; i >= index; i-- {
		arr[i+1] = arr[i] // shift element right
	}
	// Insert new value at index
	arr[index] = val
	return arr
}

func main() {
	arr := []int{1, 2, 3, 4, 5}
	index := 2
	val := 99
	newArr := insertAtMiddle(arr, val, index)
	// Print array in arrow format
	for i, v := range newArr {
		fmt.Print(v)
		if i != len(newArr)-1 {
			fmt.Print(" -> ")
		}
	}
	fmt.Println(" -> null")
}
arr = append(arr, 0)
Increase array size by one to make space for new element
for i := len(arr) - 2; i >= index; i-- {
Start shifting elements from the end towards the insertion index
arr[i+1] = arr[i] // shift element right
Move element one position to the right to free space
arr[index] = val
Insert the new value at the specified index
OutputSuccess
1 -> 2 -> 99 -> 3 -> 4 -> 5 -> null
Complexity Analysis
Time: O(n) because in the worst case we shift half of the elements to the right
Space: O(n) because we create a new slice with one extra space
vs Alternative: Compared to appending at the end which is O(1), insertion in the middle requires shifting elements, making it O(n)
Edge Cases
Insert at index 0 (start of array)
All elements shift right, new value placed at start
DSA Go
for i := len(arr) - 2; i >= index; i-- {
Insert at last index (end of array)
No shifting needed, new value appended
DSA Go
for i := len(arr) - 2; i >= index; i-- {
Empty array insertion
New array with single element returned
DSA Go
arr = append(arr, 0)
When to Use This Pattern
When you need to add an element inside an array and keep order, use shifting to make space before insertion.
Common Mistakes
Mistake: Not shifting elements from the end, causing overwriting of data
Fix: Shift elements starting from the last index down to the insertion index to avoid overwriting
Mistake: Appending the new element without increasing array size first
Fix: Always append a dummy element first to increase slice size before shifting
Summary
Inserts a new value at a given middle index by shifting elements right to make space.
Use when you want to add an element inside an array without losing existing data order.
The key is to shift elements from the end towards the insertion point before placing the new value.

Practice

(1/5)
1. What is the middle index of an array with 7 elements when inserting a new element?
easy
A. 3
B. 4
C. 2
D. 5

Solution

  1. Step 1: Calculate middle index for odd length array

    For an array of length 7, middle index = length / 2 = 7 / 2 = 3 (integer division).
  2. Step 2: Confirm insertion position

    The new element should be inserted at index 3 to be in the middle.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    Middle index = 7/2 = 3 [OK]
Hint: Middle index = length divided by 2 (integer division) [OK]
Common Mistakes:
  • Using length/2 + 1 for middle index
  • Confusing zero-based index with count
  • Using length/2 as float instead of integer
2. Which Go code snippet correctly inserts an element `x` at the middle index of slice `arr`?
easy
A. arr = append(arr, x)
B. arr = append(arr[:len(arr)/2], append([]int{x}, arr[len(arr)/2:]...)...)
C. arr = append(arr[:len(arr)/2], x, arr[len(arr)/2:])
D. arr = append(arr[:len(arr)/2+1], append([]int{x}, arr[len(arr)/2:]...)...)

Solution

  1. Step 1: Understand slice insertion in Go

    To insert at middle, split slice at middle index, append new element slice, then append remaining slice.
  2. Step 2: Check syntax correctness

    arr = append(arr[:len(arr)/2], append([]int{x}, arr[len(arr)/2:]...)...) correctly uses append with slices and variadic syntax to insert element at middle.
  3. Final Answer:

    arr = append(arr[:len(arr)/2], append([]int{x}, arr[len(arr)/2:]...)...) -> Option B
  4. Quick Check:

    Correct slice append syntax = arr = append(arr[:len(arr)/2], append([]int{x}, arr[len(arr)/2:]...)...) [OK]
Hint: Use append with slices and variadic ... to insert at middle [OK]
Common Mistakes:
  • Trying to append element directly without wrapping in slice
  • Incorrect index calculation with +1
  • Appending element at end instead of middle
3. What is the output of this Go code?
arr := []int{1, 2, 3, 4}
mid := len(arr) / 2
arr = append(arr[:mid], append([]int{99}, arr[mid:]...)...)
fmt.Println(arr)
medium
A. [1 2 99 3 4]
B. [1 2 3 99 4]
C. [99 1 2 3 4]
D. [1 2 3 4 99]

Solution

  1. Step 1: Calculate middle index

    len(arr) = 4, so mid = 4 / 2 = 2.
  2. Step 2: Insert 99 at index 2

    arr[:2] = [1, 2], arr[2:] = [3, 4]. Insert 99 between them.
  3. Step 3: Resulting array

    New arr = [1, 2, 99, 3, 4]
  4. Final Answer:

    [1 2 99 3 4] -> Option A
  5. Quick Check:

    Insert 99 at index 2 = [1 2 99 3 4] [OK]
Hint: Middle index = length/2; insert element at that index [OK]
Common Mistakes:
  • Inserting element at wrong index
  • Appending element at end instead of middle
  • Misunderstanding slice append syntax
4. Identify the error in this Go code that tries to insert 50 at the middle of slice `nums`:
nums := []int{10, 20, 30, 40}
mid := len(nums) / 2
nums = append(nums[:mid], 50, nums[mid:])
fmt.Println(nums)
medium
A. Middle index calculation is wrong
B. Slice nums is not initialized
C. Cannot append element and slice together without wrapping element in slice
D. fmt.Println syntax error

Solution

  1. Step 1: Check append syntax

    append(nums[:mid], 50, nums[mid:]...) tries to append int and slice variadically, which is invalid.
  2. Step 2: Correct approach

    Wrap 50 in a slice: append(nums[:mid], append([]int{50}, nums[mid:]...)...).
  3. Final Answer:

    Cannot append element and slice together without wrapping element in slice -> Option C
  4. Quick Check:

    Append element + slice needs nested append [OK]
Hint: Wrap single element in slice when appending with another slice [OK]
Common Mistakes:
  • Appending element and slice directly together
  • Incorrect middle index calculation
  • Forgetting variadic ... operator
5. Given a slice `data := []int{5, 10, 15, 20, 25}`, write the correct Go code to insert `100` exactly in the middle, then print the updated slice.
hard
A. mid := len(data)/2 data = append(data[:mid], 100, data[mid:]) fmt.Println(data)
B. mid := len(data)/2 data = append(data[:mid+1], append([]int{100}, data[mid:]...)...) fmt.Println(data)
C. mid := len(data)/2 data = append(data, 100) fmt.Println(data)
D. mid := len(data)/2 data = append(data[:mid], append([]int{100}, data[mid:]...)...) fmt.Println(data)

Solution

  1. Step 1: Calculate middle index

    len(data) = 5, so mid = 5 / 2 = 2 (integer division).
  2. Step 2: Insert 100 at index 2 correctly

    Use nested append: append(data[:mid], append([]int{100}, data[mid:]...)...).
  3. Step 3: Print updated slice

    Prints [5 10 100 15 20 25].
  4. Final Answer:

    mid := len(data)/2 data = append(data[:mid], append([]int{100}, data[mid:]...)...) fmt.Println(data) -> Option D
  5. Quick Check:

    Insert at middle with nested append = mid := len(data)/2 data = append(data[:mid], append([]int{100}, data[mid:]...)...) fmt.Println(data) [OK]
Hint: Use nested append with slices to insert element at middle [OK]
Common Mistakes:
  • Using mid+1 instead of mid for insertion
  • Appending element at end instead of middle
  • Appending element and slice without wrapping element
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard