pwd (print working directory) in Linux CLI - Time & Space Complexity
Let's see how the time it takes to run the pwd command changes as we use it in different situations.
We want to know how the command's work grows when the environment changes.
Analyze the time complexity of the following command.
pwd
This command prints the current directory path you are in.
Look for any repeated work inside the command.
- Primary operation: The command reads the current directory path from the system.
- How many times: It does this once each time you run
pwd.
The time to run pwd grows linearly with the length of the directory path.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 (short path) | Proportional to 10 |
| 100 (longer path) | Proportional to 100 |
| 1000 (very long path) | Proportional to 1000 |
Pattern observation: The work increases linearly with longer paths.
Time Complexity: O(n)
This means the time to run pwd increases linearly with the directory depth.
[X] Wrong: "The longer the directory path, the longer pwd takes to run."
[OK] Why it's right: The system typically builds the full path by walking up each directory, so pwd takes longer with deeper directories.
Understanding simple commands like pwd helps build a strong foundation for more complex scripting tasks.
"What if pwd had to build the full path by walking up each directory? How would the time complexity change?"