Iterating over arrays in Go - Time & Space Complexity
When we go through each item in an array one by one, it takes some time. We want to understand how this time grows as the array gets bigger.
The question is: How does the work change when the array size changes?
Analyze the time complexity of the following code snippet.
package main
func sumArray(arr []int) int {
total := 0
for _, value := range arr {
total += value
}
return total
}
This code adds up all numbers in an array by visiting each element once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each element to total inside the loop.
- How many times: Once for every element in the array.
As the array gets bigger, the number of additions grows at the same pace.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of elements.
[X] Wrong: "Since the loop is simple, it must be constant time."
[OK] Correct: Even a simple loop does more work as the array grows. The time depends on how many elements there are.
Understanding how loops over arrays scale is a key skill. It helps you explain your code clearly and shows you know how programs behave with bigger data.
"What if we nested another loop inside to compare each element with every other? How would the time complexity change?"
Practice
range keyword do when used with an array in Go?Solution
Step 1: Understand the role of
Therangein loopsrangekeyword in Go is used to iterate over elements in arrays, slices, maps, and more, providing both the index and the value of each element.Step 2: Identify what
When used with an array,rangedoes with arraysrangereturns the index and the value of each element one by one, allowing you to process or read each item.Final Answer:
It lets you loop over each element and get its index and value. -> Option CQuick Check:
rangeloops with index and value [OK]
- Thinking range changes array size
- Assuming range sorts elements
- Believing range copies the array
nums in Go?Solution
Step 1: Recall Go's for-range loop syntax
In Go, the correct way to iterate over arrays or slices is usingfor index, value := range arraysyntax.Step 2: Match the syntax with the options
for i, v := range nums { fmt.Println(i, v) } usesfor i, v := range nums, which is the correct Go syntax. Other options use invalid or non-Go syntax.Final Answer:
for i, v := range nums { fmt.Println(i, v) } -> Option AQuick Check:
Go usesfor i, v := range array[OK]
- Using 'for i in nums' like Python
- Using 'foreach' which is not Go syntax
- Using parentheses in for loop header
nums := [3]int{10, 20, 30}
for i, v := range nums {
fmt.Println(i, v)
}Solution
Step 1: Understand the array and loop
The arraynumshas 3 elements: 10 at index 0, 20 at index 1, and 30 at index 2. The loop usesrangeto get index and value.Step 2: Trace the loop output
Each iteration prints the index and the value: first line prints "0 10", second "1 20", third "2 30".Final Answer:
0 10 1 20 2 30 -> Option DQuick Check:
Index and value printed in order [OK]
- Swapping index and value in print
- Expecting values as indexes
- Thinking code has syntax error
nums := [3]int{1, 2, 3}
for i, v = range nums {
fmt.Println(i, v)
}Solution
Step 1: Check the for loop variable declaration
In Go, when declaring variables in a for-range loop, you must use ':=' to declare and assign variables, not '='.Step 2: Identify the syntax error
The code uses '=' instead of ':=' infor i, v = range nums, which causes a syntax error.Final Answer:
Missing colon in 'for i, v = range nums' should be ':=' -> Option AQuick Check:
Use ':=' to declare variables in for-range loops [OK]
- Using '=' instead of ':=' in for loop
- Confusing assignment with comparison
- Incorrect array syntax blamed
nums := [5]int{1, 2, 3, 4, 5}, how can you create a new slice containing only the even numbers using iteration?Solution
Step 1: Understand the goal and array
The goal is to create a new slice with only even numbers from the arraynums. Arrays have fixed size, so we cannot remove elements from it.Step 2: Use for-range loop and append even values
We iterate overnumsusingfor _, v := range nums, check ifv % 2 == 0, and append those values to a new slice.Final Answer:
Use a for-range loop to check each value and append even numbers to a slice. -> Option BQuick Check:
Filter with for-range and append even numbers [OK]
- Trying to change array size directly
- Ignoring values in loop
- Multiplying instead of filtering
Ready to prove it?
Pass the test and this pattern moves unknown
