Amazon Interview Question for Software Engineer in Tests


Country: United States




Comment hidden because of low score. Click to expand.
0
of 0 vote

Sorry it becomes:
$/home/def/

- JSDUDE April 30, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

How does abc get eliminated and become def ??

- D April 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

abc is followed by a '..' which in UNIX means that the parent of this directory. So the parent of abc, which in this case is the folder: home.

- JSDUDE April 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;

public class Solution {
    public String simplifyPath(String path) {
        // Start typing your Java solution below
        // DO NOT write main() function
        Stack<String> stack = new Stack<String>();
        String[] str = path.split("/");
        for(int i = 0; i<str.length;i++){
            String sw = str[i];
            switch(sw){
                case ".":
                        break;
                case "..":
                        if(!stack.empty()){
                            stack.pop();
                        }
                        break;
                case "":
                        break;
                default:
                        stack.push(sw);
                        break;
                    
            }
        }
        String ret="";
        while(!stack.empty()){
            
            ret = "/" + stack.pop() + ret;
            
        }
       if(ret == ""){
	return "/";
	} 
        return ret;
    }

   public static void main(String[] args){
	Solution sol = new Solution();
	Scanner sc = new Scanner(System.in);
	while(1==1){
	String path = sc.nextLine();
	String ret=sol.simplifyPath(path);
	System.out.println(ret);
	}
	}

}

- vishwanathsingh9 April 30, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

I also proposed stack to which he approved and then asked for a solution without using extra space.

- JSDUDE April 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static String getPath(String [] dirs) {
		String path = "";
		int ignore =0;
		for(int i= dirs.length -1; i>=0 ; i--){
			if("..".equals(dirs[i])) {
				ignore++;
				continue;
			} else if(".".equals(dirs[i])) {
				continue;
			} else if (ignore > 0) {
				ignore--;
				continue;
			} else {
				path = dirs[i] + "/" + path;
			}
		}
		return path.toString();
	}
	
	public static void main(String [] args) {
		System.out.println(getPath("/home/abc/.././def/./ghi/../.".split("/")));
	
	}

- Anonymous April 30, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def cancel_path(p,i):
    p.pop() if (i == '..') else p.append(i)
    return p

def main():
    path = "$/home/abc/.././def/./ghi/../."

    new_path = []
    for e in [x for x in path.split('/') if x != '.']:
        cancel_path(new_path,e)
    print('/'.join(new_path))

if __name__=='__main__':
    main()

- Anonymous April 30, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I'd use Perl for this:

use warnings;
use strict;

my $pathStr = "/home/abc/.././def/./ghi/../.";
print "Before: $pathStr\n";

$pathStr =~ s/(\/[^\/]*\/)\.\.//g;
$pathStr =~ s/\/\.//g;
print "After: $pathStr\n";

- Anonymous May 01, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Sorry for useless question here but was this asked on phone or onsite??

- nr May 01, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Onsite.
Not an useless Q. I did enter that this was an Onsite Q, but I don't see that information on this page.
If any one knows where it is shown, please enlighten us :).

- JSDUDE May 04, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class UnixPath {
	public static String getPath(String inputPath) {
		String outPath = "";
		String[] dirs = inputPath.split("/");
		int ignore = 0;
		for(int index = dirs.length - 1; index >= 0 ; index--) {
			if(dirs[index].equals("..")) ignore += 1;
			else if(dirs[index].equals(".")) continue;
			else {
				if(ignore != 0) ignore -= 1;
				else outPath = dirs[index] + "/" + outPath; 
			}
		}
		return outPath;
	}
}

public class Main {
	public static void main(String args[]) {
		System.out.println(UnixPath.getPath("$/home/abc/.././def/./ghi/../."));
	}	
}

- Subhajit May 01, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
#include<vector>
#include<string>
#include<sstream>
#include<deque>
int main() {
	std::stringstream ss("/home/abc/.././def/./ghi/../.");
	std::string s;
	std::vector<std::string> dirs;

	while (getline(ss, s, '/')) {
		dirs.push_back(s);	
	}
	
	std::deque<std::string>  dirstack;	
	
	for(std::vector<std::string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
		if(*i == "..") {
			dirstack.pop_back();
		} else if (*i == ".") {
		} else {
			dirstack.push_back(*i);
		}
	}

	for(std::deque<std::string>::iterator i = dirstack.begin(); i != dirstack.end(); ++i) {
		std::cout << "/" << *i;
	}
	std::cout << std::endl;	
	return 0;
}

- Anonymous May 01, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is the Java Solution

