Basic authentication in Rest API - Time & Space Complexity
When using basic authentication in a REST API, the server checks user credentials for each request.
We want to understand how the time to process a request changes as the number of users grows.
Analyze the time complexity of the following code snippet.
def authenticate(request):
auth_header = request.headers.get('Authorization')
if not auth_header:
return False
username, password = decode_basic_auth(auth_header)
user = find_user_in_database(username)
if user and user.password == password:
return True
return False
This code checks the Authorization header, decodes it, then looks up the user and verifies the password.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Searching for the user in the database.
- How many times: Once per request, but the search may scan many users depending on database structure.
As the number of users grows, the time to find a user can increase.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 user checks |
| 100 | 100 user checks |
| 1000 | 1000 user checks |
Pattern observation: The time grows roughly in direct proportion to the number of users if the search is simple.
Time Complexity: O(n)
This means the time to authenticate grows linearly with the number of users in the database.
[X] Wrong: "Authentication time stays the same no matter how many users exist."
[OK] Correct: If the user search is a simple scan, more users mean more checks, so time grows with user count.
Understanding how authentication scales helps you design APIs that stay fast as users grow, a key skill in real projects.
"What if the user data was stored in a hash map instead of a list? How would the time complexity change?"