cat (display file contents) in Linux CLI - Time & Space Complexity
When using the cat command to display file contents, it is helpful to understand how the time it takes grows as the file size grows.
We want to know how the command's work changes when the file gets bigger.
Analyze the time complexity of the following code snippet.
cat filename.txt
This command reads and shows the entire content of filename.txt on the screen.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading each byte or line from the file one by one.
- How many times: Once for every byte or line in the file, depending on implementation.
As the file size grows, the number of bytes to read grows too, so the work grows in a straight line with file size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 bytes | About 10 read steps |
| 100 bytes | About 100 read steps |
| 1000 bytes | About 1000 read steps |
Pattern observation: The work grows directly in proportion to the file size.
Time Complexity: O(n)
This means the time to display the file grows linearly as the file gets bigger.
[X] Wrong: "The cat command runs instantly no matter the file size."
[OK] Correct: Actually, cat must read every part of the file, so bigger files take more time.
Understanding how commands like cat scale with input size helps you think clearly about performance in real tasks.
"What if we used head -n 10 filename.txt instead? How would the time complexity change?"