0
$\begingroup$

Both these algorithms determine if all the parenthesis in a string are balanced and properly nested.

The first algorithm uses "a constant amount of memory, regardless of the length of the string."

Algorithm 1

The second algorithm "may use O(n) memory but must use a stack".

Algorithm 2

I understand how the algorithms work but I don't understand the descriptions of time complexity.

My understanding is that they are both O(n) because they both use a single for loop and the length of time it will take to execute them depends on the size of the string.

Also on algorithm 2 I believe the last bit should be if t!=0 instead of ==?

Any help understanding these descriptions of time complexity would be greatly appreciated. Thanks.

asked Apr 8, 2022 at 17:50
$\endgroup$
6
  • $\begingroup$ cs.stackexchange.com/q/192/755, cs.stackexchange.com/q/23593/755, cs.stackexchange.com/q/23068/755 $\endgroup$ Commented Apr 8, 2022 at 18:27
  • $\begingroup$ What do you know about the time taken by s(i), t.push(), t.pop(), t.length? $\endgroup$ Commented Apr 9, 2022 at 6:50
  • $\begingroup$ They run in O(1)? $\endgroup$ Commented Apr 9, 2022 at 18:43
  • $\begingroup$ @BenHarris You have a pretty good understanding of time-complexity. It looks like you have no questions. $\endgroup$ Commented Apr 9, 2022 at 21:32
  • 1
    $\begingroup$ I’m voting to close this question because OP has got all the right answers. No questions. $\endgroup$ Commented Apr 9, 2022 at 21:33

1 Answer 1

0
$\begingroup$

Two algorithms can have the same (asymptotic) time complexity but differ in their space complexity. The amount of extra storage space consumed by the algorithm is another performance measure of the algorithm.

Both your algorithms have the same asymptotic running time $O(n)$, but they differ in their memory usage. The first algorithm uses only $O(1)$ auxiliary storage space (for example, the variable count is used). On the other hand, the second algorithm takes $O(n)$ extra storage, because in the worst-case, the input would be of the form $(^{n/2} )^{n/2}$, i.e. $n/2$ opening parantheses followed by $n/2$ closing parantheses, and the algorithm would have to store $n/2 = O(n)$ bytes on the stack.

Yes, the == should be !=.

answered Apr 20, 2022 at 15:59
$\endgroup$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.