0
0
Rest APIprogramming~5 mins

Request headers (Content-Type, Accept) in Rest API - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Request headers (Content-Type, Accept)
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of headers increases, the loop runs more times, so processing takes longer.

Input Size (n)Approx. Operations
10About 10 loop checks
100About 100 loop checks
1000About 1000 loop checks

Pattern observation: The time grows directly with the number of headers.

Final Time Complexity

Time Complexity: O(n)

This means the time to process headers grows in a straight line as the number of headers increases.

Common Mistake

[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.

Interview Connect

Understanding how header processing scales helps you write efficient API code and explain your reasoning clearly in interviews.

Self-Check

What if we changed the code to process nested headers inside each header? How would the time complexity change?