15% off all plans & roadmaps Use code

See plans

Crawler Log Folder

Updated

TL;DR: Count how many folders deep you are after all the moves, and never let that count drop below the main folder. A `../` removes one level, `./` changes nothing, and any folder name adds one level.

Problem

A file system logs each time a user performs a change folder operation. There are three kinds of operation:

  • "../": move to the parent folder. If you are already in the main folder, stay in the same folder.
  • "./": stay in the same folder.
  • "x/": move to the child folder named x. This folder is guaranteed to exist.

You receive a list of strings logs, where logs[i] is the operation performed at step i. The file system starts in the main folder, and then the operations run in order. Return the minimum number of operations needed to go back to the main folder after the change folder operations.

Example 1

Input: logs = ["d1/","d2/","../","d21/","./"]
Output: 2
Explanation: Use the operation "../" 2 times to go back to the main folder.

Example 2

Input: logs = ["d1/","d2/","./","d3/","../","d31/"]
Output: 3

Example 3

Input: logs = ["d1/","../","../","../"]
Output: 0

Constraints

  • 1 <= logs.length <= 10^3
  • 2 <= logs[i].length <= 10
  • logs[i] contains lowercase English letters, digits, '.', and '/'.
  • logs[i] follows the format described above.
  • Folder names consist of lowercase English letters and digits.

Constraints that matter

  • logs.length is at most 10^3, so even an O(n^2) scan would run fast. Time is not the hard part of this problem.
  • Each log has at most 10 characters, so comparing a log with ../ or ./ costs a fixed amount of work.
  • Folder names are never needed for the answer, so the solution does not have to store them.
  • The main folder is a floor. A ../ at depth 0 must change nothing, so the counter must check for 0 before it decrements.

View on LeetCode

Hints

Hint 1

The operations behave like a backspace key.

Hint 2

Simulate the file system the way a shell tracks a path.

Solution

Intuition

The operations behave like a backspace key. A folder name moves you one level deeper, and ../ removes the most recent level. This matches the string comparison with backspaces idea from the two pointers family. LeetCode 844 uses the same undo logic, where a # erases the character before it.

It is like a tally counter on a turnstile. The depth integer is that counter: each child folder clicks it up by one, each ../ clicks it down, and it never goes below zero.

Notice what the question asks for. It asks for a count of levels, not the path itself. Folder names never affect that count, and ./ never changes it. That means you only need to track how deep you are.

The rule that matters is the floor at the main folder. A ../ at depth 0 must do nothing, so the counter can never go negative. Each log changes the counter by at most one, and the counter always equals the number of folders on the current path.

Watch the pattern animation

Worked example

Input: logs = ["../", "../", "./", "../"]
Output: 0
Explanation: The file system starts in the main folder, which has no parent. Each ../ at depth 0 stays put. The ./ does nothing, so the depth never leaves 0 and the answer is 0.

Approach 1: Brute force: stack of folder names

Simulate the file system the way a shell tracks a path. Keep a stack with one entry per folder on the current path. A child folder pushes its name, a ../ pops the top name when the stack is not empty, and ./ is skipped.

This is correct, and it is usually the first version people write. It stores every folder name even though the names never change the result. Only the number of entries matters, so the stored names are wasted memory.

Steps

  1. Create an empty stack of strings to hold the folder names on the current path.
  2. Loop over the logs in order.
  3. If the log is ../ and the stack is not empty, pop the top name. If the stack is empty, do nothing.
  4. If the log is ./, skip it.
  5. Otherwise the log is a child folder, so push it onto the stack.
  6. Return the size of the stack.

Dry run

Trace on logs = ["../", "../", "./", "../"]. The stack starts empty, and step 1 is ../. The stack is empty, so nothing is popped. Step 2 is another ../ on an empty stack, which changes nothing.

Step 3 is ./, which is skipped. Step 4 is ../ on an empty stack again. The stack is empty at the end, so the function returns 0.

Complexity

TimeO(n)
SpaceO(n)

Let n be the number of logs. The loop runs once per log, and each iteration compares a log of at most 10 characters with two fixed strings and does at most one push or pop, so the time is O(n). The stack can hold up to n names, each at most 10 characters, so the space is O(n) here, or O(n * L) in general where L is the longest log.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def minOperations(self, logs: List[str]) -> int:
        stack = []  # folder names on the current path
        for log in logs:
            if log == "../":
                if stack:
                    stack.pop()
            elif log == "./":
                continue
            else:
                stack.append(log)
        return len(stack)

The String Comparison with Backspaces infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

String Comparison with Backspaces

Part of Two Pointers

