0
0
DSA Goprogramming~5 mins

Linear Search Algorithm in DSA Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Linear Search Algorithm
O(n)
Understanding Time Complexity

We want to understand how the time taken by linear search changes as the list size grows.

How many steps does it take to find an item or decide it's not there?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

func linearSearch(arr []int, target int) int {
    for i, val := range arr {
        if val == target {
            return i
        }
    }
    return -1
}

This code looks through each item in the list one by one to find the target value.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking each element in the list one by one.
  • How many times: Up to n times, where n is the number of items in the list.
How Execution Grows With Input

As the list gets bigger, the number of checks grows roughly the same as the list size.

Input Size (n)Approx. Operations
10Up to 10 checks
100Up to 100 checks
1000Up to 1000 checks

Pattern observation: The work grows linearly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the item grows directly with the list size.

Common Mistake

[X] Wrong: "Linear search always takes the same time no matter the list size."

[OK] Correct: The search time depends on where the target is or if it is missing, so bigger lists usually take more time.

Interview Connect

Understanding linear search time helps you compare it with faster methods and shows you can analyze simple algorithms clearly.

Self-Check

"What if the list was sorted and we used binary search instead? How would the time complexity change?"