← run

rs-02-balanced

1.000
6/6 tests· algorithms
Challenge · difficulty 2/5
# Balanced brackets

Implement the library file **`src/lib.rs`** exposing:

```rust
pub fn is_balanced(input: &str) -> bool
```

Return `true` if and only if the brackets `()`, `[]`, and `{}` in `input` are
correctly balanced and nested. Every opening bracket must be closed by a matching
closing bracket in the right order. Any closing bracket must match the most
recently opened, still-unclosed bracket.

- Non-bracket characters are ignored.
- The empty string is balanced (returns `true`).

Examples:

- `is_balanced("")` → `true`
- `is_balanced("()[]{}")` → `true`
- `is_balanced("([{}])")` → `true`
- `is_balanced("(a + [b * c]) - {d}")` → `true`
- `is_balanced("(]")` → `false`
- `is_balanced("([)]")` → `false`
- `is_balanced("(")` → `false`
- `is_balanced(")(")` → `false`

Tests live in `tests/` and call it as `challenge::is_balanced`.
tests/balanced.rs
use challenge::is_balanced;

#[test]
fn empty_is_balanced() {
    assert!(is_balanced(""));
}

#[test]
fn simple_pairs() {
    assert!(is_balanced("()[]{}"));
    assert!(is_balanced("([{}])"));
}

#[test]
fn ignores_non_brackets() {
    assert!(is_balanced("(a + [b * c]) - {d}"));
    assert!(is_balanced("no brackets at all"));
}

#[test]
fn mismatched_type() {
    assert!(!is_balanced("(]"));
    assert!(!is_balanced("{)"));
}

#[test]
fn wrong_nesting_order() {
    assert!(!is_balanced("([)]"));
}

#[test]
fn unclosed_or_unopened() {
    assert!(!is_balanced("("));
    assert!(!is_balanced(")("));
    assert!(!is_balanced("(()"));
}
System prompt
You are an expert programmer. Solve the task exactly as specified. Output your solution as fenced code blocks using the required file name(s) and the exact function/type signatures requested. Prefer correctness; do not include prose outside code unless asked.
Proposed solution
I'll implement a solution for the balanced brackets problem using a stack approach.

```rust
// src/lib.rs

pub fn is_balanced(input: &str) -> bool {
    let mut stack = Vec::new();
    
    for ch in input.chars() {
        match ch {
            '(' | '[' | '{' => stack.push(ch),
            ')' => {
                if stack.pop() != Some('(') {
                    return false;
                }
            }
            ']' => {
                if stack.pop() != Some('[') {
                    return false;
                }
            }
            '}' => {
                if stack.pop() != Some('{') {
                    return false;
                }
            }
            _ => (), // Ignore non-bracket characters
        }
    }
    
    // All brackets should be closed (stack should be empty)
    stack.is_empty()
}
```

This implementation works by:

1. Using a stack to keep track of opening brackets
2. For each character in the input:
   - If it's an opening bracket `(`, `[`, or `{`, push it onto the stack
   - If it's a closing bracket `)`, `]`, or `}`:
     - Check if the top of the stack contains the matching opening bracket
     - If not, return false immediately
     - If yes, pop the matching opening bracket from the stack
   - For any other character, ignore it
3. After processing all characters, return true only if the stack is empty (all brackets were properly closed)

The time complexity is O(n) where n is the length of the input string, and the space complexity is O(m) where m is the maximum nesting depth of brackets.

Test output (stdout)


running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


running 6 tests
......
test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s