0
0
Linux CLIscripting~5 mins

cp (copy files and directories) in Linux CLI - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: cp (copy files and directories)
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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

The time to copy grows as the total number of files and their sizes increase.

Input Size (n files)Approx. Operations
10Copy 10 files, reading and writing each once.
100Copy 100 files, about 10 times more work than 10 files.
1000Copy 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.

Final Time Complexity

Time Complexity: O(n)

This means the time to copy grows linearly with the number of files and their total size.

Common Mistake

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

Interview Connect

Understanding how copying scales helps you reason about file operations in scripts and automation, a useful skill in many real-world tasks.

Self-Check

"What if we copy only a single large file instead of many small files? How would the time complexity change?"