Problem solution · Java

Longest Absolute File Path

Longest Absolute File Path: a Java solution using stack-based processing. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Stack-based processing
Source
walkccc LeetCode Solutions
Length
34 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Stack-based processing

For Longest Absolute File Path, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.

  1. Define what every stack entry represents.
  2. Pop entries once the current item resolves or invalidates them.
  3. Push the current item with only the information later steps need.

Code notes

  • 34 lines of Java from the credited upstream file 388.java.
  • The implementation visibly relies on work queue.
  • 2 loop blocks detected.

Complexity

If each item is pushed and popped at most once, the stack work is linear.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeLongest Absolute File Path · JavaJava
Use this to learn the idea, then write your own version.
class T {  public int depth;  public int length;  public T(int depth, int length) {    this.depth = depth;    this.length = length;  }} class Solution {  public int lengthLongestPath(String input) {    int ans = 0;    Deque<T> stack = new ArrayDeque<>();    stack.push(new T(-1, 0));     for (String token : input.split("\n")) {      final int depth = getDepth(token);      token = token.replace("\t", "");      while (depth <= stack.peek().depth)        stack.pop();      if (token.contains(".")) // `token` is file.        ans = Math.max(ans, stack.peek().length + token.length());      else // directory + '/'        stack.push(new T(depth, stack.peek().length + token.length() + 1));    }     return ans;  }   private int getDepth(final String token) {    return (int) token.chars().filter(c -> c == '\t').count();  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