Cassidoo’s Interview question of the week | 450

Hello :waving_hand:

This week question is about resolving file paths. Here it is

You are given a file system represented as an object where keys are absolute paths and values are either null (real file/directory) or a string (a symlink pointing to another path). Write a function that resolves a given path to its real destination, following symlinks along the way. If a symlink chain forms a cycle, return null .

const fs = {
  "/a": "/b",
  "/b": "/c",
  "/c": null,
  "/loop1": "/loop2",
  "/loop2": "/loop1",
  "/real": null,
  "/alias": "/real",
};

resolvePath(fs, "/a");      // "/c"
resolvePath(fs, "/alias");  // "/real"
resolvePath(fs, "/loop1");  // null
resolvePath(fs, "/real");   // "/real"

Happy coding.

2 Likes
Solution
def resolvePath fs, path
  fs = {**fs}
  while n = fs[path]
    fs[path] = false
    path = n
  end
  n == nil ? path : nil
end
1 Like
Solution
def resolve_path(filesystem, path, visited_paths = nil)
  visited_paths ||= []
  return nil if visited_paths.include?(path)
  visited_paths << path

  if filesystem[path].nil?
    path
  else
    resolve_path(filesystem, filesystem[path], visited_paths)
  end
end

This was a fun one!

My Solution
filesystem = {
“/a” => “/b”,
“/b” => “/c”,
“/c” => nil,
“/loop1” => “/loop2”,
“/loop2” => “/loop1”,
“/real” => nil,
“/alias” => “/real”,
}

def resolve(filesystem, current, start = nil)
start ||= current

return current if filesystem[current] == nil
return nil if filesystem[current] == start

return resolve(filesystem, filesystem[current], start)
end

raise unless resolve(filesystem, “/a”) == “/c”
raise unless resolve(filesystem, “/alias”) == “/real”
raise unless resolve(filesystem, “/loop1”) == nil
raise unless resolve(filesystem, “/real”) == “/real”

puts “✓ Success”