Solution to Brackets by codility

22 Jan

Question: http://codility.com/demo/take-sample-test/brackets

Question Name: Brackets

Classic application of stacks.

UPDATE (2016-07-19): Much appreciate Jeffrey’s comment and suggestion:

I’m surprised so few people didn’t do a simple modulo at the start to check whether there is an even number of chars. In production, you wouldn’t want this algorithm to run against a big string and only terminate at the end when one closing token is missing. You’d want it to terminate as soon as it’s possible

20 Replies to “Solution to Brackets by codility

  1. Ruby Version

  2. C# Solution.

  3. I don’t know if you’ve tested this in a IDE, but this is the correct C# solution 100%:

      • Above code had compilation errors even algorithm is correct but does not compile correctly. I will suggest the code below:

        See the results for this over the codility:
        https://codility.com/demo/results/demo4KD3BK-X89/

  4. I was talking about Kaiser’s solution. Apparently “<pre>” tag somehow formatted my Dictionary<string,string> VS 2013 won’t recognize Dictionary as a Generic Collection

  5. This works same as a stack and it is a bit shorter (still O(n)):

    • Good idea. Actually you are doing a stack by your self.

      For the other readers with other programming languages, please notice that the top pointer might be negative value. For example, the test input might be “)))”.

  6. Here’s a Java 100/100 Solution:
    https://codility.com/demo/results/demo97TPVG-CPP/

  7. A C# solution:

  8. I’m surprised so few people didn’t do a simple modulo at the start to check whether there is an even number of chars. In production, you wouldn’t want this algorithm to run against a big string and only terminate at the end when one closing token is missing. You’d want it to terminate as soon as it’s possible

Leave a Reply

Your email address will not be published. Required fields are marked *