What is the time complexity of the following code? public boolean…
2024
What is the time complexity of the following code?
public boolean isBalanced(String exp)
{
int len = exp.length();
Stack <Integer> stk = new Stack<Integer>();
for(int i = 0; i < len; i++)
{
char ch = exp.charAt(i);
if (ch == '(')
stk.push(i);
else if (ch == ')')
{
if(stk.peek() == null)
{
return false;
}
stk.pop();
}
}
return true;
}
Answer: B. O(n) — Answer: b Explanation: The code processes each character in the string exactly once in a single loop. The loop runs for n iterations, where n is the length of…
- A.
O(logn)
- B.
O(n)
- C.
O(1)
- D.
O(nlogn)
Attempted by 263 students.
Show answer & explanation
Correct answer: B
Answer: b
Explanation: The code processes each character in the string exactly once in a single loop. The loop runs for n iterations, where n is the length of the string. Inside the loop, each operation (push, pop, peek) on the stack is O(1). Since the loop runs n times and each operation is constant time, the total time complexity is O(n).