public static void main(String[] args) {
		String input = "C:\\a\\b\\..\\.\\c\\d\\.";
		char[] chars = input.toCharArray();
		int length = chars.length;
		int i = 0;
		while (i < length) {
			if (chars[i] == '.') {
				if (i < length - 1 && chars[i + 1] == '.') {
					int k = i - 2;
					while (chars[k] != '\\') {
						k--;
					}
					int temp = k;
					for (int j = i + 2; j < length; j++) {
						chars[k++] = chars[j];
					}
					length = k;
					i = temp;
				} else {
					int k = i - 1;
					for (int j = i + 1; j < length; j++) {
						chars[k++] = chars[j];
					}
					length = k;
					i --;
				}
			}
			i++;
		}
		for (i = 0; i < length; i++) {
			System.out.print(chars[i]);
		}
	}

- Arjun Rao May 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

here's a nice functional one in Python

path = '$/home/abc/.././def/./ghi/../.'

def joiner(acc, next):
    if next == '.' or next == '':
        return acc
    if next == '..':
        return acc[:-1]
    return acc + [next]

nice = reduce(joiner, path.split('/'), [])
res = '/'.join(nice)
print res

- bgr May 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Test {

public static void main (String [] args) {

String absolutePath = getAbsolutePath("$/home/abc/.././def/./ghi/../.");

System.out.println(absolutePath);

}


public static String getAbsolutePath(String path) {

if (path == null)
return null;

int length = path.length();

char[] pathArray = path.toCharArray();

int dotCount = 0;

StringBuilder absPath = new StringBuilder();

for (int i = length - 1; i >= 0; i--) {

if (pathArray[i] == '.') {
dotCount++;
}

if (dotCount == 0) {
absPath.insert(0, pathArray[i]);
}

if (pathArray[i] == '/') {
if (dotCount > 1) {
dotCount--;
} else {
dotCount = 0;
}

}

}

return absPath.toString();

}

}

- whatsthegoss June 06, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// c++ code ,, use stringtokenizer in java

stringstream strin(dir_path);
     string dir;
     stack<string> s;
     while ( getline(strin, dir, '/') ) 
     {
            if (dir == "." ) {} 
            else if (dir == "..") if (!s.empty()) s.pop(); 
            else s.push(dir);                 
     }
     string ans;
     while (!s.empty()) {
                ans = "/" + s.top() + ans;
                s.pop(); 
     }
     return ans.size() ? ans : "/";

- Anonymous August 02, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote
You can do it using simple regex expression. As I see, there is no need of stacks. {{{ public class SimplifyUnixPath { static String inppath; public static void main(String[] args) { String inputstring = "/home/abc/.././def/./ghi/../."; String toprint = simplifyPath(inputstring); System.out.println(toprint); } public static String simplifyPath(String inp){ inppath = inp; String splitexp = "/\\w*/\\.\\.|/\\."; String output = ""; String[] outputarr; outputarr = inppath.split(splitexp); for(String s : outputarr){ output = output+s; } return output; } } /// - Anonymous August 09, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

You can do it using simple regex expression. As I see, there is no need of stacks. Sorry for my above post.

public class SimplifyUnixPath {
	static String inppath;
	public static void main(String[] args) {
		String inputstring = "/home/abc/.././def/./ghi/../.";
		//System.out.println(inputstring);
		String toprint = simplifyPath(inputstring);
		System.out.println(toprint);
		// TODO Auto-generated method stub

	}
	public static String simplifyPath(String inp){
		inppath = inp;
		String splitexp = "/\\w*/\\.\\.|/\\.";
		String output = "";
		String[] outputarr;
		outputarr = inppath.split(splitexp);
		for(String s : outputarr){
			//System.out.println(s);
			output = output+s;
		}
		return output;
		
	}

}

- sk August 09, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This is a version that doesn't use stacks and no extra memory. Probably a little inefficient.

var nextSegment = function(path, i) {
  var end = i;
  while(end < path.length) {
    if(path[end] === '/') break;
    end++;
  }

  return end;
}

var toAbsPath = function(path) {
  var i = 0;

  while(i < path.length) {
    if(path[i] === '.') {
      var segment = path.slice(i,i+3);
      if(segment.match(/\.\.(\/)?/)) {
        var end = nextSegment(path, i),
            upDir = false;
        i -= 2;
        while(i > 0 && !upDir) {
          if(path[i] === '/') {
            path = path.slice(0,i) + path.slice(end);
            upDir = true;
          }
          i--;
        }
      } else if(segment.match(/\.(\/[a-zA-Z0-9\.])?/)) {
        var end = nextSegment(path, i);

        path = path.slice(0,i) + path.slice(end + 1);
      }
    }

    i++;
  }

  return path;
};

console.log(toAbsPath("$/home/abc/.././def/./ghi/../."));

- Richard Tom April 01, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package tree;

public class UnixPath {

	public static void main(String[] args) {
		String input = "$/home/abc/.././def/./ghi/../.";
		String arr[] = input.split("/");
		String out[] = new String[arr.length];
		int i=-1;
		for(String s: arr){
			if(s.equals(".."))
				i--;
			else if(!s.equals("."))
				out[++i] = s;
		}
		for(int j=0; j<=i; j++)
			System.out.print(out[j]+"/");
	}

}

- Anonymous November 25, 2016 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More