Sobes.tech
Middle

It is necessary to validate the structure ONLY for the correctness of opening and closing brackets. test_data = [ "[][][]", # valid "[[[]]]", # valid "[]", # valid "][[", # invalid "[[]", # invalid "[]]", # invalid "[[]]", # invalid "][[]", # invalid "[][]]", # invalid "[]][", # invalid ] def is_valid():

sobes.tech AI

Answer from AI

To check the correctness of opening and closing brackets, a simple stack can be used. When iterating through the string:

  • If an opening bracket [ is encountered, push it onto the stack.
  • If a closing bracket ] is encountered, check if there is a corresponding opening bracket in the stack. If not — the string is incorrect.

At the end, the stack should be empty; otherwise, there are unclosed brackets.

Example implementation:

def is_valid(s: str) -> bool:
    stack = []
    for char in s:
        if char == '[':
            stack.append(char)
        elif char == ']':
            if not stack:
                return False
            stack.pop()
    return len(stack) == 0

# Test data check

test_data = [
    "[][][]",  # valid
    "[[[]]]",  # valid
    "[]",      # valid
    "][[",     # invalid
    "[[]",     # invalid
    "[]]",     # invalid
    "[[]]",    # valid
    "][[]",    # invalid
    "[][]]",   # invalid
    "[]][",    # invalid
]

for s in test_data:
    print(f"{s}: {is_valid(s)}")

Note that in the original list, "[[]]" is marked as invalid, but logically, brackets are correctly opened and closed there, so it is valid.