cp (copy files and directories) in Linux CLI - Time & Space Complexity
When copying files or directories, it is important to understand how the time taken grows as the amount of data increases.
We want to know how the copy command's work changes when copying more or larger files.
Analyze the time complexity of the following copy command.
cp -r source_dir/ destination_dir/
This command copies all files and folders inside source_dir recursively into destination_dir.
Look at what repeats during the copy process.
- Primary operation: Reading and writing each file's data.
- How many times: Once for every file and folder inside the source directory, including nested ones.
The time to copy grows as the total number of files and their sizes increase.
| Input Size (n files) | Approx. Operations |
|---|---|
| 10 | Copy 10 files, reading and writing each once. |
| 100 | Copy 100 files, about 10 times more work than 10 files. |
| 1000 | Copy 1000 files, about 100 times more work than 10 files. |
Pattern observation: The work grows roughly in direct proportion to the number of files and their sizes.
Time Complexity: O(n)
This means the time to copy grows linearly with the number of files and their total size.
[X] Wrong: "Copying a directory is always fast because it just copies folder names."
[OK] Correct: The command copies every file inside, not just folder names, so the time depends on all file sizes and counts.
Understanding how copying scales helps you reason about file operations in scripts and automation, a useful skill in many real-world tasks.
"What if we copy only a single large file instead of many small files? How would the time complexity change?"