> For the complete documentation index, see [llms.txt](https://trizen.gitbook.io/sidef-lang/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://trizen.gitbook.io/sidef-lang/programming_tasks/b/balanced_brackets.md).

# Balanced brackets

```ruby
func balanced (str) {
 
    var depth = 0
    str.each { |c|
           if(c=='['){ ++depth }
        elsif(c==']'){ --depth < 0 && return false }
    }
 
    return !depth
}

for str [']','[','[[]','][]','[[]]','[[]]]][][]]','x[ y [ [] z ]][ 1 ][]abcd'] {
    printf("%sbalanced\t: %s\n", balanced(str) ? "" : "NOT ", str)
}
```

#### Output:

```
NOT balanced    : ]
NOT balanced    : [
NOT balanced    : [[]
NOT balanced    : ][]
balanced        : [[]]
NOT balanced    : [[]]]][][]]
balanced        : x[ y [ [] z ]][ 1 ][]abcd
```
