1233. Remove Sub-Folders from the Filesystem #747
-
Topics: Given a list of folders If a The format of a path is one or more concatenated strings of the form:
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can utilize a combination of sorting and string comparison. The steps below outline a solution in PHP:
Let's implement this solution in PHP: 1233. Remove Sub-Folders from the Filesystem <?php
function removeSubfolders($folders) {
// Step 1: Sort folders lexicographically
sort($folders);
// Step 2: Initialize result array
$result = [];
// Step 3: Loop through each folder
foreach ($folders as $folder) {
// Check if the current folder is a sub-folder of the last folder in result
if (empty($result) || strpos($folder, end($result) . '/') !== 0) {
// If it's not a sub-folder, add it to the result
$result[] = $folder;
}
}
return $result;
}
// Test cases
$folder1 = ["/a","/a/b","/c/d","/c/d/e","/c/f"];
$folder2 = ["/a","/a/b/c","/a/b/d"];
$folder3 = ["/a/b/c","/a/b/ca","/a/b/d"];
print_r(removeSubfolders($folder1)); // Output: ["/a","/c/d","/c/f"]
print_r(removeSubfolders($folder2)); // Output: ["/a"]
print_r(removeSubfolders($folder3)); // Output: ["/a/b/c","/a/b/ca","/a/b/d"]
?> Explanation:
This approach is efficient with a time complexity of O(n log n) due to the sorting step, and the linear scan has O(n), making this a good solution for larger inputs within the problem's constraints. |
Beta Was this translation helpful? Give feedback.
We can utilize a combination of sorting and string comparison. The steps below outline a solution in PHP:
Sort the Folders Lexicographically: Sorting the folder paths in lexicographical order ensures that any sub-folder will follow its parent folder immediately. For example,
"/a"
will be followed by"/a/b"
in the sorted list, allowing us to check for sub-folder relationships easily.Identify and Filter Out Sub-Folders: We can iterate through the sorted list, checking if the current folder path is a sub-folder of the previously added path. If it is, we skip it. If not, we add it to our result list.
Implement the Solution in PHP: We keep track of the last folder path added to the resu…