# How to calculate whether a parenthesis string is valid using a 2-tape Turing machine?

If I have a language over alphabet $\Sigma=\{(,[,],)\}$. How can I find out if a tape has a valid (matching) parentheses structure in linear time?

So far, my attempt is as follows:

• state 0: accept ( or [ i.e. no open parentheses
• state 1: accept ), ( or [ i.e. a ( has occurred previously
• state 2: accept ], ( or [ i.e. a [ has occurred previously

The problem with this setup is that I won't know how many ( or [ has occurred previously. One idea was to store how many occurrences of open parentheses of each kind on the second tape, but this would potentially require an infinite tape alphabet. So it seems as if I'm approaching the problem the wrong way.

How can I create a Turing machine that wouldn't need to store the amount of open parentheses while still being able to accomplish this in linear time?

I looked at this question already, but couldn't figure out how this would be applicable to multiple types of parentheses and still be done in linear time.

Any input would be much appreciated!

• Your attempt so far appears to be a DFA, which can't work, since the language isn't regular. Note also that this question is about having two tapes, whereas the one you link to is about two states, so probably won't help. You can store numbers on the second tape in binary: you don't need an infinite alphabet. Jul 4, 2017 at 15:35

As others have pointed out, you can use a stack to check for matching parentheses. Such manipulation is the base idea of the shunting yard algorithm by Dijkstra.

Hint: use the second tape to store the stack of open brackets and parentheses you've seen. Each time you see a close, manipulate the stack appropriately.

• Thanks for the input! Could you elaborate a bit more on the functionality of the stack?
– Void
Jul 4, 2017 at 16:46
• I'm not sure I can really say more without solving the exercise for you. I've told you what should go on the stack (each time you see a ( or a [, you put it on the stack) so you just need to figure out what to do when you see ) or ]. Jul 4, 2017 at 17:00
• Ok, maybe I'm seeing this the wrong way, but isn't the time complexity surpass linear time by having to move the second head back and forth like that?
– Void
Jul 4, 2017 at 17:11
• The point of using a stack is that the second head never has to move more than one step to find the thing it needs. Jul 4, 2017 at 17:13
• @Void each symbol the main head reads only results in at most 2 total moves of the heads (one to move the main head forward and maybe one to optionally move the second head 1 space when pushing or popping) Jul 5, 2017 at 11:09