Given a string s consisting only of uppercase English letters (A-Z), digits (0-9), and the characters '[' and ']', and an index pos such that s[pos] == '[', find the index of the corresponding closing bracket ']'.
The string is guaranteed to have valid matching brackets.
Examples:
Input: s = "[ABC[23]][89]", pos = 0
Output: 8
Explanation: [ABC[23]][89] The closing bracket corresponding to the opening bracket at index 0 is at index 8.Input: s = "ABC[58]", pos = 3
Output: 6
Explanation: ABC[58] The closing bracket corresponding to the opening bracket at index 3 is at index 6.
Table of Content
[Naive Approach] Using Stack - O(n) Time and O(n) Space
The idea is to use a stack to keep track of opening brackets encountered while traversing from pos.
Every [ is pushed into the stack, and every ] removes one opening bracket.
When the stack becomes empty, the current closing bracket matches the opening bracket at pos.
- Create an empty stack.
- Traverse the string starting from pos.
- If the current character is [, push it into the stack.
- If the current character is ], pop the top element.
- If the stack becomes empty after the pop, return the current index.
- Return -1 if no matching bracket is found.
#include <bits/stdc++.h>
using namespace std;
int closing(string &s, int pos)
{
// Stack stores the indices of opening brackets.
stack<int> st;
// Traverse the string starting from the given position.
for (int i = pos; i < s.size(); i++)
{
// If an opening bracket is found,
// store its index in the stack.
if (s[i] == '[')
{
st.push(i);
}
// If a closing bracket is found,
// it matches the most recent opening bracket.
else if (s[i] == ']')
{
// Remove the corresponding opening bracket.
st.pop();
// If the stack becomes empty,
// the current closing bracket matches
// the opening bracket at pos.
if (st.empty())
return i;
}
}
// This case is not expected because
// the input is guaranteed to have valid brackets.
return -1;
}
int main()
{
string s = "[ABC[23]][89]";
int pos = 0;
cout << closing(s, pos) << endl;
return 0;
}
import java.util.*;
class GFG {
static int closing(String s, int pos)
{
// Stack stores the indices of opening brackets.
Stack<Integer> st = new Stack<>();
// Traverse the string starting from the given
// position.
for (int i = pos; i < s.length(); i++) {
// If an opening bracket is found,
// store its index in the stack.
if (s.charAt(i) == '[') {
st.push(i);
}
// If a closing bracket is found,
// it matches the most recent opening bracket.
else if (s.charAt(i) == ']') {
// Remove the corresponding opening bracket.
st.pop();
// If the stack becomes empty,
// the current closing bracket matches
// the opening bracket at pos.
if (st.empty())
return i;
}
}
// This case is not expected because
// the input is guaranteed to have valid brackets.
return -1;
}
public static void main(String[] args)
{
String s = "[ABC[23]][89]";
int pos = 0;
System.out.println(closing(s, pos));
}
}
def closing(s, pos):
# Stack stores the indices of opening brackets.
st = []
# Traverse the string starting from the given position.
for i in range(pos, len(s)):
# If an opening bracket is found,
# store its index in the stack.
if s[i] == '[':
st.append(i)
# If a closing bracket is found,
# it matches the most recent opening bracket.
elif s[i] == ']':
# Remove the corresponding opening bracket.
st.pop()
# If the stack becomes empty,
# the current closing bracket matches
# the opening bracket at pos.
if not st:
return i
# This case is not expected because
# the input is guaranteed to have valid brackets.
return -1
# Driver Code
if __name__ == "__main__":
s = "[ABC[23]][89]"
pos = 0
print(closing(s, pos))
using System;
using System.Collections.Generic;
class GFG {
static int closing(string s, int pos)
{
// Stack stores the indices of opening brackets.
Stack<int> st = new Stack<int>();
// Traverse the string starting from the given
// position.
for (int i = pos; i < s.Length; i++) {
// If an opening bracket is found,
// store its index in the stack.
if (s[i] == '[') {
st.Push(i);
}
// If a closing bracket is found,
// it matches the most recent opening bracket.
else if (s[i] == ']') {
// Remove the corresponding opening bracket.
st.Pop();
// If the stack becomes empty,
// the current closing bracket matches
// the opening bracket at pos.
if (st.Count == 0)
return i;
}
}
// This case is not expected because
// the input is guaranteed to have valid brackets.
return -1;
}
public static void Main()
{
string s = "[ABC[23]][89]";
int pos = 0;
Console.WriteLine(closing(s, pos));
}
}
function closing(s, pos)
{
// Stack stores the indices of opening brackets.
let st = [];
// Traverse the string starting from the given position.
for (let i = pos; i < s.length; i++) {
// If an opening bracket is found,
// store its index in the stack.
if (s[i] === "[") {
st.push(i);
}
// If a closing bracket is found,
// it matches the most recent opening bracket.
else if (s[i] === "]") {
// Remove the corresponding opening bracket.
st.pop();
// If the stack becomes empty,
// the current closing bracket matches
// the opening bracket at pos.
if (st.length === 0)
return i;
}
}
// This case is not expected because
// the input is guaranteed to have valid brackets.
return -1;
}
// Driver Code
let s = "[ABC[23]][89]";
let pos = 0;
console.log(closing(s, pos));
Output
8
[Expected Approach] Using Balance Counter - O(n) Time and O(1) Space
Since there is only one type of bracket, we do not need stack. The idea is to maintain a balance counter. Increase the counter whenever [ is found and decrease it whenever ] is found.
When the counter becomes 0, all brackets opened from pos have been closed, so the current index is the corresponding closing bracket.
- Initialize cnt = 0.
- Traverse the string from pos to the end.
- If the current character is [, increment cnt.
- If the current character is ], decrement cnt.
- When cnt becomes 0, return the current index.
- Return -1 if no matching bracket is found.
#include <bits/stdc++.h>
using namespace std;
int closing(string &s, int pos)
{
// Balance keeps track of the number of
// unmatched opening brackets.
int balance = 0;
// Traverse the string starting from the given position.
for (int i = pos; i < s.size(); i++)
{
// If an opening bracket is found,
// increase the balance.
if (s[i] == '[')
balance++;
// If a closing bracket is found,
// decrease the balance.
else if (s[i] == ']')
balance--;
// When the balance becomes zero,
// the current bracket matches the opening
// bracket at position pos.
if (balance == 0)
return i;
}
// This case is not expected because
// the input is guaranteed to have valid brackets.
return -1;
}
int main()
{
string s = "[ABC[23]][89]";
int pos = 0;
cout << closing(s, pos) << endl;
return 0;
}
class GFG {
static int closing(String s, int pos)
{
// Balance keeps track of the number of
// unmatched opening brackets.
int balance = 0;
// Traverse the string starting from the given
// position.
for (int i = pos; i < s.length(); i++) {
// If an opening bracket is found,
// increase the balance.
if (s.charAt(i) == '[')
balance++;
// If a closing bracket is found,
// decrease the balance.
else if (s.charAt(i) == ']')
balance--;
// When the balance becomes zero,
// the current bracket matches the opening
// bracket at position pos.
if (balance == 0)
return i;
}
// This case is not expected because
// the input is guaranteed to have valid brackets.
return -1;
}
public static void main(String[] args)
{
String s = "[ABC[23]][89]";
int pos = 0;
System.out.println(closing(s, pos));
}
}
def closing(s, pos):
# Balance keeps track of the number of
# unmatched opening brackets.
balance = 0
# Traverse the string starting from the given position.
for i in range(pos, len(s)):
# If an opening bracket is found,
# increase the balance.
if s[i] == '[':
balance += 1
# If a closing bracket is found,
# decrease the balance.
elif s[i] == ']':
balance -= 1
# When the balance becomes zero,
# the current bracket matches the opening
# bracket at position pos.
if balance == 0:
return i
# This case is not expected because
# the input is guaranteed to have valid brackets.
return -1
# Driver Code
if __name__ == "__main__":
s = "[ABC[23]][89]"
pos = 0
print(closing(s, pos))
using System;
class GFG {
static int closing(string s, int pos)
{
// Balance keeps track of the number of
// unmatched opening brackets.
int balance = 0;
// Traverse the string starting from the given
// position.
for (int i = pos; i < s.Length; i++) {
// If an opening bracket is found,
// increase the balance.
if (s[i] == '[')
balance++;
// If a closing bracket is found,
// decrease the balance.
else if (s[i] == ']')
balance--;
// When the balance becomes zero,
// the current bracket matches the opening
// bracket at position pos.
if (balance == 0)
return i;
}
// This case is not expected because
// the input is guaranteed to have valid brackets.
return -1;
}
public static void Main()
{
string s = "[ABC[23]][89]";
int pos = 0;
Console.WriteLine(closing(s, pos));
}
}
function closing(s, pos)
{
// Balance keeps track of the number of
// unmatched opening brackets.
let balance = 0;
// Traverse the string starting from the given position.
for (let i = pos; i < s.length; i++) {
// If an opening bracket is found,
// increase the balance.
if (s[i] === "[")
balance++;
// If a closing bracket is found,
// decrease the balance.
else if (s[i] === "]")
balance--;
// When the balance becomes zero,
// the current bracket matches the opening
// bracket at position pos.
if (balance === 0)
return i;
}
// This case is not expected because
// the input is guaranteed to have valid brackets.
return -1;
}
// Driver Code
let s = "[ABC[23]][89]";
let pos = 0;
console.log(closing(s, pos));
Output
8