Request headers (Content-Type, Accept) in Rest API - Time & Space Complexity
When working with REST APIs, request headers like Content-Type and Accept help servers understand data formats.
We want to see how the time to process these headers changes as the number of headers grows.
Analyze the time complexity of the following code snippet.
function processHeaders(headers) {
if (headers['Content-Type']) {
// process Content-Type
}
if (headers['Accept']) {
// process Accept
}
// process other headers
for (const key in headers) {
// handle each header
}
}
This code checks for specific headers and then loops through all headers to process them.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through all headers with
for (const key in headers). - How many times: Once for each header in the request.
As the number of headers increases, the loop runs more times, so processing takes longer.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 loop checks |
| 100 | About 100 loop checks |
| 1000 | About 1000 loop checks |
Pattern observation: The time grows directly with the number of headers.
Time Complexity: O(n)
This means the time to process headers grows in a straight line as the number of headers increases.
[X] Wrong: "Checking specific headers like Content-Type takes extra time for each header."
[OK] Correct: Checking a few specific headers is a fixed cost and does not grow with the number of headers; only looping through all headers grows with input size.
Understanding how header processing scales helps you write efficient API code and explain your reasoning clearly in interviews.
What if we changed the code to process nested headers inside each header? How would the time complexity change?