Link relations in responses in Rest API - Time & Space Complexity
When a REST API includes link relations in its responses, it adds extra steps to build those links.
We want to know how the time to create these links grows as the response size grows.
Analyze the time complexity of the following code snippet.
function buildResponse(items) {
return items.map(item => ({
data: item,
links: {
self: `/items/${item.id}`,
related: `/items/${item.id}/related`
}
}));
}
This code creates a response array where each item includes its data and two link relations.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The map function loops over each item once.
- How many times: Exactly once per item in the input array.
As the number of items grows, the number of link creations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 link creations (2 per item) |
| 100 | 200 link creations |
| 1000 | 2000 link creations |
Pattern observation: The work grows directly with the number of items, doubling for twice as many items.
Time Complexity: O(n)
This means the time to build the response grows in a straight line with the number of items.
[X] Wrong: "Adding link relations does not affect time because itβs just a small addition."
[OK] Correct: Even small additions happen for every item, so the total time adds up as the list grows.
Understanding how adding links affects response time helps you design APIs that stay fast as data grows.
What if we added nested link relations inside each related item? How would the time complexity change?