Cow Cotillion

Interview

Time limit1sMemory limit128 MB

Summary
Given strings of '<' and '>', decide for each whether every character can be paired as a properly nested '><' bow, i.e. whether the brackets are balanced.
Level

Easy3 of 10

Topics
Stack, String, Implementation, Greedy
Solved
No attempts yet

Problem

The cow cotillion is a fancy spring dance in which the cows (written as >) and the bulls (written as <) bow to each other. A single, properly bowing pair is written ><.

Sometimes another pair sashays between a bowing pair, giving > >< < (that is, >><<). Larger groups can mix on the dance floor, such as > >< < ><, which adds a second bowing pair on the right.

Even complex arrangements can be perfectly legal formations:

> > > >< < >< < >< >< >< <

| | | -- | -- | -- -- -- |
| | ------    |          |
| -------------          |
--------------------------

Sometimes a stray heifer sneaks into a group and unbalances it, for example > >< < <><. This is strictly forbidden.

Farmer John records dance lines of up to 500 cattle and wonders whether each line is properly balanced — that is, whether every animal can be paired off, in at least one way, as a properly bowing >< pair. He writes down only the direction each animal bows, with no spaces; for instance, the illegal line above becomes >><<<><.

Equivalently, treat > as an opening bracket and < as a closing bracket: a line is legal exactly when the brackets are balanced (scanning left to right, every < matches an earlier still-unmatched >, and no animal is left unmatched).

You are given NN recordings. Each recording is a string PP made up only of the characters > and <. For each recording, print legal if all the cattle can be paired into proper bowing pairs, and illegal otherwise.

Constraints

  • 1≤N≤10001 \le N \le 1000
  • Each pattern has length KK with 1≤K≤2001 \le K \le 200.

Input

  • Line 1: a single integer NN.
  • Lines 2…N+12 \ldots N+1: line ii contains an integer KiK_i, a space, and a string of KiK_i characters (each > or <) — the length KiK_i and the pattern PiP_i.

Output

  • Lines 1…N1 \ldots N: line ii contains legal if pattern PiP_i forms a valid bowing configuration, or illegal otherwise.

Examples6

  1. Example 1

    Input
    2
    6 >><<><
    4 ><<>
    
    Expected output
    legal
    illegal
    
  2. Example 2

    Input
    1
    2 ><
    
    Expected output
    legal
    
  3. Example 3

    Input
    1
    1 >
    
    Expected output
    illegal
    
  4. Example 4

    Input
    1
    1 <
    
    Expected output
    illegal
    
  5. Example 5

    Input
    1
    4 >><<
    
    Expected output
    legal
    
  6. Example 6

    Input
    1
    7 >><<<><
    
    Expected output
    illegal