0
0
Goprogramming~5 mins

Nested structs in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nested structs
O(n)
Understanding Time Complexity

When working with nested structs in Go, it's important to understand how accessing and processing them affects the time your program takes.

We want to see how the time grows when we work through nested structs.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

type Address struct {
    City  string
    State string
}

type Person struct {
    Name    string
    Age     int
    Address Address
}

func printCities(people []Person) {
    for _, p := range people {
        fmt.Println(p.Address.City)
    }
}

This code loops through a list of people and prints the city from their nested Address struct.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the slice of people.
  • How many times: Once for each person in the list.
How Execution Grows With Input

As the number of people increases, the number of times we print cities grows at the same rate.

Input Size (n)Approx. Operations
1010 prints
100100 prints
10001000 prints

Pattern observation: The work grows directly with the number of people.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of people.

Common Mistake

[X] Wrong: "Accessing nested structs makes the time complexity multiply or become slower than linear."

[OK] Correct: Accessing fields inside nested structs is a direct operation and does not add extra loops, so it does not increase the overall time complexity beyond the main loop.

Interview Connect

Understanding how nested structs affect time helps you explain your code clearly and shows you know how data structures impact performance.

Self-Check

"What if we added a nested loop inside the printCities function to loop over multiple addresses per person? How would the time complexity change?"