Suppose we have a file system that stores both files and directories. Given a string input representing the file system in a specific format, return the length of the longest absolute path to a file in the abstracted file system.
The input string uses \n (newline) to separate different files/directories, and \t (tab) characters to represent the depth level in the directory hierarchy.
Each file name is of the form name.extension, while directory names consist of letters, digits, and/or spaces without extensions.
The key insight is to use a stack to efficiently track directory path lengths at each nesting level. Best approach is the stack-based solution which processes input in a single pass. Time: O(n), Space: O(d) where d is maximum directory depth.
Common Approaches
✓
Dfs
⏱️ Time: N/A
Space: N/A
Optimized
⏱️ Time: N/A
Space: N/A
Generate All Paths
⏱️ Time: O(n²)
Space: O(n²)
Parse the input to build the complete directory tree structure, then recursively generate all possible paths to files and track the maximum length.
Stack-Based Path Tracking
⏱️ Time: O(n)
Space: O(d)
Parse the input line by line, use a stack to maintain the current directory path lengths based on indentation depth. When encountering a file, calculate the total path length.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char input_buffer[10000];
static char* lines[1000];
static int line_count = 0;
int max(int a, int b) {
return a > b ? a : b;
}
int count_tabs(const char* line) {
int count = 0;
while (line[count] == '\t') {
count++;
}
return count;
}
int is_file(const char* name) {
return strchr(name, '.') != NULL;
}
int dfs(int start_idx, int target_depth, const char* current_path) {
int max_len = 0;
for (int i = start_idx; i < line_count; i++) {
const char* line = lines[i];
int depth = count_tabs(line);
// If we've gone back to a shallower depth, we're done with this subtree
if (depth < target_depth) {
break;
}
// Only process items at exactly the target depth (immediate children)
if (depth == target_depth) {
const char* name = line + depth; // Skip tabs
// Build new path
char new_path[1000];
if (strlen(current_path) == 0) {
strcpy(new_path, name);
} else {
sprintf(new_path, "%s/%s", current_path, name);
}
if (is_file(name)) {
max_len = max(max_len, (int)strlen(new_path));
} else {
// It's a directory, explore its children
int child_max = dfs(i + 1, depth + 1, new_path);
max_len = max(max_len, child_max);
}
}
}
return max_len;
}
int solution(const char* input_str) {
if (!input_str || strlen(input_str) == 0) {
return 0;
}
// Split input by newlines
char* input_copy = malloc(strlen(input_str) + 1);
strcpy(input_copy, input_str);
line_count = 0;
char* token = strtok(input_copy, "\n");
while (token != NULL && line_count < 1000) {
lines[line_count] = malloc(strlen(token) + 1);
strcpy(lines[line_count], token);
line_count++;
token = strtok(NULL, "\n");
}
int result = dfs(0, 0, "");
// Free allocated memory
for (int i = 0; i < line_count; i++) {
free(lines[i]);
}
free(input_copy);
return result;
}
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
arr[(*size)++] = (int)strtol(p, (char**)&p, 10);
}
}
int main() {
// Read input
if (!fgets(input_buffer, sizeof(input_buffer), stdin)) {
printf("0\n");
return 0;
}
// Remove newline
int len = strlen(input_buffer);
if (len > 0 && input_buffer[len-1] == '\n') {
input_buffer[len-1] = '\0';
len--;
}
// Remove surrounding quotes if present
char* start = input_buffer;
char* end = input_buffer + len - 1;
if (*start == '"') start++;
if (*end == '"') *end = '\0';
// Process escaped characters
char processed[10000];
int j = 0;
for (int i = 0; start[i]; i++) {
if (start[i] == '\\' && start[i+1] == 'n') {
processed[j++] = '\n';
i++; // skip the 'n'
} else if (start[i] == '\\' && start[i+1] == 't') {
processed[j++] = '\t';
i++; // skip the 't'
} else {
processed[j++] = start[i];
}
}
processed[j] = '\0';
int result = solution(processed);
printf("%d\n", result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
✓ Linear Growth
Space Complexity
n
2n
✓ Linear Space
67.0K Views
MediumFrequency
~25 minAvg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.