Uber phone interview question

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2020-04-02Added By Anonymous
Source: Link

Company: Uber

Interview Stage: Phone Screen


Original Post Content:


Let there be a simple language like this:

expr ::= int | '( ' op expr+ ')'

op ::= '+' | '*'


The task is to write a function `int evaluate(String expression)` that evaluates a given expression. You can assume that expression is valid for this given language.


Examples:


"3" = 3

"( + 1 2 )" = 3

"( + 3 4 5 )" = 12

"( + 7 ( * 8 12 ) ( * 2 ( + 9 4 ) 7 ) 3 )" = 288


I made some progress but wasn't able to finish it in time. I was trying to do it the same way as evaluating RPN and spent too much time exploring this incorrect idea.

The language explicitly puts spaces around each token and I think it's an important detail. It should probably be splitted by space and then parsed and evaluated recursively.

Comments