Skip to content

Add possible solution to the "Reverse Parenthesis" problem #68

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 17, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 36 additions & 4 deletions interview-process/engineers/questions/parenthesis.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,45 @@ Write a method that for a given input string, reverse all the characters inside
```

## Observations
- How to solve it? Using a stack and a queue.
- How to solve it? Two possible solutions for this problem are using recursion or using a stack.

## Possible Solutions
```python
def reverse_text_inside_parens(text):
pending_outputs = []
output_so_far = ''

for i in range(len(text)):
if text[i] == '(':
pending_outputs.append(output_so_far)
output_so_far = ''

elif text[i] == ')':
if len(pending_outputs) == 0:
raise ValueError('Malformed expression')

previous_output = pending_outputs.pop()
output_so_far = previous_output + output_so_far[::-1]
else:
output_so_far += text[i]

if len(pending_outputs) > 0:
raise ValueError('Malformed expression')

return output_so_far
```

## Test cases
```javascript
foobarbaz => foobarbaz
foo(bar)baz => foorabbaz
foo(bar(baz))blim => foo(barzab)blim => foobazrabblim
'' => ''
'()' => ''
'(())(((())))' => ''
'(bar)' => 'rab'
'((bar))' => 'bar'
'wi(ez)(((il)))(en)' => 'wizeline'
'foobarbaz' => 'foobarbaz'
'foo(bar)baz' => 'foorabbaz'
'foo(bar(baz))blim' => 'foo(barzab)blim' => 'foobazrabblim'
```

[Home](../../../README.md) |
Expand Down