Python 1598.py
class Solution:
def minOperations(self, logs: List[str]) -> int:
result = 0
for l in logs:
if l == "../":
result = max(0, result - 1)
elif l == "./":
pass
else:
result += 1
return result
Difficulty
and has an acceptance rate of about 72% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Stack
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single method minOperations. The method receives a list of string commands that simulate directory navigation and returns the minimum number of operations required to return to the main folder after executing all commands. The algorithm processes the log entries sequentially, maintaining a counter that represents the current depth relative to the main folder.
Core Logic
The algorithm revolves around a single integer variable that tracks the effective depth. The variable is initialized to zero, reflecting the starting position at the main folder.
result = 0
A for loop iterates over each log entry. The loop body distinguishes three possible patterns:
- The entry
"../"indicates moving one level up. The depth is decreased, but never allowed to become negative. This is achieved with themaxfunction, which clamps the value at zero.
if l == "../":
result = max(0, result - 1)
- The entry
"./"represents staying in the current directory. No change to the depth is required, and the code explicitly performs a no-op.
elif l == "./":
pass
- Any other string is interpreted as moving into a sub-folder. The depth counter is incremented accordingly.
else:
result += 1
After all entries have been processed, the counter holds the number of steps needed to return to the main folder, which is returned directly.
return result
Edge Cases Handled
The implementation gracefully manages several boundary conditions:
-
Excessive upward moves - When the log contains more
"../"commands than the current depth, themaxcall prevents the counter from dropping below zero, effectively treating attempts to move above the main folder as no-ops. -
Empty log list - If
logsis empty, the loop body never executes and the method returns the initial value0, correctly indicating that no operations are required. -
Repeated no-op entries - Multiple
"./"entries are ignored without affecting the counter, ensuring that redundant stay-in-place commands do not inflate the result. -
Unrecognized patterns - Any string that does not match the two explicit cases is automatically treated as a folder entry, incrementing the depth. This design implicitly supports folder names of arbitrary length and composition, as long as they end with a slash in the input format.
Performance Characteristics
The algorithm processes each log entry exactly once, updating a single integer variable. This approach yields constant auxiliary memory usage, as no additional data structures (such as stacks or lists) are allocated beyond the input itself. The use of the built-in max function for clamping the depth eliminates the need for an explicit conditional branch to check for negative values, which can be beneficial for branch prediction on modern CPUs. The overall flow is linear with respect to the number of log entries, providing an efficient solution for large input sizes.
ELI5 - Simplified Explanation
Imagine you are in a giant, magical house full of secret rooms. This code is like a little robot helper that keeps track of how deep inside the house you are. The robot starts at the entrance, where the number is zero. Every time the robot sees a list of places you visited, it follows a set of rules.
If the robot sees two dots and a slash, it means you turned around and walked out of the room you were in, so the robot subtracts one from the total count. If the robot sees a single dot and a slash, it means you stayed exactly where you were, so the robot does nothing and just keeps standing there. If the robot sees anything else, it means you opened a door and stepped into a new room, so the robot adds one to the count to show you are deeper inside. The robot keeps doing this for every instruction in the list until it reaches the final count.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Java | |||||||||
| leetcode.ca | C++ | Python | JS | Java | C | Go | Rust | TS | |||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| withaarzoo | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Java | ||||||||||
| leetcode.ca | C, C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| withaarzoo | C++ | ||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 682: Baseball Game
- problem 844: Backspace String Compare
Solved On The Same Day
- problem 1413: Minimum Value to Get Positive Step by Step Sum
- problem 1460: Make Two Arrays Equal by Reversing Subarrays
- problem 1507: Reformat Date
- problem 1944: Number of Visible People in a Queue
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality