Problem solution · Java

Design File System

Design File System: a Java solution using hash-based lookup. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Hash-based lookup
Source
walkccc LeetCode Solutions
Length
40 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

Hash-based lookup

For Design File System, the implementation stores previously seen values or frequencies in a hash table for direct membership and lookup operations.

  1. Decide the key that represents the information needed later.
  2. Update its count or stored state while scanning the input.
  3. Use constant-time expected lookups to detect matches or assemble the result.

Code notes

  • 40 lines of Java from the credited upstream file 1166.java.
  • The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
  • 2 loop blocks detected.

Complexity

Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.

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 codeDesign File System · JavaJava
Use this to learn the idea, then write your own version.
class TrieNode {  public Map<String, TrieNode> children = new HashMap<>();  public int value;  public TrieNode(int value) {    this.value = value;  }} class FileSystem {  public boolean createPath(String path, int value) {    final String[] subpaths = path.split("/");    TrieNode node = root;     for (int i = 1; i < subpaths.length - 1; ++i) {      if (!node.children.containsKey(subpaths[i]))        return false;      node = node.children.get(subpaths[i]);    }     final String lastSubpath = subpaths[subpaths.length - 1];    if (node.children.containsKey(lastSubpath))      return false;    node.children.put(lastSubpath, new TrieNode(value));    return true;  }   public int get(String path) {    final String[] subpaths = path.split("/");    TrieNode node = root;    for (int i = 1; i < subpaths.length; ++i) {      if (!node.children.containsKey(subpaths[i]))        return -1;      node = node.children.get(subpaths[i]);    }    return node.value;  }   private TrieNode root = new TrieNode(0);} 

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 ↗