Phone Interview Question ...

21 Feb 2008

I read this amazing article on how to get a phone interview right ...
http://steve.yegge.googlepages.com/five-essential-phone-screen-questions

I think it is a must read for everyone - experienced and inexperienced students like myself. I feel I can answer atleast 80% of what is asked over there except the REGEX part of it, which I really have no clue. My RegEx is supported heavily by Google and I somehow feel lazy to learn RegEx. Anyway there was one such question, which I lift from the link i gave above.

Let's say you're on my team, and I've decided I'm a real stickler for code formatting. But I've got peculiar tastes, and one day I decide I want to have all parentheses stand out very clearly in your code.

So let's say you've got a set of source files in C, C++, or Java. Your choice. And I want you to modify them so that in each source file, every open- and close-paren has exactly one space character before and after it. If there is any other whitespace around the paren, it's collapsed into a single space character.

For instance, this code:

foo (bar ( new Point(x, graph.getY()) ));

Would be modified to look like this:

foo ( bar ( new Point ( x, graph.getY ( ) ) ) ) ;

I tell you (as your manager) that I don't care how you solve this problem. You can take the code down to Kinko's Copies and manually cut and paste the characters with scissors if you like.

How will you solve this problem?


My solution is very simple and I do not use RegEx, yet I could complete it in 3-4 minutes. Probably one with RegEx experience can do it in a minute. Also, the code shown below might be bugged and I did not test it yet. So in case you find a bug, let me know before I figure it out myself.

def sampleCode = " foo (bar ( new Point(x, graph.getY()) ));"
sampleCode = sampleCode.replace(" (","(");
sampleCode = sampleCode.replace("( ","(");
sampleCode = sampleCode.replace(" )",")");
sampleCode = sampleCode.replace(") ",")");
sampleCode = sampleCode.replace(")"," ) ");
sampleCode = sampleCode.replace("("," ( ");
sampleCode = sampleCode.replace(" "," ");
println("Expected : foo ( bar ( new Point ( x, graph.getY ( ) ) ) ) ;")
println "Obtained : "+sampleCode.trim()

So do I get a job at Amazon?? Or atleast a phone interview call!