Pagination metadata in response in Rest API - Time & Space Complexity
When a REST API sends pagination metadata, it helps clients know how many pages or items exist.
We want to understand how the time to prepare this metadata changes as the data size grows.
Analyze the time complexity of the following code snippet.
// Example: Prepare pagination metadata
function getPaginationMetadata(totalItems, itemsPerPage) {
const totalPages = Math.ceil(totalItems / itemsPerPage);
return {
totalItems: totalItems,
itemsPerPage: itemsPerPage,
totalPages: totalPages
};
}
This code calculates total pages and returns metadata for pagination.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Simple arithmetic calculations (division and ceiling).
- How many times: Exactly once per request, no loops or repeated steps.
Explain the growth pattern intuitively.
| Input Size (totalItems) | Approx. Operations |
|---|---|
| 10 | 3 (division, ceiling, return) |
| 100 | 3 (same as above) |
| 1000 | 3 (same as above) |
Pattern observation: The number of operations stays the same no matter how many items there are.
Time Complexity: O(1)
This means the time to prepare pagination metadata does not grow with the number of items.
[X] Wrong: "Calculating pagination metadata takes longer as the number of items grows because it processes each item."
[OK] Correct: The code only uses total counts and simple math, so it does not look at each item individually.
Understanding that pagination metadata calculation is quick and constant time helps you explain efficient API design clearly and confidently.
"What if the code also counted items by scanning a list instead of using a total count? How would the time complexity change?"