What is complexity of this code snippet?

Technology CommunityCategory: Big-O NotationWhat is complexity of this code snippet?
VietMX Staff asked 3 years ago
Problem

Let’s say we wanted to find a number in the list:

for (int i = 0; i < n; i++){
    if(array[i] == numToFind){ return i; }
}

What will be the time complexity (Big O) of that code snippet?

This would be O(n) since at most we would have to look through the entire list to find our number. The Big-O is still O(n) even though we might find our number the first try and run through the loop once because Big-O describes the upper bound for an algorithm.