Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Implement the `cd` command

Sharing is caring!

Problem statement
Implement the cd command i.e. given a function cd('a/b','c/../d/e/../f'), where 1st param is current directory and 2nd param is the sequence of operations, find the final directory that the user will be in when the cd command is executed.

Solution
I am going to use a Stack to solve this problem. The steps are as follows:
1. Split the current path around /.
2. Push each of the separate parts on the stack.
3. Split the command around /.
4. Iterate over the separate command parts. If part matches .. pop one directory from the stack. Else add to the stack.
5. Pop first element on the stack to get the final directory.

Full code

public class CDCommand {

    private static final String BACK = "..";
    private static final String SLASH = "/";

    private static String cd(String current, String commands) {
        Deque stack = new ArrayDeque();
        String[] split = current.split(SLASH);
        for (String cmd:split) {
            stack.push(cmd);
        }


        split = commands.split(SLASH);
        for (String cmd:split) {
            if (BACK.equals(cmd)) {
                if (!stack.isEmpty()) {
                    stack.pop();
                }
            } else {
                stack.push(cmd);
            }
        }

        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) {
            String cmd = stack.pop();
            sb.insert(0,cmd);
            sb.insert(0,SLASH);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(cd("a/b","c/../d/e/../f"));
    }
}