What is the time complexity of the following code? public boolean…

2023

What is the time complexity of the following code?

public boolean isBalanced(String exp)

{

int len = exp.length();

Stack stk = new Stack();

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;

}

  1. A.

    O(logn)

  2. B.

    O(n)

  3. C.

    O(1)

  4. D.

    O(nlogn)

Attempted by 78 students.

Show answer & explanation

Correct answer: B

Answer: b

Explanation: All the characters in the string have to be processed, hence the complexity is O(n).

Explore the full course: Coding For Placement