0

I am trying to calculate the time complexity of this algorithm and failing horribly I think. Can anyone tell if I'm on the right track here? any help would be greatly appreciated. (:

data = [["Jacob", "91"], ["John", "81"], ["James", "71"], ["Joe", "61"]] size n


name = "Joe"
not_found = True
index = 0
marks = 0


for i in range(len(data)): # n
    if name == data[i][0]: # n(3)
        marks = data[i][1] # n(3)(3)
print(marks) #1

#T(n) = n + 3n +9n^2 + 1
#T(n) = 9n^2 +4n + 1
#O(n) = 9n^2
1
  • 2
    It is O(n). You are iterating n times and every time you do a O(1) operation (if statement), and only once you get to do another O(1) operation (marks = ...), so O(n*1+1) -> O(n) Commented Mar 26, 2022 at 14:12

1 Answer 1

1

I think a better way to approach this problem is to think how many times you run the same command.

for i in range(len(data)): 
    if name == data[i][0]:
        marks = data[i][1]  # <- this command only runs n times

so this is O(n), since you run this command n times

marks = 0
for _ in range(len(data)): 
    for _ in range(len(data)): 
        marks += 1  #  <- this command only runs n^2 times

so this is O(n^2)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.