Self link for current resource in Rest API - Time & Space Complexity
When a REST API returns a self link for the current resource, it often builds a URL dynamically.
We want to understand how the time to create this link changes as the resource data grows.
Analyze the time complexity of the following code snippet.
GET /users/{id}
function getUserResponse(userId) {
const user = database.findUserById(userId);
const selfLink = `/users/${user.id}`;
return { data: user, links: { self: selfLink } };
}
This code fetches a user by ID and creates a self link URL for that user.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Searching the database for the user by ID.
- How many times: Once per request, no loops in link creation.
The time to build the self link string stays about the same regardless of user data size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 users | Search once + build link once |
| 100 users | Search once + build link once |
| 1000 users | Search once + build link once |
Pattern observation: The link creation cost does not grow with input size; it is constant.
Time Complexity: O(1)
This means creating the self link takes the same amount of time no matter how many users exist.
[X] Wrong: "Building the self link takes longer if the user data is bigger."
[OK] Correct: The self link is just a short string using the user ID, so its creation time stays constant regardless of user data size.
Understanding how small parts of an API scale helps you write efficient and predictable code, a skill valued in real projects and interviews.
"What if the self link included a list of all related resources? How would the time complexity change?"