Clean directories with recursion – Code

Clean directories is to clean out files that are older than certain dates, and also remove the empty directories after the files are deleted. This can be done using recursion.

clean directories

Recursion is a technique that a function calls itself.  When the base condition is met, the rest of call stacks return from the last call to the first. It is used to solve many math problem such as factorial numbers. It is also used in data structures such as trees and graphs. 

File system is a recursive system as well. At root, there are directories. A directory has multiple directories and files. All programming languages provides the classes and methods to access file system. Files and directories can be created, checked and deleted using the libraries.

LinkedIn Interview Question:
Write a function that cleans out files older than a user specified number of days, and removes empty directories recursively.

Java Code:

Output:
file is deleted.
file is deleted.
file is deleted.
file is deleted.
Folder Name :folder\oldfiles\subfolder is deleted.

O notation:
Time complexity is O(n), n is the number of files/directories.
space complexity is O(m), m is the depth of the recursion.


Download CleanDirectories.java
Clean directories with recursion (YouTube)
Java Coding Interview Pocket Book (2nd Edition)

Comments are closed