0

This was asked to me in an interview. I didn't know the proper recurrence for it at that time. The question was, if I am given the length of the expression, then how many proper bracket expressions can be made of that length and what will they be?

A proper bracket expression is for example,

[[]][[[]][]] 
[[[][]]][][[]]

The following is not a proper bracket expression,

[[[][]]][]][[]]

That is, there is a closing bracket for each opening bracket. I am not looking for the implementation, but just the algorithm or how should I approach it?

Thanks!

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
Elliot
  • 483
  • 2
  • 6
  • 17

2 Answers2

1

Here's an algorithm in Python:

def properbracket(l, s):
  if l == 0:
    if s == 0:
      return 1
    else:
      return 0
  ret = 0
  if s > 0:
    ret += properbracket(l-1, s-1)
  ret += properbracket(l-1, s+1)
  return ret

print properbracket(2, 0)
print properbracket(4, 0)
print properbracket(6, 0)

...and here are the valid expressions for different lengths: len == 2:

[]

len == 4:

[[]]
[][]

len == 6:

[[[]]]
[][][]
[][[]]
[[][]]
[[]][]

This assumes that "][" is not a valid expression.

juhist
  • 4,210
  • 16
  • 33
0

The following recurrence is based on the leading open bracket must have a matching closing bracket, such that there must be a valid expression inside these brackets and another after the closing one

  • P(0) = 1
  • P(1) = 0
  • P(2) = 1
  • P(N>2) = sum(i=0..N/2-1)( P(2i) * P(N-2-2i) )
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101