0
0
Goprogramming~5 mins

Defining structs in Go - Time & Space Complexity

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

When we define structs in Go, we want to know how much time it takes to create and use them as our program grows.

We ask: How does the time to handle structs change when we have more data or more fields?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

type Person struct {
    Name string
    Age  int
}

func createPeople(n int) []Person {
    people := make([]Person, n)
    for i := 0; i < n; i++ {
        people[i] = Person{Name: "Name", Age: i}
    }
    return people
}

This code defines a struct Person and creates a slice of n Person structs, filling each with data.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that runs n times to create each Person struct.
  • How many times: Exactly n times, once for each element in the slice.
How Execution Grows With Input

As n grows, the number of times we create and assign structs grows the same way.

Input Size (n)Approx. Operations
1010 struct creations and assignments
100100 struct creations and assignments
10001000 struct creations and assignments

Pattern observation: The work grows directly with n; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to create the structs grows in a straight line with the number of structs you want to make.

Common Mistake

[X] Wrong: "Creating structs is instant and does not depend on how many I create."

[OK] Correct: Each struct creation takes time, so more structs mean more time spent.

Interview Connect

Understanding how struct creation scales helps you explain how your program handles data efficiently as it grows.

Self-Check

"What if we added a nested struct inside Person? How would the time complexity change when creating many Persons?"