Cou

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Week one Assignment

Ans 1:

To solve this problem, we can use a stack data structure to keep track of the opening brackets that we
encounter while traversing the input string. Whenever we encounter a closing bracket, we check if it
matches the top of the stack. If it does, we pop the opening bracket from the stack, and continue. If it
doesn't match or the stack is empty, we have an error.We also need to keep track of the position of the
first unmatched opening and closing brackets. We can do this by storing the index of each bracket in a
separate stack. Whenever we push an opening bracket onto the stack, we also push its index onto the
index stack. Whenever we pop an opening bracket from the stack, we also pop its index from the index
stack. Whenever we encounter a closing bracket that doesn't match the top of the stack, we can output the
index of the closing bracket. If the stack is not empty after we traverse the input string, we can output the
index of the top opening bracket on the stack.Here's the pseudocode for this algorithm:stack = empty
stack index_stack = empty stack for i = 1 to length of input string do if input[i] is an opening bracket then
push input[i] onto stack push i onto index_stack else if input[i] is a closing bracket then if stack is empty
or input[i] doesn't match top of stack then output i return else pop top element from stack pop
corresponding index from index_stack if stack is not empty then output top element of index_stack else
output "Success"

def find_mismatch(text):

stack = []

index_stack = []

for i in range(len(text)):

if text[i] in "([{":

stack.append(text[i])

index_stack.append(i+1)

elif text[i] in ")]}":

if not stack or (text[i] == ")" and stack[-1] != "(") or \

(text[i] == "]" and stack[-1] != "[") or \

(text[i] == "}" and stack[-1] != "{"):

return i+1

else:

stack.pop()

index_stack.pop()
if stack:

return index_stack[-1]

else:

return "Success"

The time complexity of this algorithm is O(n), where n is the length of the input string, since we
only traverse the string once and each operation on the stack takes constant time. The space
complexity is also O(n), since in the worst case we need to store all the opening brackets in the
stack.

You might also like