rs-02-balanced
1.000
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
```rust
pub fn is_balanced(input: &str) -> bool {
let mut stack = Vec::new();
for c in input.chars() {
match c {
'(' | '[' | '{' => stack.push(c),
')' => if stack.pop() != Some('(') { return false; },
']' => if stack.pop() != Some('[') { return false; },
'}' => if stack.pop() != Some('{') { return false; },
_ => {}
}
}
stack.is_empty()
}
```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
Reasoning (chain-of-thought)
The user wants a Rust implementation of a function `is_balanced(input: &str) -> bool` that checks if brackets `()`, `[]`, and `{}` are balanced and correctly nested.
Non-bracket characters should be ignored.
Empty string returns `true`.
I need to implement this in `src/lib.rs`.
Algorithm:
Use a stack to keep track of opening brackets.
Iterate over each character in the input string.
If it's an opening bracket `(`, `[`, `{`, push it onto the stack.
If it's a closing bracket `)`, `]`, `}`, check if the stack is empty. If empty, return `false`.
Pop the top of the stack and check if it matches the closing bracket.
If it doesn't match, return `false`.
After iterating through all characters, return `true` if the stack is empty, else `false`.
Let's write it out.
```rust
pub fn is_balanced(input: &str) -> bool {
let mut stack = Vec::new();
for c in input.chars() {
match c {
'(' | '[' | '{' => stack.push(c),
')' => if stack.pop() != Some('(') { return false; },
']' => if stack.pop() != Some('[') { return false; },
'}' => if stack.pop() != Some('{') { return false; },
_ => {}
}
}
stack.is_empty()
}
```
Wait, `stack.pop()` returns `Option<char>`. If stack is empty, `pop()` returns `None`, which doesn't equal `Some('(')`, so it returns `false`. That's correct.
Let's double check logic.
`is_balanced("")` -> loop doesn't run, `stack.is_empty()` is true. Correct.
`is_balanced("()[]{}")` -> pushes `(`, pops `(` matches `)`, pushes `[`, pops `[` matches `]`, pushes `{`, pops `{` matches `}`. Stack empty. True. Correct.
`is_balanced("(]")` -> pushes `(`, sees `]`, pops `(` != `[`, returns false. Correct.
`is_balanced("([)]")` -> pushes `(`, pushes `[`, sees `)`, pops `[` != `(`, returns false. Correct.
`is_balanced("(")` -> pushes `(`, loop ends, stack not empty, returns false. Correct.
`is_balanced(")(")` -> sees `)`, stack empty, pop returns None != Some('('), returns false. Correct.
The code looks solid.
I will wrap it in `src/lib.rs` format.
The prompt says: "Implement the library file **`src/lib.rs`** exposing: `pub fn is_balanced(input: &str) -> bool`"
And "Tests live in `tests/` and call it as `challenge::is_balanced`." This implies the crate name is `challenge`, but I just need to provide `src/lib.rs`.
I'll output exactly the code for `src/lib.rs`.
One minor point: `Vec` is fine, but I could also use an array or just `Vec<char>`. `Vec<char>` is perfectly fine.
Let's consider performance or idiomatic Rust.
Using `Vec<char>` is standard.
Could also use a fixed-size array if we want, but `Vec` is simpler.
The code is concise and correct.
I will produce the solution.
No extra prose.
Just the code block.
```rust
pub fn is_balanced(input: &str) -> bool {
let mut stack = Vec::new();
for c in input.chars() {
match c {
'(' | '[' | '{' => stack.push(c),
')' => if stack.pop() != Some('(') { return false; },
']' => if stack.pop() != Some('[') { return false; },
'}' => if stack.pop() != Some('{') { return false; },
_ => {}
}
}
stack.is_empty()
}
```
Wait, should I include `#[cfg(test)]` or anything? The prompt says "Tests live in `tests/`", so I don't need to include tests.
Just the function.
One detail: `stack.pop() != Some('(')` works, but some might prefer `stack.pop() == Some('(')` inside an `if let` or match. But the current form is fine.
Actually, `stack.pop() != Some('(')` is correct.
Let's verify with an example: `input = "a(b)c"`
`a` -> ignored
`(` -> push `(`
`b` -> ignored
`)` -> pop `(`, matches, continues
`c` -> ignored
stack empty -> true. Correct.
All good.
I will output the code.
One thing: the prompt says "Implement the library file **`src/lib.rs`** exposing: ...". I'll just provide the content of `src/lib.rs`.
Final check of the code:
```rust
pub fn is_balanced(input: &str) -> bool {
let mut stack = Vec::new();
for c in input.chars() {
match c {
'(' | '[' | '{' => stack.push(c),
')' => if stack.pop() != Some('(') { return false; },
']' => if stack.pop() != Some('[') { return false; },
'}' => if stack.pop() != Some('{') { return false; },
_ => {}
}
}
stack.is_empty()
}
```
This is correct and idiomatic.
I will produce it now.
No extra text.
Done.
I'll format it inside a rust code block.
The prompt asks for `src/lib.rs`. I will just give the code.
Ready.
Output matches request.✅
Proceeds.
(Self-Correction/Refinement during thought)
Could there be any issue with `stack.pop() != Some('(')`?
If stack is empty, `pop()` returns `None`. `None != Some('(')` is true, so it returns `false`. Correct.
If stack has `(`, `pop()` returns `Some('(')`. `Some('(') != Some('(')` is false, so it continues. Correct.
If stack has `[`, `pop()` returns `Some('[')`. `Some('[') != Some('(')` is true, returns `false`. Correct.
So it's perfectly fine.
I'll output exactly that.
All good.
Proceeds.
[Output Generation] -> *fenced code block*
```rust
pub fn is_balanced(input: &str) -> bool {
let mut stack = Vec::new();
for c in input.chars() {
match c {
'(' | '[' | '{' => stack.push(c),
')' => if stack.pop() != Some('(') { return false; },
']' => if stack.pop() != Some('[') { return false; },
'}' => if stack.pop() != Some('{') { return false; },
_ => {}
}
}
stack.is_empty()
}
```
Matches requirements. Done.
I will produce the response now.
All steps verified. No extra fluff.
Output matches exactly.
Done.
[Final Check]
The prompt says: "Implement the library file **`src/lib.rs`** exposing: `pub fn is_balanced(input: &str) -> bool`"
I will provide exactly that.
Code is correct.
Ready.
[Output Generation] (Proceeds)