Directory structure (single-level, two-level, tree, acyclic graph) in Operating Systems - Time & Space Complexity
When working with directory structures, it is important to understand how the time to find or manage files grows as the number of files and folders increases.
We want to know how the structure type affects the time it takes to access or organize files.
Analyze the time complexity of searching for a file in different directory structures.
// Example: Searching for a file in a directory
function searchFile(directory, filename) {
for (let file of directory.files) {
if (file.name === filename) {
return file;
}
}
return null;
}
This code searches through all files in a directory to find a file with a matching name.
Look at what repeats when searching for a file:
- Primary operation: Checking each file's name in the directory.
- How many times: Once for every file in the directory.
As the number of files grows, the search takes longer because it checks more files one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The time grows directly with the number of files; doubling files doubles the work.
Time Complexity: O(n)
This means the time to find a file grows in direct proportion to the number of files in the directory.
[X] Wrong: "Searching a file in any directory structure always takes the same time regardless of size."
[OK] Correct: Different directory structures organize files differently, so the time to find a file depends on how many files and folders must be checked.
Understanding how directory structures affect search time helps you explain file system design and efficiency clearly, a useful skill in many technical discussions.
What if the directory structure was a tree instead of a single-level list? How would the time complexity of searching for a file change?