#include<bits/stdc++.h>
using namespace std;
int main()
{
    long long t,i;
    cin>>t;
    string s;
    while(t--)
    {
        cin>>s;
        long long sum1=0,sum2=0,ans=0,flag1=0,flag2=0;
        stack<char>s1,s2;
        for(i=0;i<s.length();i++)
        {
            if(s[i]=='(')
                s1.push(s[i]);
            if(s[i]==')'&&!s1.empty())
            {
                sum1++;
                s1.pop();
            }
            if(s[i]==')'&&s1.empty())
                flag1=1;
            if(s[i]=='[')
                s2.push(s[i]);
            if(s[i]==']'&&!s2.empty())
            {
                sum2++;
                s2.pop();
            }
            if(s[i]==']'&&s2.empty())
                flag2=1; 
        }
        ans+=sum1+sum2;
        if(!s1.empty()||!s2.empty()||flag1||flag2)
             ans++;
        cout<<ans-1<<endl;
    }   
    
}