Approach 2: One-pass depth counterOptimalString Comparison with Backspaces

The stack is slow in memory. It keeps every folder name, but the answer only uses the number of entries. Each name is stored, read for its count, and never used again.

The insight that fixes it: the answer is the stack size, so replace the stack with one integer named depth. A child folder adds 1, a ../ subtracts 1 unless depth is already 0, and a ./ changes nothing. Depth always equals the stack size, so the output is the same.

Why it is correct. The invariant is that depth always equals the number of folders on the current path. Each log changes that path length by at most one, and the zero floor matches the rule for the main folder. Folder names and ./ leave the count alone, so skipping them never loses anything the answer needs.

Steps

  1. Set depth to 0. It counts how many folders deep you are.
  2. Loop over the logs in order.
  3. If the log is ../, subtract 1 from depth, but only when depth is greater than 0.
  4. If the log is ./, skip it.
  5. Otherwise the log is a child folder, so add 1 to depth.
  6. Return depth.

Dry run

Trace on logs = ["../", "../", "./", "../"]. Each row shows the state before and after one log.

StepLogDepth beforeActionDepth after
startnone0begin in main folder0
1../0depth is 0, so stay put0
2../0depth is 0, so stay put0
3./0skip0
4../0depth is 0, so stay put0

The loop ends with depth 0, which is the output.

Complexity

TimeO(n)
SpaceO(1)

Let n be the number of logs. The loop body runs once per log, and each iteration does a fixed number of string comparisons, since each log has at most 10 characters, plus one integer update. The time is therefore O(n). The only state is the integer depth, so the extra space does not grow with n, which gives O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def minOperations(self, logs: List[str]) -> int:
        depth = 0  # how many folders deep we are
        for log in logs:
            if log == "../":
                if depth > 0:  # never go above the main folder
                    depth -= 1
            elif log == "./":
                continue
            else:
                depth += 1
        return depth

Common mistakes

  • Decrementing without a floor check, as in depth-- with no depth > 0 test. A leading ../ drives depth to -1, and every later count is off by one. Guard the decrement, or clamp with max(0, depth - 1).
  • Checking only for startswith('..') and forgetting ./. The ./ log then falls into the child branch and adds 1. Give ./ its own branch that changes nothing.
  • Comparing strings with == in Java, as in log == "../". Java compares references there, so the test can fail on equal text. Use log.equals("../") instead.
  • Popping an empty stack in the brute force, as in stack.pop() with no size check. Python raises IndexError, Java and C# throw, and Go slicing with index -1 panics. Check that the stack is not empty first.
  • Returning len(logs) or the number of non-parent logs. That counts operations, not depth, so it includes the ../ and ./ entries that should move you or change nothing.
  • Breaking out of the loop at the first ../ that hits the floor. Later logs can still move you deeper, so the loop must read every log.

Edge cases

  • ["../"] should return 0. A parent move from the main folder changes nothing.
  • ["./"] should return 0. Logs that only stay in place never change the depth.
  • ["a/", "../", "../"] should return 0. The second ../ hits the floor and is ignored.
  • ["a/", "a/", "a/"] should return 3. Repeated names are separate levels, and names never merge.
  • ["a/", "./", "b/", "../"] should return 1. A ./ in the middle changes nothing, and the final ../ removes one level.
  • A list of 1000 child folder logs should return 1000. The counter stays far inside the int range, so overflow is not a concern.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Crawler Log Folder, with how to answer them.

Unlock the follow-ups

Crawler Log Folder FAQ

What is the time complexity of Crawler Log Folder?

The depth counter runs in O(n) time, where n is the number of logs. Each log takes constant work because the logs have at most 10 characters. The brute force stack also runs in O(n) time.

Why use a depth counter for Crawler Log Folder?

The answer is the number of folders on the current path, and that number changes by at most 1 per log. A counter tracks it exactly, so you do not need to store the names. This reduces the space from O(n) to O(1).

Can Crawler Log Folder be solved in O(1) extra space?

Yes. The depth counter uses one integer no matter how many logs there are. The stack of names is not needed, since the names never change the count.

Why is Crawler Log Folder filed under two pointers?

The depth counter uses one loop index and one integer, so it is a single pass, not a standard two pointer scan. The link comes from the backspace idea in LeetCode 844, where two pointers read a string from the end and skip erased characters. The undo logic in this problem is the same, even though the code is simpler.

Why does the Java solution use equals instead of ==?

In Java, == on strings compares object references, not the text. Two strings with the same characters can be different objects, so == may return false for a match. Use equals to compare the text of each log.

Asked at

See which companies ask this — Pro

Practise it