Câu hỏi phỏng vấn Arrays
Câu hỏi

Check for balanced parentheses in...

Câu trả lời

To check for balanced parentheses in linear time using constant space, you can use a counter-based approach. This method avoids the use of a stack, which typically requires O(n) space, and instead uses a few integer variables to keep track of the balance of parentheses. Here is a step-by-step explanation and implementation in Python:

Explanation

  1. Initialize Counters: Use counters to keep track of the number of opening and closing parentheses.
  2. Traverse the String: Iterate through each character in the string.
  3. Update Counters:
    • Increment the counter when encountering an opening parenthesis.
    • Decrement the counter when encountering a closing parenthesis.
  4. Check Balance:
    • If at any point the counter becomes negative, it means there are more closing parentheses than opening ones, and the string is not balanced.
  5. Final Check:
    • After traversing the entire string, if the counter is not zero, it means there are unmatched opening parentheses, and the string is not balanced.

Python Implementation

def is_balanced_parentheses(s: str) -> bool:
    # Initialize counters for different types of parentheses
    round_count = 0
    square_count = 0
    curly_count = 0
    
    for char in s:
        if char == '(':
            round_count += 1
        elif char == ')':
            round_count -= 1
        elif char == '[':
            square_count += 1
        elif char == ']':
            square_count -= 1
        elif char == '{':
            curly_count += 1
        elif char == '}':
            curly_count -= 1
        
        # Check if any counter goes negative
        if round_count < 0 or square_count < 0 or curly_count < 0:
            return False
    
    # Final check to ensure all counters are zero
    return round_count == 0 and square_count == 0 and curly_count == 0

# Example usage
print(is_balanced_parentheses("({[]})"))  # Output: True
print(is_balanced_parentheses("({[})"))   # Output: False

Explanation of the Code

  • Counters: round_count, square_count, and curly_count are used to track the balance of (), [], and {} respectively.
  • Loop: The loop iterates through each character in the string s.
  • Increment/Decrement: Depending on the type of parenthesis, the corresponding counter is in...
senior

senior

Gợi ý câu hỏi phỏng vấn

middle

When to use a Linked List over an Array/Array List?

junior

What is a main difference between an Array and a Dictionary?

entry

Explain what is an Array Explain what is an Array?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào