Resource identifiers in URLs in Rest API - Time & Space Complexity
When using resource identifiers in URLs, it's important to see how the system handles requests as the number of resources grows.
We want to know how the time to find or access a resource changes when there are more resources.
Analyze the time complexity of the following code snippet.
GET /users/{userId}
// Server receives a request with a userId in the URL
// It looks up the user in a database or data store by that ID
// Then returns the user data as a response
This code handles a request to get a user by their unique ID from a collection of users.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Searching for the user by ID in the data store.
- How many times: Depends on the data structure; could be one direct lookup or a search through all users.
As the number of users grows, the time to find one user depends on how the data is stored.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 or 1 (depending on lookup method) |
| 100 | 100 or 1 |
| 1000 | 1000 or 1 |
Pattern observation: If the system searches through all users, operations grow with n; if it uses direct lookup, operations stay about the same.
Time Complexity: O(1)
This means finding a user by their ID takes about the same time no matter how many users there are, assuming a direct lookup method.
[X] Wrong: "Finding a user by ID always takes longer as the number of users grows."
[OK] Correct: Many systems use direct lookup methods like hash tables or indexed databases, so the time stays constant regardless of size.
Understanding how resource identifiers affect lookup time helps you explain efficient API design and data access in real projects.
"What if the user data was stored in a simple list without indexing? How would the time complexity change?"