AI for comparing schools and programs in AI for Everyone - Time & Space Complexity
When AI compares schools and programs, it processes lots of information to help make decisions.
We want to know how the time needed grows as more schools or programs are added.
Analyze the time complexity of the following code snippet.
for school in schools:
for program in school.programs:
score = evaluate(program)
results.append((school.name, program.name, score))
results.sort(key=lambda x: x[2], reverse=True)
This code goes through each school and its programs, evaluates each program, and then sorts all results by score.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops over schools and their programs to evaluate each program.
- How many times: Once for every program in every school.
- Secondary operation: Sorting the list of all evaluated programs once after collection.
As the number of schools and programs grows, the number of evaluations grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 schools with 5 programs each | 50 evaluations + sorting 50 items |
| 100 schools with 5 programs each | 500 evaluations + sorting 500 items |
| 100 schools with 50 programs each | 5,000 evaluations + sorting 5,000 items |
Pattern observation: The time grows roughly with the total number of programs, and sorting adds some extra time but less than the evaluations.
Time Complexity: O(p + p log p)
This means the time grows a bit faster than the number of programs because of sorting, but mostly it depends on how many programs there are.
[X] Wrong: "Sorting the results takes the most time, so it dominates the whole process."
[OK] Correct: Evaluating each program happens many times and usually takes more time overall than sorting, especially when there are many programs.
Understanding how AI processes many items helps you explain efficiency clearly, a useful skill in many tech discussions.
"What if the evaluation step was replaced by a simple lookup instead of a calculation? How would the time complexity change?"