Programming Search⌘K

Taskintro

Use a stack

Also called push and pop, stack push pop peek, lifo stack, check balanced brackets, matching parentheses.

Check that the brackets of a text match and nest, with push, pop and peek on the standard stack type of each tier 1 language.

Task

Use a stack to check the brackets of a text. The function balanced(text) returns true if each opening bracket (, [ or { has a closing bracket of the same kind after it, and the pairs nest without crossing. The other characters do not count. For example, balanced("f(a[0], {b: 1})") is true, and balanced("([)]") is false.

The solution reads the text from left to right. It pushes each opening bracket. At a closing bracket, it pops the top and compares the two brackets. At the end, the stack must be empty. The most recent open bracket must close first, and that is the order of a stack. For the idea, see Stack.

Solutions

Language Stack Push, pop and top
Python list append(x), pop(), stack[-1]
JavaScript Array push(x), pop(), stack[stack.length - 1]
TypeScript string[] push(x), pop() with the type string | undefined
Java ArrayDeque<Character> as a Deque push(x), pop() or poll(), peek()
C a char array and a count stack[count++] = x, count--, stack[count - 1]
C++ std::stack<char> push(x), pop(), top()
C# Stack<char> Push(x), Pop() or TryPop(out x), Peek()
Go a slice []rune append(s, x), s = s[:n-1], s[n-1]
Rust Vec<char> push(x), pop() that gives an Option, last()
Bash an indexed array stack+=("$x"), unset 'stack[-1]', ${stack[-1]}
  • A list or an array is often the stack. The Python tutorial says: "The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved"1. A JavaScript array works in the same way. push() "adds the specified elements to the end of an array and returns the new length of the array."2 The Rust documentation shows the same use: "Use a Vec as an efficient stack"3. Go has no stack type. The solution uses a slice. The function append "appends zero or more values x to a slice s of type S and returns the resulting slice"4, and a shorter slice removes the top.
  • Java uses ArrayDeque, not Stack. The documentation of the old Stack class says: "A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class."5 ArrayDeque "is likely to be faster than Stack when used as a stack"6. The solution uses poll(), because it "returns null if this deque is empty"6. pop() throws an exception in that case.
  • C++ and C# have a stack type. std::stack is "a container adaptor that gives the programmer the functionality of a stack - specifically, a LIFO (last-in, first-out) data structure."7 In .NET, Stack<T> "Represents a variable size last-in-first-out (LIFO) collection of instances of the same specified type."8 The C# solution uses TryPop, which "Returns a value that indicates whether there is an object at the top of the Stack"8.
  • C makes a stack from an array. The text has n characters, so the stack never holds more than n brackets. The solution gets n + 1 bytes with malloc, keeps a count, and frees the array before it returns.
  • Bash uses an indexed array. The index -1 is the last element: "an index of -1 references the last element."9 unset 'stack[-1]' removes it.
  • Rust and TypeScript show the empty case in the type. Rust pop "Removes the last element from a vector and returns it, or None if it is empty."3 The Rust solution compares stack.pop() with Some(want), so an empty stack gives false with no extra test.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty and no-brackets: a text with no brackets is balanced.
  • unclosed: (( leaves two brackets on the stack. A solution that does not test the stack at the end returns true.
  • extra-close: ()) pops from an empty stack at the third character.
  • close-first: )( has one bracket of each kind, but the closing bracket comes first. A count of open brackets that goes below 0 finds this too, but a count does not find wrong-kind.
  • wrong-kind: (] pops ( for ].
  • deep: 1000 opening brackets and then 1000 closing brackets. The stack holds 1000 items. The solutions use no recursion, so the depth of the call stack does not change.

Pitfalls

  • Python pop() on an empty list raises an exception. "It raises an IndexError if the list is empty or the index is outside the list range."1 stack[-1] on an empty list also raises IndexError. Test the stack before you pop or read the top:
stack = []
try:
    stack.pop()
except IndexError:
    print("pop: IndexError")
try:
    stack[-1]
except IndexError:
    print("top: IndexError")
print("top:", stack[-1] if stack else None)
Output
pop: IndexError
top: IndexError
top: None
  • Do not forget the test at the end. A function that only checks each closing bracket accepts a text with open brackets that are left. Return not stack (or len(stack) == 0) in place of True:

This code runs but gives a wrong answer on purpose.

def balanced(text):
    stack = []
    for c in text:
        if c == "(":
            stack.append(c)
        elif c == ")":
            if not stack:
                return False
            stack.pop()
    return True

print(balanced("(("))
Output
True
  • JavaScript push returns the length, not the array. The return value is "The new length property of the object upon which the method was called."2 If you assign it back to the stack, the stack becomes a number. And pop() on an empty array does not throw: "If you call pop() on an empty array, it returns undefined"10.
let stack = [];
stack = stack.push("a");
console.log(stack);
try {
  stack.push("b");
} catch (e) {
  console.log(e.constructor.name);
}
console.log([].pop());
Output
1
TypeError
undefined
  • Java ArrayDeque refuses null, and pop() throws on an empty stack. "Null elements are prohibited."6 pop() throws "NoSuchElementException - if this deque is empty"6, and poll() returns null:
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.NoSuchElementException;

public class Main {
  public static void main(String[] args) {
    Deque<String> stack = new ArrayDeque<>();
    try {
      stack.push(null);
    } catch (NullPointerException e) {
      System.out.println("push(null): NullPointerException");
    }
    try {
      stack.pop();
    } catch (NoSuchElementException e) {
      System.out.println("pop(): NoSuchElementException");
    }
    System.out.println("poll(): " + stack.poll());
  }
}
Output
push(null): NullPointerException
pop(): NoSuchElementException
poll(): null
  • C++ pop() returns nothing, and an empty stack is not checked. std::stack::pop "Removes the top element from the stack. Effectively calls c.pop_back()"11. It returns void, so read top() first. The default container is std::deque, and for its pop_back on an empty container, "the behavior is undefined"12 (until C++26). Test empty() before top() and pop().
  • C# Pop throws on an empty stack. The Pop page gives InvalidOperationException for the case "The Stack is empty."13 Use TryPop when the stack can be empty:
using System;
using System.Collections.Generic;

var stack = new Stack<char>();
try
{
    stack.Pop();
}
catch (InvalidOperationException)
{
    Console.WriteLine("Pop: InvalidOperationException");
}
Console.WriteLine(stack.TryPop(out char top) ? "top: " + top : "TryPop: empty");
Output
Pop: InvalidOperationException
TryPop: empty
  • Go s[len(s)-1] on an empty slice panics. For a slice, "if x is out of range at run time, a run-time panic occurs"4. Test len(s) first:
package main

import "fmt"

func top(stack []rune) (r rune, ok bool) {
	defer func() {
		if recover() != nil {
			ok = false
		}
	}()
	return stack[len(stack)-1], true
}

func main() {
	_, ok := top(nil)
	if !ok {
		fmt.Println("top of an empty slice: panic")
	}
	r, _ := top([]rune{'(', '['})
	fmt.Println("top:", string(r))
}
Output
top of an empty slice: panic
top: [
  • Bash unset stack[-1] without quotes can match a file. An argument such as a[4] goes through filename expansion, and the manual says: "Quote the argument if pathname expansion is not desired"9. In a directory with a file named stack1, the word stack[-1] becomes stack1, and unset removes a variable with that name. The stack does not change:
dir=$(mktemp -d)
cd "$dir" || exit 1
touch stack1
stack=(a b c)
unset stack[-1]
echo "${stack[@]}"
unset 'stack[-1]'
echo "${stack[@]}"
cd / && rm -r -- "${dir:?}"
Output
a b c
a b
  • Use a queue: the first item in is the first item out.
  • Use a priority queue: the item with the best priority is the next item out.
  • Stack: the idea behind this task and the operations.
  • Deque: one type that is a stack and a queue.

Code

The build runs the native tests of each language in a pinned toolchain.

balanced.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-stack/.

PAIRS = {")": "(", "]": "[", "}": "{"}


def balanced(text: str) -> bool:
    """Returns True if the brackets of text match and nest correctly."""
    stack: list[str] = []  # a list is the stack: append pushes, pop pops
    for c in text:
        if c in "([{":
            stack.append(c)
        elif c in PAIRS:
            if not stack or stack[-1] != PAIRS[c]:  # stack[-1] is the top
                return False
            stack.pop()
    return not stack  # an opening bracket that is left has no partner
test_balanced.py 28 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-stack/.

import pytest

from balanced import balanced

DEEP = "(" * 1000 + ")" * 1000

CASES = {
    "pair": ("()", True),
    "nested": ("{[()()]}", True),
    "code": ("f(a[0], {b: 1})", True),
    "crossed": ("([)]", False),
    "empty": ("", True),
    "no-brackets": ("abc", True),
    "unclosed": ("((", False),
    "extra-close": ("())", False),
    "close-first": (")(", False),
    "wrong-kind": ("(]", False),
    "deep": (DEEP, True),
}


@pytest.mark.parametrize("case", CASES)
def test_balanced(case):
    text, want = CASES[case]
    assert balanced(text) is want
balanced.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

#include "balanced.hpp"

#include <stack>

bool balanced(std::string_view text) {
    std::stack<char> stack;
    for (char c : text) {
        if (c == '(' || c == '[' || c == '{') {
            stack.push(c);
        } else if (c == ')' || c == ']' || c == '}') {
            char want = c == ')' ? '(' : c == ']' ? '[' : '{';
            // top() and pop() on an empty stack are undefined behavior, so
            // test empty() first.
            if (stack.empty() || stack.top() != want) {
                return false;
            }
            stack.pop(); // pop() returns nothing; read top() before it
        }
    }
    return stack.empty();
}
balanced.hpp 9 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

#pragma once

#include <string_view>

// balanced returns true if the brackets of text match and nest correctly.
bool balanced(std::string_view text);
test_balanced.cpp 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

#include "balanced.hpp"

#include <iostream>
#include <string>
#include <string_view>

static int failures = 0;

static void check(std::string_view label, std::string_view text, bool want) {
    if (balanced(text) != want) {
        std::cerr << "case " << label << " failed\n";
        failures++;
    }
}

int main() {
    const std::string deep = std::string(1000, '(') + std::string(1000, ')');
    check("pair", "()", true);
    check("nested", "{[()()]}", true);
    check("code", "f(a[0], {b: 1})", true);
    check("crossed", "([)]", false);
    check("empty", "", true);
    check("no-brackets", "abc", true);
    check("unclosed", "((", false);
    check("extra-close", "())", false);
    check("close-first", ")(", false);
    check("wrong-kind", "(]", false);
    check("deep", deep, true);
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
Brackets.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

import java.util.ArrayDeque;
import java.util.Deque;

final class Brackets {
  private Brackets() {}

  /** Returns true if the brackets of text match and nest correctly. */
  static boolean balanced(String text) {
    // ArrayDeque is the stack. The class Stack is older; its documentation
    // tells you to use a Deque.
    Deque<Character> stack = new ArrayDeque<>();
    for (int i = 0; i < text.length(); i++) {
      char c = text.charAt(i);
      switch (c) {
        case '(', '[', '{' -> stack.push(c);
        case ')', ']', '}' -> {
          Character top = stack.poll(); // null if the stack is empty
          if (top == null || top != open(c)) {
            return false;
          }
        }
        default -> {}
      }
    }
    return stack.isEmpty();
  }

  private static char open(char close) {
    return switch (close) {
      case ')' -> '(';
      case ']' -> '[';
      default -> '{';
    };
  }
}
BracketsTest.java 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class BracketsTest {
  static Stream<Arguments> cases() {
    String deep = "(".repeat(1000) + ")".repeat(1000);
    return Stream.of(
        Arguments.of("pair", "()", true),
        Arguments.of("nested", "{[()()]}", true),
        Arguments.of("code", "f(a[0], {b: 1})", true),
        Arguments.of("crossed", "([)]", false),
        Arguments.of("empty", "", true),
        Arguments.of("no-brackets", "abc", true),
        Arguments.of("unclosed", "((", false),
        Arguments.of("extra-close", "())", false),
        Arguments.of("close-first", ")(", false),
        Arguments.of("wrong-kind", "(]", false),
        Arguments.of("deep", deep, true));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void balanced(String name, String text, boolean want) {
    assertEquals(want, Brackets.balanced(text));
  }
}
balanced.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

#include "balanced.h"

#include <stdlib.h>
#include <string.h>

static char opening(char close) {
    switch (close) {
    case ')':
        return '(';
    case ']':
        return '[';
    default:
        return '{';
    }
}

bool balanced(const char *text) {
    // C has no stack type. An array and a count make one: the count is the
    // index of the next free slot, and the top is at count - 1. The stack
    // never holds more characters than the text has.
    size_t n = strlen(text);
    char *stack = malloc(n + 1);
    if (stack == NULL) {
        return false;
    }
    size_t count = 0;
    bool ok = true;
    for (size_t i = 0; i < n && ok; i++) {
        char c = text[i];
        if (c == '(' || c == '[' || c == '{') {
            stack[count++] = c; // push
        } else if (c == ')' || c == ']' || c == '}') {
            if (count == 0 || stack[count - 1] != opening(c)) {
                ok = false; // check the count before you read the top
            } else {
                count--; // pop
            }
        }
    }
    free(stack);
    return ok && count == 0;
}
balanced.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

#ifndef BALANCED_H
#define BALANCED_H

#include <stdbool.h>

// balanced returns true if the brackets of the string text match and nest
// correctly. It returns false also if it cannot get memory for the stack.
bool balanced(const char *text);

#endif
test_balanced.c 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

#include "balanced.h"

#include <stdio.h>
#include <string.h>

static int failures = 0;

static void check(const char *label, const char *text, bool want) {
    if (balanced(text) != want) {
        fprintf(stderr, "case %s failed\n", label);
        failures++;
    }
}

int main(void) {
    static char deep[2001];
    memset(deep, '(', 1000);
    memset(deep + 1000, ')', 1000);
    deep[2000] = '\0';
    check("pair", "()", true);
    check("nested", "{[()()]}", true);
    check("code", "f(a[0], {b: 1})", true);
    check("crossed", "([)]", false);
    check("empty", "", true);
    check("no-brackets", "abc", true);
    check("unclosed", "((", false);
    check("extra-close", "())", false);
    check("close-first", ")(", false);
    check("wrong-kind", "(]", false);
    check("deep", deep, true);
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
Brackets.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

using System.Collections.Generic;

public static class Brackets
{
    // Returns true if the brackets of text match and nest correctly.
    public static bool Balanced(string text)
    {
        var stack = new Stack<char>();
        foreach (char c in text)
        {
            switch (c)
            {
                case '(' or '[' or '{':
                    stack.Push(c);
                    break;
                case ')' or ']' or '}':
                    // TryPop returns false on an empty stack; Pop would throw.
                    if (!stack.TryPop(out char top) || top != Opening(c))
                    {
                        return false;
                    }
                    break;
            }
        }
        return stack.Count == 0;
    }

    private static char Opening(char close) => close switch
    {
        ')' => '(',
        ']' => '[',
        _ => '{',
    };
}
BracketsTests.cs 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

using Xunit;

public sealed class BracketsTests
{
    public static TheoryData<string, string, bool> Cases => new()
    {
        { "pair", "()", true },
        { "nested", "{[()()]}", true },
        { "code", "f(a[0], {b: 1})", true },
        { "crossed", "([)]", false },
        { "empty", "", true },
        { "no-brackets", "abc", true },
        { "unclosed", "((", false },
        { "extra-close", "())", false },
        { "close-first", ")(", false },
        { "wrong-kind", "(]", false },
        { "deep", new string('(', 1000) + new string(')', 1000), true },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, string text, bool want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Brackets.Balanced(text));
    }
}
balanced.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

const PAIRS = { ")": "(", "]": "[", "}": "{" };

// balanced returns true if the brackets of text match and nest correctly.
// An array is the stack: push adds to the end, and pop removes from the end.
export function balanced(text) {
  const stack = [];
  for (const c of text) {
    if (c === "(" || c === "[" || c === "{") {
      stack.push(c);
    } else if (c in PAIRS) {
      // pop returns undefined on an empty array, and undefined matches no
      // bracket, so an extra closing bracket gives false.
      if (stack.pop() !== PAIRS[c]) return false;
    }
  }
  return stack.length === 0;
}
balanced.test.js 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { balanced } from "./balanced.js";

const deep = "(".repeat(1000) + ")".repeat(1000);

const cases = [
  ["pair", "()", true],
  ["nested", "{[()()]}", true],
  ["code", "f(a[0], {b: 1})", true],
  ["crossed", "([)]", false],
  ["empty", "", true],
  ["no-brackets", "abc", true],
  ["unclosed", "((", false],
  ["extra-close", "())", false],
  ["close-first", ")(", false],
  ["wrong-kind", "(]", false],
  ["deep", deep, true],
];

for (const [name, text, want] of cases) {
  test(name, () => {
    assert.equal(balanced(text), want);
  });
}
balanced.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

const PAIRS: Readonly<Record<string, string>> = { ")": "(", "]": "[", "}": "{" };

// balanced returns true if the brackets of text match and nest correctly.
export function balanced(text: string): boolean {
  const stack: string[] = [];
  for (const c of text) {
    if (c === "(" || c === "[" || c === "{") {
      stack.push(c);
    } else if (c in PAIRS) {
      // The type of pop() is string | undefined: the stack can be empty.
      const top: string | undefined = stack.pop();
      if (top !== PAIRS[c]) return false;
    }
  }
  return stack.length === 0;
}
balanced.test.ts 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { balanced } from "./balanced.ts";

const deep = "(".repeat(1000) + ")".repeat(1000);

const cases: [string, string, boolean][] = [
  ["pair", "()", true],
  ["nested", "{[()()]}", true],
  ["code", "f(a[0], {b: 1})", true],
  ["crossed", "([)]", false],
  ["empty", "", true],
  ["no-brackets", "abc", true],
  ["unclosed", "((", false],
  ["extra-close", "())", false],
  ["close-first", ")(", false],
  ["wrong-kind", "(]", false],
  ["deep", deep, true],
];

for (const [name, text, want] of cases) {
  test(name, () => {
    assert.equal(balanced(text), want);
  });
}
balanced.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

// Package brackets checks brackets with a stack.
package brackets

var opening = map[rune]rune{')': '(', ']': '[', '}': '{'}

// Balanced returns true if the brackets of text match and nest correctly.
// Go has no stack type. A slice is the stack: append pushes, and a shorter
// slice pops.
func Balanced(text string) bool {
	var stack []rune
	for _, c := range text {
		switch c {
		case '(', '[', '{':
			stack = append(stack, c)
		case ')', ']', '}':
			n := len(stack)
			if n == 0 || stack[n-1] != opening[c] { // stack[n-1] is the top
				return false
			}
			stack = stack[:n-1]
		}
	}
	return len(stack) == 0
}
balanced_test.go 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

package brackets

import (
	"strings"
	"testing"
)

var cases = []struct {
	name string
	text string
	want bool
}{
	{"pair", "()", true},
	{"nested", "{[()()]}", true},
	{"code", "f(a[0], {b: 1})", true},
	{"crossed", "([)]", false},
	{"empty", "", true},
	{"no-brackets", "abc", true},
	{"unclosed", "((", false},
	{"extra-close", "())", false},
	{"close-first", ")(", false},
	{"wrong-kind", "(]", false},
	{"deep", strings.Repeat("(", 1000) + strings.Repeat(")", 1000), true},
}

func TestBalanced(t *testing.T) {
	for _, c := range cases {
		if got := Balanced(c.text); got != c.want {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}
balanced.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

/// Returns true if the brackets of text match and nest correctly.
/// A Vec is the stack: push adds to the end, and pop removes from the end.
pub fn balanced(text: &str) -> bool {
    let mut stack: Vec<char> = Vec::new();
    for c in text.chars() {
        let want = match c {
            '(' | '[' | '{' => {
                stack.push(c);
                continue;
            }
            ')' => '(',
            ']' => '[',
            '}' => '{',
            _ => continue,
        };
        // pop returns None on an empty Vec, so an extra closing bracket
        // does not match.
        if stack.pop() != Some(want) {
            return false;
        }
    }
    stack.is_empty()
}
tests/balanced_test.rs 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-stack/.

use algo_use_a_stack::balanced;

#[test]
fn cases() {
    let deep = "(".repeat(1000) + &")".repeat(1000);
    let cases: Vec<(&str, &str, bool)> = vec![
        ("pair", "()", true),
        ("nested", "{[()()]}", true),
        ("code", "f(a[0], {b: 1})", true),
        ("crossed", "([)]", false),
        ("empty", "", true),
        ("no-brackets", "abc", true),
        ("unclosed", "((", false),
        ("extra-close", "())", false),
        ("close-first", ")(", false),
        ("wrong-kind", "(]", false),
        ("deep", &deep, true),
    ];
    for (name, text, want) in cases {
        assert_eq!(balanced(text), want, "case {name}");
    }
}
balanced.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-stack/.

# balanced TEXT: exits with status 0 if the brackets of TEXT match and nest
# correctly, and with status 1 if they do not. An indexed array is the stack.
balanced() {
  local text=$1 c want i
  local -a stack=()
  for ((i = 0; i < ${#text}; i++)); do
    c=${text:i:1}
    case $c in
      '(' | '[' | '{') stack+=("$c") ;;
      ')' | ']' | '}')
        case $c in
          ')') want='(' ;;
          ']') want='[' ;;
          *) want='{' ;;
        esac
        ((${#stack[@]} > 0)) || return 1
        [[ ${stack[-1]} == "$want" ]] || return 1
        unset 'stack[-1]' # the quotes stop pathname expansion
        ;;
    esac
  done
  ((${#stack[@]} == 0))
}
test_balanced.bats 66 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-stack/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/balanced.sh"
}

check() { # check STATUS TEXT
  run balanced "$2"
  [ "$status" -eq "$1" ]
  [ "$output" = "" ]
}

deep() {
  local open close
  printf -v open '%1000s' ''
  printf -v close '%1000s' ''
  printf '%s%s' "${open// /(}" "${close// /)}"
}

@test "pair" {
  check 0 '()'
}

@test "nested" {
  check 0 '{[()()]}'
}

@test "code" {
  check 0 'f(a[0], {b: 1})'
}

@test "crossed" {
  check 1 '([)]'
}

@test "empty" {
  check 0 ''
}

@test "no-brackets" {
  check 0 'abc'
}

@test "unclosed" {
  check 1 '(('
}

@test "extra-close" {
  check 1 '())'
}

@test "close-first" {
  check 1 ')('
}

@test "wrong-kind" {
  check 1 '(]'
}

@test "deep" {
  check 0 "$(deep)"
}

References

  1. The Python Tutorial, 5. Data Structures, 5.1 More on Lists; 5.1.1 Using Lists as Stacks
  2. Array.prototype.push(), MDN Web Docs, the introduction; Return value
  3. Struct Vec, The Rust Standard Library, the description; pop
  4. The Go Programming Language Specification, Index expressions; Appending to and copying slices
  5. Stack (Java SE 27 and JDK 27), the class description
  6. ArrayDeque (Java SE 27 and JDK 27), the class description; poll; pop
  7. std::stack, cppreference.com, the introduction
  8. Stack<T> Class, .NET API reference, the summary; Methods
  9. Bash Reference Manual, 6.7 Arrays
  10. Array.prototype.pop(), MDN Web Docs, Return value; Description
  11. std::stack::pop, cppreference.com, the description
  12. std::deque::pop_back, cppreference.com, the description
  13. Stack<T>.Pop Method, .NET API reference, Exceptions

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source