klind klind - 1 year ago 587
Java Question

Codility : Brackets Determine whether a given string of parentheses is properly nested

Problem description from codility :

A string S consisting of N characters is considered to be properly nested if any of the following conditions is true:

S is empty;
S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string;
S has the form "VW" where V and W are properly nested strings.
For example, the string "{[()()]}" is properly nested but "([)()]" is not.

Write a function:

class Solution { public int solution(String S); }

that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.

For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above.

Assume that:

N is an integer within the range [0..200,000];
string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")".

expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N) (not counting the storage required for input arguments).

I get 87% I cant seem to figure out the problem.

enter image description here

Here is my code :

// you can also use imports, for example:
// import java.util.*;
import java.util.Stack;
// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
public int solution(String s) {

if (s.length() % 2 != 0) {
return 0;

Character openingBrace = new Character('{');
Character openingBracket = new Character('[');
Character openingParen = new Character('(');
Stack<Character> openingStack = new Stack<Character>();

for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == openingBrace || c == openingBracket || c == openingParen) {
} else {
if (i == s.length()-1 && openingStack.size() != 1) {
return 0;
if (openingStack.isEmpty()) {
return 0;
Character openingCharacter = openingStack.pop();
switch (c) {
case '}':
if (!openingCharacter.equals(openingBrace)) {
return 0;
case ']':
if (!openingCharacter.equals(openingBracket)) {
return 0;
case ')':
if (!openingCharacter.equals(openingParen)) {
return 0;


return 1;


Answer Source

Your first condition in the closing brackets block checks whether your stack has the size != 1. I assume this is meant to check that you don't have any leftover opening brackets, which is a good idea. However, you'll miss this entire check if your last char isn't a closing bracket/paren/..

This for example would fail for an input like (((.

A simple fix would be replacing this condition with a check after the loop ends that the stack is indeed empty.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download