Search⌘ K

Solution Review: Index Array

Understand how to implement index array solutions using nested loops in Go. Explore techniques to rearrange array elements to their correct index positions and handle missing values. Learn to analyze the time complexity and improve array manipulation skills through detailed example code.

First solution

We’ll use nested loops:

  • The outer loop will help us store the value of index i in curr.
  • In the inner loop, we have to swap the values to the respective index position in the array. If that position is not available, we have to place -1 there.
Go (1.6.2)
package main
import("fmt")
func indexArray(arr []int, size int) {
for i := 0; i < size; i++ {
curr := i
value := -1
/* swaps to move elements in the proper position. */
for arr[curr] != -1 && arr[curr] != curr {
temp := arr[curr]
arr[curr] = value
value = temp
curr = temp
}
/* check if some swaps happened. */
if value != -1 {
arr[curr] = value
}
}
}
/* Testing code */
func main() {
arr := []int{8, -1, 6, 1, 9, 3, 2, 7, 4, -1}
size := len(arr)
indexArray(arr, size)
fmt.Println(arr)
}

Time complexity

The time complexity of the solution is O(n) ...