import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;

public class C {
	public static void main(String[] args)
	{
		FastScanner in=new FastScanner();
		int tt=in.nextInt();
		while(tt-->0)
		{
			String x=in.next();
			int l=x.length();
			int count=0;
			for(int i=0;i<l-1;i++)
			{
				String pair=String.valueOf(x.charAt(i))+String.valueOf(x.charAt(i+1));
				int len=l-x.replace(pair, "").length();
				if(count<len)
					count=len;
			}
			System.out.println(l-count);
		}
	}
static final Random random=new Random();

	static void ruffleSort(int[] a) {
		int n=a.length;//shuffle, then sort
		for (int i=0; i<n; i++) {
			int oi=random.nextInt(n), temp=a[oi];
			a[oi]=a[i]; a[i]=temp;
		}
		Arrays.sort(a);
	}

	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}
		int[] readArray(int n) {
			int[] a=new int[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
		}
		long nextLong() {
			return Long.parseLong(next());
		}
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;

public class C {
	public static void main(String[] args)
	{
		FastScanner in=new FastScanner();
		int tt=in.nextInt();
		while(tt-->0)
		{
			int[] count=new int[10];
			int[] counte=new int[10];
			int[] counto=new int[10];
			char[] x=in.next().toCharArray();
			int l=x.length;
			for(int i=0;i<l;i++)
			count[x[i]-'0']++;
			int max=0,ans=0;
			if(l%2==1)
			{
				for(int i=0;i<10;i++)
				{
					if(max<count[i])
						max=count[i];
				}
				if(max==1)
					max=2;
				ans=l-max;
			}
			else
			{
				for(int i=0;i<10;i++)
				{
					for(int j=0;j<10;j++)
					{
						int len=0;
						for(char c: x)
						{
							if(len%2==0)
							{
							if((c-'0')==i) len++;
							}
							else {
								if((c-'0')==j) len++;
							}
						}
						len-=len%2;
						max=Math.max(len,max);
					}
				}
				ans=l-max;
			}
			System.out.println(ans);
		}
	}
static final Random random=new Random();

	static void ruffleSort(int[] a) {
		int n=a.length;//shuffle, then sort
		for (int i=0; i<n; i++) {
			int oi=random.nextInt(n), temp=a[oi];
			a[oi]=a[i]; a[i]=temp;
		}
		Arrays.sort(a);
	}

	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}
		int[] readArray(int n) {
			int[] a=new int[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
		}
		long nextLong() {
			return Long.parseLong(next());
		}
	}
}


import java.util.*;
import java.io.*;

public class C {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		while(t-->0) {
			char[] a = sc.next().toCharArray();
			int[] counts = new int[10];
			int n = a.length;
			for(int i = 0; i < n; i++) {
				counts[a[i] - '0']++;
			}
			Arrays.sort(counts);
			int maxToKeep = counts[9];
			for(int f = 0; f < 10; f++) {
				for(int s = 0; s < 10; s++) {
					int curToKeep = 0;
					for(int i = 0; i < n; i++) {
						if(curToKeep % 2 == 0) {
							if(a[i] - '0' == f) {
								curToKeep++;
							}
						} else {
							if(a[i] - '0' == s) {
								curToKeep++;
							}
						}
					}
					curToKeep -= curToKeep%2;
					maxToKeep = Math.max(curToKeep, maxToKeep);
				}
			}
			System.out.println(n - maxToKeep);
		}
	}
}


import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        in.nextLine();
        for (; t > 0; t--) {
            char[] a = in.nextLine().toCharArray();
            int two = a.length - 2;
            int count[] = new int[10];

            for (int i = 0; i < a.length; i++) {
                count[a[i] - '0']++;
            }

            int max = 0;
            for (int i = 0; i < count.length; i++) {
                if (max < count[i]) {
                    max = count[i];
                }
            }
            int allSame = a.length - max;

            ArrayList<ArrayList<ArrayList<Integer>>> c = new ArrayList<ArrayList<ArrayList<Integer>>>();
            for (int i = 0; i < 10; i++) {
                c.add(new ArrayList<ArrayList<Integer>>());
                for (int j = 0; j < 10; j++) {
                    c.get(i).add(new ArrayList<Integer>());
                }
            }
            for (int i = 0; i < a.length; i++) {
                for (int j = 0; j < 10; j++) {
                    if (c.get(j).get(a[i] - '0').isEmpty()
                            || c.get(j).get(a[i] - '0').get(c.get(j).get(a[i] - '0').size() - 1) != a[i] - '0')
                        c.get(j).get(a[i] - '0').add(a[i] - '0');
                    if (c.get(a[i] - '0').get(j).isEmpty()
                            || c.get(a[i] - '0').get(j).get(c.get(a[i] - '0').get(j).size() - 1) != a[i] - '0')
                        c.get(a[i] - '0').get(j).add(a[i] - '0');
                }
            }
            max = 0;
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 10; j++) {
                    if (c.get(i).get(j).size() > max) {
                        if (c.get(i).get(j).size() % 2 == 1) {
                            max = c.get(i).get(j).size() - 1;
                        } else {
                            max = c.get(i).get(j).size();
                        }
                    }
                }
            }
            int twoRep = a.length - max;
            System.out.println(Math.min(twoRep, Math.min(two, allSame)));
        }
        in.close();
    }

}


import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        in.nextLine();
        for (; t > 0; t--) {
            char[] a = in.nextLine().toCharArray();
            int two = a.length - 2;
            int count[] = new int[10];

            for (int i = 0; i < a.length; i++) {
                count[a[i] - '0']++;
            }

            int max = 0;
            for (int i = 0; i < count.length; i++) {
                if (max < count[i]) {
                    max = count[i];
                }
            }
            int allSame = a.length - max;

            int[] countOdd = new int[10];
            int[] countEven = new int[10];
            for (int i = 0; i < a.length; i++) {
                if (i % 2 == 0) {
                    countEven[a[i] - '0']++;
                } else {
                    countOdd[a[i] - '0']++;
                }
            }

            int maxOdd = 0;
            int maxEven = 0;
            for (int i = 0; i < countOdd.length; i++) {
                if (maxOdd < countOdd[i]) {
                    maxOdd = countOdd[i];
                }
            }
            for (int i = 0; i < countEven.length; i++) {
                if (maxEven < countEven[i]) {
                    maxEven = countEven[i];
                }
            }
            int twoRep = a.length - Math.min(maxOdd, maxEven) * 2;
            System.out.println(Math.min(twoRep, Math.min(two, allSame)));
        }
        in.close();
    }

}


import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        in.nextLine();
        for (; t > 0; t--) {
            char[] a = in.nextLine().toCharArray();
            int two = a.length - 2;
            int count[] = new int[10];

            for (int i = 0; i < a.length; i++) {
                count[a[i] - '0']++;
            }

            int max = 0;
            for (int i = 0; i < count.length; i++) {
                if (max < count[i]) {
                    max = count[i];
                }
            }
            int allSame = a.length - max;

            int[] countOdd = new int[10];
            int[] countEven = new int[10];
            for (int i = 0; i < a.length; i++) {
                if (i % 2 == 0) {
                    countEven[a[i] - '0']++;
                } else {
                    countOdd[a[i] - '0']++;
                }
            }

            int maxOdd = 0;
            int maxEven = 0;
            for (int i = 0; i < countOdd.length; i++) {
                if (maxOdd < countOdd[i]) {
                    maxOdd = countOdd[i];
                }
            }
            for (int i = 0; i < countEven.length; i++) {
                if (maxEven < countEven[i]) {
                    maxEven = countEven[i];
                }
            }
            int twoRep = a.length - maxOdd - maxEven;
            if (a.length % 2 == 1) {
                twoRep = Integer.MAX_VALUE;
            }
            System.out.println(Math.min(twoRep, Math.min(two, allSame)));
        }
        in.close();
    }

}


import java.util.*;import java.io.*;import java.math.*;
public class Main
{
    public static void process()throws IOException
    {
        String s=nln();
        int n=s.length();
        int[]A=new int[n];
        for(int i=0;i<n;i++)
            A[i]=s.charAt(i)-48;
        int max=0;
        for(int i=0;i<10;i++)
        {
            for(int j=0;j<10;j++)
            {
                int len=0;
                int flag=i;
                for(int k=0;k<n;k++)
                {
                    if(A[k]==flag)
                    {
                        len++;
                        if(flag==i)
                            flag=j;
                        else flag=i;
                    }
                }
                if(len%2==0)
                    max=Math.max(len,max);
            }
        }
        pn(n-max);

    }

    static AnotherReader sc;
    static PrintWriter out;
    public static void main(String[]args)throws IOException
    {
        boolean oj = System.getProperty("ONLINE_JUDGE") != null;
        if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);}
        else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");}
        int t=1;
        t=ni();
        while(t-->0) {process();}
        out.flush();out.close();
    }

    static void pn(Object o){out.println(o);}
    static void p(Object o){out.print(o);}
    static void pni(Object o){out.println(o);out.flush();}
    static int ni()throws IOException{return sc.nextInt();}
    static long nl()throws IOException{return sc.nextLong();}
    static double nd()throws IOException{return sc.nextDouble();}
    static String nln()throws IOException{return sc.nextLine();}
    static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;}
    static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;}
    static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);}
    static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);}
    static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

    static class AnotherReader{BufferedReader br; StringTokenizer st;
    AnotherReader()throws FileNotFoundException{
    br=new BufferedReader(new InputStreamReader(System.in));}
    AnotherReader(int a)throws FileNotFoundException{
    br = new BufferedReader(new FileReader("input.txt"));}
    String next()throws IOException{
    while (st == null || !st.hasMoreElements()) {try{
    st = new StringTokenizer(br.readLine());}
    catch (IOException  e){ e.printStackTrace(); }}
    return st.nextToken(); } int nextInt() throws IOException{
    return Integer.parseInt(next());}
    long nextLong() throws IOException
    {return Long.parseLong(next());}
    double nextDouble()throws IOException { return Double.parseDouble(next()); }
    String nextLine() throws IOException{ String str = ""; try{
    str = br.readLine();} catch (IOException e){
    e.printStackTrace();} return str;}}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
}


import java.util.*;import java.io.*;import java.math.*;
public class Main
{
    public static void process()throws IOException
    {
        String s=nln();
        int n=s.length();
        int[]A=new int[n];
        for(int i=0;i<n;i++)
            A[i]=s.charAt(i)-48;
        int max=0;
        for(int i=0;i<10;i++)
        {
            for(int j=0;j<10;j++)
            {
                int len=0;
                int flag=i;
                for(int k=0;k<n;k++)
                {
                    if(A[k]==flag)
                    {
                        len++;
                        if(flag==i)
                            flag=j;
                        else flag=i;
                    }
                }
                if(len%2==0)
                    max=Math.max(len,max);
                else
                    max=Math.max(len-1,max);
            }
        }
        pn(n-max);

    }

    static AnotherReader sc;
    static PrintWriter out;
    public static void main(String[]args)throws IOException
    {
        boolean oj = System.getProperty("ONLINE_JUDGE") != null;
        if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);}
        else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");}
        int t=1;
        t=ni();
        while(t-->0) {process();}
        out.flush();out.close();
    }

    static void pn(Object o){out.println(o);}
    static void p(Object o){out.print(o);}
    static void pni(Object o){out.println(o);out.flush();}
    static int ni()throws IOException{return sc.nextInt();}
    static long nl()throws IOException{return sc.nextLong();}
    static double nd()throws IOException{return sc.nextDouble();}
    static String nln()throws IOException{return sc.nextLine();}
    static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;}
    static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;}
    static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);}
    static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);}
    static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

    static class AnotherReader{BufferedReader br; StringTokenizer st;
    AnotherReader()throws FileNotFoundException{
    br=new BufferedReader(new InputStreamReader(System.in));}
    AnotherReader(int a)throws FileNotFoundException{
    br = new BufferedReader(new FileReader("input.txt"));}
    String next()throws IOException{
    while (st == null || !st.hasMoreElements()) {try{
    st = new StringTokenizer(br.readLine());}
    catch (IOException  e){ e.printStackTrace(); }}
    return st.nextToken(); } int nextInt() throws IOException{
    return Integer.parseInt(next());}
    long nextLong() throws IOException
    {return Long.parseLong(next());}
    double nextDouble()throws IOException { return Double.parseDouble(next()); }
    String nextLine() throws IOException{ String str = ""; try{
    str = br.readLine();} catch (IOException e){
    e.printStackTrace();} return str;}}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
}


import java.util.*;import java.io.*;import java.math.*;
public class Main
{
    public static void process()throws IOException
    {
        String s=nln();
        int n=s.length();
        int[]A=new int[n];
        for(int i=0;i<n;i++)
            A[i]=s.charAt(i)-48;
        int max=0;
        for(int i=0;i<10;i++)
        {
            for(int j=0;j<10;j++)
            {
                int len=0;
                int flag=i;
                for(int k=0;k<n;k++)
                {
                    if(A[k]==flag)
                    {
                        len++;
                        if(flag==i)
                            flag=j;
                        else flag=i;
                    }
                }
                if(i==j)
                    max=Math.max(len,max);
                else
                {
                    if(len%2==0)
                        max=Math.max(len,max);
                    else
                        max=Math.max(len-1,max);
                }
            }
        }
        pn(n-max);

    }

    static AnotherReader sc;
    static PrintWriter out;
    public static void main(String[]args)throws IOException
    {
        boolean oj = System.getProperty("ONLINE_JUDGE") != null;
        if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);}
        else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");}
        int t=1;
        t=ni();
        while(t-->0) {process();}
        out.flush();out.close();
    }

    static void pn(Object o){out.println(o);}
    static void p(Object o){out.print(o);}
    static void pni(Object o){out.println(o);out.flush();}
    static int ni()throws IOException{return sc.nextInt();}
    static long nl()throws IOException{return sc.nextLong();}
    static double nd()throws IOException{return sc.nextDouble();}
    static String nln()throws IOException{return sc.nextLine();}
    static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;}
    static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;}
    static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);}
    static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);}
    static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

    static class AnotherReader{BufferedReader br; StringTokenizer st;
    AnotherReader()throws FileNotFoundException{
    br=new BufferedReader(new InputStreamReader(System.in));}
    AnotherReader(int a)throws FileNotFoundException{
    br = new BufferedReader(new FileReader("input.txt"));}
    String next()throws IOException{
    while (st == null || !st.hasMoreElements()) {try{
    st = new StringTokenizer(br.readLine());}
    catch (IOException  e){ e.printStackTrace(); }}
    return st.nextToken(); } int nextInt() throws IOException{
    return Integer.parseInt(next());}
    long nextLong() throws IOException
    {return Long.parseLong(next());}
    double nextDouble()throws IOException { return Double.parseDouble(next()); }
    String nextLine() throws IOException{ String str = ""; try{
    str = br.readLine();} catch (IOException e){
    e.printStackTrace();} return str;}}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
}


import java.math.BigInteger;
import java.util.*;

public class ak {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
       /* int n = sc.nextInt();
        int m = sc.nextInt();
        System.out.println(numberSorter(n,m));
*/
       int t=sc.nextInt();
        sc.nextLine();
        while(t-->0) {
           char ar[] = sc.nextLine().toCharArray();
           int n = ar.length;
           int no[] = new int[n];
           for (int i = 0; i < n; i++) {
               no[i] = ar[i] - '0';
           }
          // System.out.println(Arrays.toString(no));
           int ans = Integer.MAX_VALUE;
           for (int i = 0; i < 10; i++) {
               for (int j = 0; j < 10; j++) {
                   int cur = i;
                   int remove = 0;
                   for (int k = 0; k < n; k++) {
                       cur = (k & 1) > 0 ? i : j;
                       if (no[k] != cur) {
                           remove++;
                       }
                   }
                   ans = Math.min(ans, remove);
               }
           }
           System.out.println(ans);
       }
    }
    public static int numberSorter(int month,int day)
    {

        int days[]={31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        int m=0;
        int c=0;
        for(int i=0;i<month-1;i++)
        {
        for(int j=1;j<=days[i];j++)
        {
            c=c+1;
            c%=7;
        }
        }
        for(int j=1;j<=day&&j<=days[month-1];j++)
        {
            c=c+1;
            c%=7;
        }
        String da[]={ "WED",
            "THU", "FRI", "SAT", "SUN","MON", "TUE"};
        System.out.println(da[(c-1+7)%7]);
        //return da[c-1];
        // System.out.println(da[c-1]);
        /*int ans=0;
        int dg[]=new int[10];
        int t=n;
        while(t>0)
        {
            int d=t%10;
            dg[d]++;
            t/=10;
        }
        for(int i=9;i>=0;i--)
        {
            if(dg[i]>0) {
                while (dg[i] > 0) {
                dg[i]--;
                ans=ans*10+i;
                }
            }
        }
        return ans;
    */
return 0;
    }
}


import java.math.BigInteger;
import java.util.*;

public class ak {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
       /* int n = sc.nextInt();
        int m = sc.nextInt();
        System.out.println(numberSorter(n,m));
*/
       int t=sc.nextInt();
        sc.nextLine();
        while(t-->0) {
           char ar[] = sc.nextLine().toCharArray();
           int n = ar.length;
           int no[] = new int[n];
           for (int i = 0; i < n; i++) {
               no[i] = ar[i] - '0';
           }
          //  System.out.println(n);
          // System.out.println(Arrays.toString(no));
           int ans = Integer.MIN_VALUE;
           for (int i = 0; i < 10; i++) {
               for (int j = 0; j < 10; j++) {
                   int cur = i;
                   int remove =0;
                   for (int k = 0; k < n; k++) {
                      if (no[k] == cur) {
                          cur = cur==i ? j : i;
                          remove++;
                       }
                   }
                   remove=i!=j&&remove%2!=0?remove-1:remove;
                   ans = Math.max(ans, remove);
               }
           }
           System.out.println(n-ans);
       }
    }
    public static int numberSorter(int month,int day)
    {

        int days[]={31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        int m=0;
        int c=0;
        for(int i=0;i<month-1;i++)
        {
        for(int j=1;j<=days[i];j++)
        {
            c=c+1;
            c%=7;
        }
        }
        for(int j=1;j<=day&&j<=days[month-1];j++)
        {
            c=c+1;
            c%=7;
        }
        String da[]={ "WED",
            "THU", "FRI", "SAT", "SUN","MON", "TUE"};
        System.out.println(da[(c-1+7)%7]);
        //return da[c-1];
        // System.out.println(da[c-1]);
        /*int ans=0;
        int dg[]=new int[10];
        int t=n;
        while(t>0)
        {
            int d=t%10;
            dg[d]++;
            t/=10;
        }
        for(int i=9;i>=0;i--)
        {
            if(dg[i]>0) {
                while (dg[i] > 0) {
                dg[i]--;
                ans=ans*10+i;
                }
            }
        }
        return ans;
    */
return 0;
    }
}


import java.util.*;import java.io.*;import java.math.*;
public class GoodString
{
    public static void process()throws IOException
    {
        String s = nln();
        int n = s.length();
        if(n == 2){
            pn(0);
            return;
        }
        int[] dp = new int[100];
        for(int i = 0; i < n-1; i++){
            String ch = s.charAt(i) + "" + s.charAt(i+1);
            dp[Integer.parseInt(ch)]++;
        }
        int ans = 0, val = 0;
        for(int i = 0; i < 100; i++){
            if(ans < dp[i]){
                ans = dp[i];
                val = i;
            }
        }
        int[] f = new int[10];
        int ans1 = 0, v1 = 0;
        for(int i = 0; i < n; i++){
           int c = Integer.parseInt(s.charAt(i) + "");
           f[c]++;
        }
        for(int i = 0; i < 10; i++){
            if(ans1 < f[i])
                ans1 = f[i];
        }
        ans = n - Math.max(ans*2, ans1);
        pn(ans);
    }

    static AnotherReader sc;
    static PrintWriter out;
    public static void main(String[]args)throws IOException
    {
        boolean oj = System.getProperty("ONLINE_JUDGE") != null;
        if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);}
        else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");}
        long s = System.currentTimeMillis();
        int t=1;
        t=ni();
        while(t-->0) {process();}
        out.flush();
        System.err.println(System.currentTimeMillis()-s+"ms");
        out.close();
    }

    static void pn(Object o){out.println(o);}
    static void p(Object o){out.print(o);}
    static void pni(Object o){out.println(o);out.flush();}
    static int ni()throws IOException{return sc.nextInt();}
    static long nl()throws IOException{return sc.nextLong();}
    static double nd()throws IOException{return sc.nextDouble();}
    static String nln()throws IOException{return sc.nextLine();}
    static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;}
    static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;}
    static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);}
    static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);}
    static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));}
    static long power(long k, long c, long mod){
        long y = 1;
        while(c > 0){
            if(c%2 == 1)
                y = y * k % mod;
            c = c/2;
            k = k * k % mod;
        }
        return y;
    }

/////////////////////////////////////////////////////////////////////////////////////////////////////////

    static class AnotherReader{BufferedReader br; StringTokenizer st;
    AnotherReader()throws FileNotFoundException{
    br=new BufferedReader(new InputStreamReader(System.in));}
    AnotherReader(int a)throws FileNotFoundException{
    br = new BufferedReader(new FileReader("input.txt"));}
    String next()throws IOException{
    while (st == null || !st.hasMoreElements()) {try{
    st = new StringTokenizer(br.readLine());}
    catch (IOException  e){ e.printStackTrace(); }}
    return st.nextToken(); } int nextInt() throws IOException{
    return Integer.parseInt(next());}
    long nextLong() throws IOException
    {return Long.parseLong(next());}
    double nextDouble()throws IOException { return Double.parseDouble(next()); }
    String nextLine() throws IOException{ String str = ""; try{
    str = br.readLine();} catch (IOException e){
    e.printStackTrace();} return str;}}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
}


import java.util.*;import java.io.*;import java.math.*;
public class GoodString
{
    public static void process()throws IOException
    {
        String s = nln();
        int n = s.length();
        if(n == 2){
            pn(0);
            return;
        }
        int[] dp = new int[100];
        for(int i = 0; i < n-1; i+= 2){
            String ch = s.charAt(i) + "" + s.charAt(i+1);
            dp[Integer.parseInt(ch)]++;
        }
        int ans = 0, val = 0;
        for(int i = 0; i < 100; i++){
            if(ans < dp[i]){
                ans = dp[i];
                val = i;
            }
        }
        int[] f = new int[10];
        int ans1 = 0, v1 = 0;
        for(int i = 0; i < n; i++){
           int c = Integer.parseInt(s.charAt(i) + "");
           f[c]++;
        }
        for(int i = 0; i < 10; i++){
            if(ans1 < f[i])
                ans1 = f[i];
        }
        ans = n - Math.max(ans*2, ans1);
        pn(ans);
    }

    static AnotherReader sc;
    static PrintWriter out;
    public static void main(String[]args)throws IOException
    {
        boolean oj = System.getProperty("ONLINE_JUDGE") != null;
        if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);}
        else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");}
        long s = System.currentTimeMillis();
        int t=1;
        t=ni();
        while(t-->0) {process();}
        out.flush();
        System.err.println(System.currentTimeMillis()-s+"ms");
        out.close();
    }

    static void pn(Object o){out.println(o);}
    static void p(Object o){out.print(o);}
    static void pni(Object o){out.println(o);out.flush();}
    static int ni()throws IOException{return sc.nextInt();}
    static long nl()throws IOException{return sc.nextLong();}
    static double nd()throws IOException{return sc.nextDouble();}
    static String nln()throws IOException{return sc.nextLine();}
    static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;}
    static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;}
    static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);}
    static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);}
    static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));}
    static long power(long k, long c, long mod){
        long y = 1;
        while(c > 0){
            if(c%2 == 1)
                y = y * k % mod;
            c = c/2;
            k = k * k % mod;
        }
        return y;
    }

/////////////////////////////////////////////////////////////////////////////////////////////////////////

    static class AnotherReader{BufferedReader br; StringTokenizer st;
    AnotherReader()throws FileNotFoundException{
    br=new BufferedReader(new InputStreamReader(System.in));}
    AnotherReader(int a)throws FileNotFoundException{
    br = new BufferedReader(new FileReader("input.txt"));}
    String next()throws IOException{
    while (st == null || !st.hasMoreElements()) {try{
    st = new StringTokenizer(br.readLine());}
    catch (IOException  e){ e.printStackTrace(); }}
    return st.nextToken(); } int nextInt() throws IOException{
    return Integer.parseInt(next());}
    long nextLong() throws IOException
    {return Long.parseLong(next());}
    double nextDouble()throws IOException { return Double.parseDouble(next()); }
    String nextLine() throws IOException{ String str = ""; try{
    str = br.readLine();} catch (IOException e){
    e.printStackTrace();} return str;}}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
}


import java.util.*;import java.io.*;import java.math.*;
public class GoodString
{
    public static void process()throws IOException
    {
        char[] ch = nln().toCharArray();
        int n = ch.length;
        int count = 0;
        int[] dp = new int[10];
        for(int i = 0; i < n; i++){
            int v = ch[i]-'0';
            dp[v]++;
        }
        for(int i : dp){
           // pn(i);
            count = Math.max(count, i);
        }
        int ans = n-count;
        count = 0;
        for(int i = 0; i < 10; i++){
            for(int j = 0; j < 10; j++){
                if(j == i)
                    continue;
                boolean f = false;
                for(int k = 0; k < n; k++){
                    if(ch[k]-'0' == i && f == false)
                        f = true;
                    if(ch[k]-'0' == j && f == true){
                        count++;
                        f = false;
                    }
                }
                ans = Math.min(ans, n-2*count);
                count = 0;
            }
        }
        pn(ans);
    }

    static AnotherReader sc;
    static PrintWriter out;
    public static void main(String[]args)throws IOException
    {
        boolean oj = System.getProperty("ONLINE_JUDGE") != null;
        if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);}
        else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");}
        long s = System.currentTimeMillis();
        int t=1;
        t=ni();
        while(t-->0) {process();}
        out.flush();
        System.err.println(System.currentTimeMillis()-s+"ms");
        out.close();
    }

    static void pn(Object o){out.println(o);}
    static void p(Object o){out.print(o);}
    static void pni(Object o){out.println(o);out.flush();}
    static int ni()throws IOException{return sc.nextInt();}
    static long nl()throws IOException{return sc.nextLong();}
    static double nd()throws IOException{return sc.nextDouble();}
    static String nln()throws IOException{return sc.nextLine();}
    static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;}
    static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;}
    static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);}
    static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);}
    static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));}
    static long power(long k, long c, long mod){
        long y = 1;
        while(c > 0){
            if(c%2 == 1)
                y = y * k % mod;
            c = c/2;
            k = k * k % mod;
        }
        return y;
    }

/////////////////////////////////////////////////////////////////////////////////////////////////////////

    static class AnotherReader{BufferedReader br; StringTokenizer st;
    AnotherReader()throws FileNotFoundException{
    br=new BufferedReader(new InputStreamReader(System.in));}
    AnotherReader(int a)throws FileNotFoundException{
    br = new BufferedReader(new FileReader("input.txt"));}
    String next()throws IOException{
    while (st == null || !st.hasMoreElements()) {try{
    st = new StringTokenizer(br.readLine());}
    catch (IOException  e){ e.printStackTrace(); }}
    return st.nextToken(); } int nextInt() throws IOException{
    return Integer.parseInt(next());}
    long nextLong() throws IOException
    {return Long.parseLong(next());}
    double nextDouble()throws IOException { return Double.parseDouble(next()); }
    String nextLine() throws IOException{ String str = ""; try{
    str = br.readLine();} catch (IOException e){
    e.printStackTrace();} return str;}}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
}


import java.util.Scanner;

public class er92c {
	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		int t=scan.nextInt();
		for(int tt=0;tt<t;tt++) {
			char[] a=scan.next().toCharArray();
			int n=a.length;

			int res=Integer.MAX_VALUE;

			for(char i='0';i<='9';i++) {
				for(char j='0';j<='9';j++) {
					char cur=i;
					int len=0;
					for(int x=0;x<n;x++) {
						if(a[x]==cur) {
							len++;
							if(cur==i) cur=j;
							else cur=i;
						}
					}
					if(i!=j) len-=len%2;
					res=Math.min(res,n-len);
				}
			}
			System.out.println(res);
		}
	}
}


import javax.xml.crypto.Data;
import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        InputReader sc = new InputReader(System.in);
        PrintWriter pw = new PrintWriter(System.out);
        Random gen = new Random();
        int test = sc.nextInt();
        while(test-->0) {

            //int n = sc.nextInt();

            char[] a=sc.readString().toCharArray();
            int[] counts=new int[10];
            for (char c:a) counts[c-'0']++;
            Arrays.sort(counts);
            int maxLength=counts[counts.length-1];

            for (int first=0; first<10; first++) {
                for (int second=0; second<10; second++) {
                    int len=0;
                    for (char c:a) {
                        if (len%2==0) {
                            if (c-'0'==first) len++;
                        }
                        else {
                            if (c-'0'==second) len++;
                        }
                    }
                    len-=len%2;
                    maxLength=Math.max(maxLength, len);
                }
            }
            System.out.println(a.length-maxLength);
        }
        pw.close();

    }

    static class Data implements Comparable<Data>{
        int x, a;

        public Data (int m, int n) {
            x = m;
            a = n;
        }
        @Override
        public int compareTo(Data o) {
            return a - o.a;
        }
    }

    static class InputReader {

        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar, snumChars;

        public InputReader(InputStream st) {
            this.stream = st;
        }

        public int read() {
            if (snumChars == -1)
                throw new InputMismatchException();
            if (curChar >= snumChars) {
                curChar = 0;
                try {
                    snumChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (snumChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n) {
            int [] a = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = nextInt();
            }
            return a;
        }

        public static int[] shuffle(int[] a, Random gen)
        { for(int i = 0, n = a.length;i < n;i++)
        { int ind = gen.nextInt(n-i)+i;
            int d = a[i];
            a[i] = a[ind];
            a[ind] = d;

        }
            return a;
        }

        public String readString() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public String nextLine() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isEndOfLine(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }

    }

}


import java.io.*;
import java.util.*;

public class C {
    public static void main(String args[]) throws Exception {
        BufferedReader bu = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(bu.readLine());
        StringBuilder sb = new StringBuilder();
        while (t-- > 0) {
            String inp = bu.readLine();
            int res = 0;
            for (int a = '0'; a <= '9'; a++) {
                for (int b = '0'; b <= '9'; b++) {
                    int cnt = 0;
                    char c = (char) a, d = (char) b;
                    for (char ch:inp.toCharArray()){
                        if (ch==c) {
                            cnt++;
                            c = (char) (c^d^(d=c));
                        }
                    }
                    if (a==b)
                        res = Math.max(res, cnt);
                    else
                        res = Math.max(res, cnt&~1);
                }
            }
            sb.append(inp.length()-res+"\n");
        }
        System.out.print(sb);
    }
}


import java.io.*;
import java.util.*;

public class C {
    public static void main(String args[]) throws Exception {
        BufferedReader bu = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(bu.readLine());
        StringBuilder sb = new StringBuilder();
        while (t-- > 0) {
            String inp = bu.readLine();
            if ((inp.substring(1)+inp.charAt(0)).equals(inp.charAt(inp.length()-1)+inp.substring(0, inp.length()-1)))
                sb.append("0\n");
            else{
                HashMap<Character, Integer>freq = new HashMap<>();
                for (int pos = 0; pos < inp.length(); pos++) {
                    freq.put(inp.charAt(pos), freq.getOrDefault(inp.charAt(pos), 0)+1);
                }
                ArrayList<Character> keys = new ArrayList<>(freq.keySet());
                keys.sort((c1, c2)->-freq.get(c2)+freq.get(c1));
                if (keys.size() == inp.length())
                    sb.append(inp.length()-2+"\n");
                else {
                    long ans = 0;
                    for (int pos = 0; pos < keys.size()-1; pos++) {
                        ans+= freq.get(keys.get(pos));
                    }
                    sb.append(ans+"\n");
                }
            }
        }
        System.out.print(sb);
    }
}


import java.io.*;
import java.util.*;

public class C {
    public static void main(String args[]) throws Exception {
        BufferedReader bu = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(bu.readLine());
        StringBuilder sb = new StringBuilder();
        while (t-- > 0) {
            String inp = bu.readLine();
            int lenOfFinalString = 0;
            for (int a = 0; a < 9; a++) {
                for (int b = 0; b < 9; b++) {
                    char c = (char)('0'+a), d = (char) ('0'+b);
                    int turn = 1, cnt = 0;
                    for (char ch:inp.toCharArray()){
                        if (turn==1 && ch==c)cnt++;
                        else if (turn==2 && ch==d)cnt++;
                        turn ^= 1^2;
                    }
                    if (a==b)
                        lenOfFinalString = Math.max(lenOfFinalString, cnt);
                    else
                        lenOfFinalString = Math.max(lenOfFinalString, cnt&~1);
                }
            }
            sb.append(inp.length()-lenOfFinalString+"\n");
        }
        System.out.print(sb);
    }
}


import java.io.*;
import java.util.*;

public class C {
    public static void main(String args[]) throws Exception {
        BufferedReader bu = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(bu.readLine());
        StringBuilder sb = new StringBuilder();
        while (t-- > 0) {
            String inp = bu.readLine();
            int lenOfFinalString = 0;
            for (int a = '0'; a <= '9'; a++) {
                for (int b = '0'; b <= '9'; b++) {
                    int turn = 1, cnt = 0;
                    for (char ch:inp.toCharArray()){
                        if (turn==1 && ch==a)cnt++;
                        else if (turn==2 && ch==b)cnt++;
                        turn ^= 1^2;
                    }
                    if (a==b)
                        lenOfFinalString = Math.max(lenOfFinalString, cnt);
                    else
                        lenOfFinalString = Math.max(lenOfFinalString, cnt&~1);
                }
            }
            sb.append(inp.length()-lenOfFinalString+"\n");
        }
        System.out.print(sb);
    }
}


import java.io.*;
import java.util.*;

public class C {
    public static void main(String args[]) throws Exception {
        BufferedReader bu = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(bu.readLine());
        StringBuilder sb = new StringBuilder();
        while (t-- > 0) {
            String S = bu.readLine();
            int ans = 0;
            for (char a = '0'; a <= '9'; a++) {
                for (char b = '0'; b <= '9'; b++) {
                    char x = a, y = b;
                    int cnt = 0;
                    for (char c : S.toCharArray()) {
                        if (c == x) {
                            cnt++;
                            x = (char) (x^y^(y=x));
                        }
                    }
                    if (a == b) ans = Math.max(ans, cnt);
                    else ans = Math.max(ans, cnt&~1);
                }
            }
            sb.append(S.length()-ans+"\n");
        }
        System.out.print(sb);
    }
}


import java.util.*;

public class B {

    static int solve(char c[], int n, int x, int y) {
        int ans = 0;
        for (int i = 0; i < n; i++) {
            int cur = c[i] - '0';
            if (cur == x) {
                ans++;
                int temp = x;
                x = y;
                y = temp;
            }
        }
        if (x != y && ans % 2 != 0) {
            --ans;
        }
        return ans;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();
        int testCases = sc.nextInt();
        sc.nextLine();
        for (int t = 0; t < testCases; t++) {
            String str = sc.nextLine();
            char c[] = str.toCharArray();
            int n = c.length;
            if (n == 1) {
                sb.append("0").append("\n");
                continue;
            }
            HashSet<Integer> set = new HashSet<>();
            for (int i = 0; i < n; i++) {
                int cur = c[i] - '0';
                if (!set.contains(cur)) {
                    set.add(cur);
                }
            }
            if (set.size() == 1) {
                sb.append("0").append("\n");
                continue;
            }
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 10; j++) {
                    max = Math.max(max, solve(c, n, i, j));
                }
            }
            sb.append(n - max).append("\n");
        }
        System.out.print(sb);
    }
}


import java.io.*;
import java.util.*;
import java.math.*;
import java.util.regex.*;

 public class Main    {
    static class cell{
        int a, b;
        public cell(int x, int y) {
            a = x;
            b = y;
        }
    }
   static class Pair implements Comparable<Pair>{

       int a;
       int b;
//       int ind;
//       public Pair(int x, long y) {a = x;b=y;}
       public Pair(int x, int y) {a = x;b=y;}
//       public Pair(int x,int y, int z){a=x;b=y;ind = z;}
       public int compareTo(Pair p){
           if(a == p.a)
               return b - p.b;
           else
               return a - p.a;
       }
//        @Override
//        public int hashCode() {
//            final int prime = 31;
//            int result = 1;
//            result = prime * result + a;
//            result = prime * result + b;
//
//            return result;
//        }
//        @Override
//        public boolean equals(Object obj) {
//            Pair cur = (Pair)obj;
//            if((a==cur.a && b==cur.b))return true;
//            return false;
//        }
 }

public static void main(String[] args) throws Exception {
   new Thread(null, null, "Anshum Gupta", 99999999) {
        public void run() {
            try {
                solve();
            } catch(Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }.start();
}
public static long gcd(long a,long b)
{
  if(a<b)
    return gcd(b,a);
  if(b==0)
    return a;
  return gcd(b,a%b);

}
static long lcm(int a,int b) {
  return  a*b / gcd(a,b);
}
static int[] z(char[]arr) {
    int l = 0, r = 0;
    int[]z = new int[n];
    for(int i=1; i<n; i++) {
        if(i > r) {
            l = r = i;
            while(r < n && arr[r-l] == arr[r])r++;
            z[i] = r-- - l;
        }else {
            int k = i - l;
            if(z[k] < r - i + l)z[i] = z[k];
            else {
                l = i;
                while(r < n && arr[r-l] == arr[r])r++;
                z[i] = r-- - l;
            }
        }
    }
    return z;
}
static long pow(long x,long y){
    if(y == 0)return 1;
    if(y==1)return x;
    long a = pow(x,y/2);
    a = (a*a)%mod;
    if(y%2==0){
        return a;
    }
    return (a*x)%mod;
}

static long[]fact,inv_fact;
static long my_inv(long a) {
    return pow(a,mod-2);
}
static long bin(int a,int b) {
    if(a < b || a<0 || b<0)return 0;
    return ((fact[a]*inv_fact[a-b])%mod * inv_fact[b])%mod;
}

static void make_facts() {
  fact=new long[mxN];
  inv_fact = new long[mxN];
  fact[0]=inv_fact[0]=1L;
  for(int i=1;i<mxN;i++) {
       fact[i] = (i*fact[i-1])%mod;
       inv_fact[i] = my_inv(fact[i]);
  }
}
static void lazy(int st, int e, int tn) {
    if(lazy[tn] != INF) {
        tree[tn] = Math.min(tree[tn], lazy[tn]);
        if(st != e) {
            lazy[2*tn] = Math.min(lazy[2*tn], lazy[tn]);
            lazy[2*tn+1] = Math.min(lazy[2*tn+1], lazy[tn]);
        }
        lazy[tn] = INF;
    }
}
static void update(int ind, int val, int st, int e, int tn) {
    if(st == e) {
        tree[tn] = val;
        return;
    }
    int mid = (st + e) >> 1;
      if(ind <= mid)
        update(ind, val, st, mid, 2*tn);
      else
        update(ind, val, mid+1, e, 2*tn+1);
    tree[tn] = Math.min(tree[2*tn], tree[2*tn+1]);
}
static int query(int l, int r, int st, int e, int tn) {
    if(st > r || e < l)return INF;

    if(st >= l && e <= r) {
        return tree[tn];
    }

    int mid = (st + e) >> 1;
    int x = query(l, r, st, mid, 2 * tn);
    int y = query(l, r, mid+1, e, 2 * tn + 1);
    return Math.min(x, y);
}
static final long mxx = (long)(3e18+5);
static final int mxN = (int)(1e5);
static final int mxV = (int)(1e5+5);
static long mod = (long)(1e9+7); //998244353;//
static int[]tree, lazy;
static final int INF = (int)2e9+5;
static boolean[]vis;
static ArrayList<ArrayList<Integer>> adj;
static int n, m, q, t, k, p, z;
static int[]a, c, pre;
static char[]arr;
static int[][]dp;
static boolean pos(int val) {
	assert(val % 2 == 0);
	int[]cnt = new int[10];
	int[]consec = new int[10];
	for(int i=0; i<n; i++) {
		cnt[arr[i]-'0']++;
	}
	for(int i=0; i<n; ) {
		int j = i+1;
		while(j < n && arr[j] == arr[i]) {
			consec[arr[i]-'0']++;
			j++;
		}
		i = j;
	}
	for(int i=0; i<10; i++) {
		for(int j=0; j<10; j++) {

		}
	}
	int x = 0;
	for(int i=0; i<10; i++) {
		if(cnt[i] >= val)return true;
		cnt[i] -= consec[i];
		if(cnt[i] >= val / 2) {
			x++;
		}
	}
	return (x >= 2);
}
static int mv() {
	int[]cnt = new int[10];
	int[]consec = new int[10];
	for(int i=0; i<n; i++) {
		cnt[arr[i]-'0']++;
	}
	for(int i=0; i<n; ) {
		int j = i+1;
		while(j < n && arr[j] == arr[i]) {
			consec[arr[i]-'0']++;
			j++;
		}
		i = j;
	}
	int res = 0;
	for(int i=0; i<10; i++)res = Math.max(res, cnt[i]);
	int v1 = 0, v2 =0;
	for(int i=0; i<10;i++) {
		cnt[i] -= consec[i];
		if(cnt[i] > v1) {
			v2 = v1;
			v1 = cnt[i];
		}
		else if(cnt[i] > v2) {
			v2 = cnt[i];
		}
	}
	res = Math.max(res, Math.min(v1, v2) * 2);
	return res;
}
public static void solve() throws Exception {
   // solve the problem here
   MyScanner s = new MyScanner();
        out = new PrintWriter(new BufferedOutputStream(System.out), true);
        int tc = s.nextInt();

        while(tc-->0){
        	arr = s.next().toCharArray();
        	n = arr.length;
        	int mv = mv();
        	out.println(n - mv);
//        	int lo = 1, hi = n/2, ans = lo;
//        	while(lo <= hi) {
//        		int mid = (lo + hi) >> 1;
//        		if(pos(mid*2)) {
//        			lo = mid + 1;
//        			ans = mid;
//        		}else {
//        			hi = mid - 1;
//        		}
//        	}
//        	out.println(n - ans * 2);
        }

        out.flush();
}

    //-----------PrintWriter for faster output---------------------------------
    public static PrintWriter out;

    //-----------MyScanner class for faster input----------
    public static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        public MyScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() { return Integer.parseInt(next()); }
        long nextLong() { return Long.parseLong(next()); }
        double nextDouble() { return Double.parseDouble(next()); }

        String nextLine(){
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    //--------------------------------------------------------
}


import java.io.*;
import java.util.*;
import java.math.*;
import java.util.regex.*;

 public class Main    {
    static class cell{
        int a, b;
        public cell(int x, int y) {
            a = x;
            b = y;
        }
    }
   static class Pair implements Comparable<Pair>{

       int a;
       int b;
//       int ind;
//       public Pair(int x, long y) {a = x;b=y;}
       public Pair(int x, int y) {a = x;b=y;}
//       public Pair(int x,int y, int z){a=x;b=y;ind = z;}
       public int compareTo(Pair p){
           if(a == p.a)
               return b - p.b;
           else
               return a - p.a;
       }
//        @Override
//        public int hashCode() {
//            final int prime = 31;
//            int result = 1;
//            result = prime * result + a;
//            result = prime * result + b;
//
//            return result;
//        }
//        @Override
//        public boolean equals(Object obj) {
//            Pair cur = (Pair)obj;
//            if((a==cur.a && b==cur.b))return true;
//            return false;
//        }
 }

public static void main(String[] args) throws Exception {
   new Thread(null, null, "Anshum Gupta", 99999999) {
        public void run() {
            try {
                solve();
            } catch(Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }.start();
}
public static long gcd(long a,long b)
{
  if(a<b)
    return gcd(b,a);
  if(b==0)
    return a;
  return gcd(b,a%b);

}
static long lcm(int a,int b) {
  return  a*b / gcd(a,b);
}
static int[] z(char[]arr) {
    int l = 0, r = 0;
    int[]z = new int[n];
    for(int i=1; i<n; i++) {
        if(i > r) {
            l = r = i;
            while(r < n && arr[r-l] == arr[r])r++;
            z[i] = r-- - l;
        }else {
            int k = i - l;
            if(z[k] < r - i + l)z[i] = z[k];
            else {
                l = i;
                while(r < n && arr[r-l] == arr[r])r++;
                z[i] = r-- - l;
            }
        }
    }
    return z;
}
static long pow(long x,long y){
    if(y == 0)return 1;
    if(y==1)return x;
    long a = pow(x,y/2);
    a = (a*a)%mod;
    if(y%2==0){
        return a;
    }
    return (a*x)%mod;
}

static long[]fact,inv_fact;
static long my_inv(long a) {
    return pow(a,mod-2);
}
static long bin(int a,int b) {
    if(a < b || a<0 || b<0)return 0;
    return ((fact[a]*inv_fact[a-b])%mod * inv_fact[b])%mod;
}

static void make_facts() {
  fact=new long[mxN];
  inv_fact = new long[mxN];
  fact[0]=inv_fact[0]=1L;
  for(int i=1;i<mxN;i++) {
       fact[i] = (i*fact[i-1])%mod;
       inv_fact[i] = my_inv(fact[i]);
  }
}
static void lazy(int st, int e, int tn) {
    if(lazy[tn] != INF) {
        tree[tn] = Math.min(tree[tn], lazy[tn]);
        if(st != e) {
            lazy[2*tn] = Math.min(lazy[2*tn], lazy[tn]);
            lazy[2*tn+1] = Math.min(lazy[2*tn+1], lazy[tn]);
        }
        lazy[tn] = INF;
    }
}
static void update(int ind, int val, int st, int e, int tn) {
    if(st == e) {
        tree[tn] = val;
        return;
    }
    int mid = (st + e) >> 1;
      if(ind <= mid)
        update(ind, val, st, mid, 2*tn);
      else
        update(ind, val, mid+1, e, 2*tn+1);
    tree[tn] = Math.min(tree[2*tn], tree[2*tn+1]);
}
static int query(int l, int r, int st, int e, int tn) {
    if(st > r || e < l)return INF;

    if(st >= l && e <= r) {
        return tree[tn];
    }

    int mid = (st + e) >> 1;
    int x = query(l, r, st, mid, 2 * tn);
    int y = query(l, r, mid+1, e, 2 * tn + 1);
    return Math.min(x, y);
}
static final long mxx = (long)(3e18+5);
static final int mxN = (int)(1e5);
static final int mxV = (int)(1e5+5);
static long mod = (long)(1e9+7); //998244353;//
static int[]tree, lazy;
static final int INF = (int)2e9+5;
static boolean[]vis;
static ArrayList<ArrayList<Integer>> adj;
static int n, m, q, t, k, p, z;
static int[]a, c, pre;
static char[]arr;
static int[][]dp;
static int one(int x) {
	int ans = 0;
	for(int i=0; i<n; i++) {
		if( (arr[i] - '0') == x ) {
			ans++;
		}
	}
	return ans;
}
static int two(int x, int y) {
	int ans = 0;
	for(int i=0; i<n; i++) {
		if(ans % 2 == 0) {
			if( (arr[i] - '0') == x)
				ans++;
		}
		else {
			if( (arr[i] - '0') == y)
				ans++;
		}
	}
	if(ans % 2 != 0)ans--;
	return ans;
}
public static void solve() throws Exception {
   // solve the problem here
   MyScanner s = new MyScanner();
        out = new PrintWriter(new BufferedOutputStream(System.out), true);
        int tc = s.nextInt();

        while(tc-->0){
        	arr = s.next().toCharArray();
        	n = arr.length;
        	int ans = 0;
        	for(int i=0; i<10; i++) {
        		ans = Math.max(ans, one(i));
        	}
        	for(int i=0; i<10; i++) {
        		for(int j=0; j<10; j++) {
        			if(i != j) {
        				ans = Math.max(ans, two(i, j));
        			}
        		}
        	}
        	out.println(n - ans);
        }

        out.flush();
}

    //-----------PrintWriter for faster output---------------------------------
    public static PrintWriter out;

    //-----------MyScanner class for faster input----------
    public static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        public MyScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() { return Integer.parseInt(next()); }
        long nextLong() { return Long.parseLong(next()); }
        double nextDouble() { return Double.parseDouble(next()); }

        String nextLine(){
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    //--------------------------------------------------------
}


import java.io.*;
import java.util.*;
import java.math.*;
import java.util.regex.*;

 public class Main    {
    static class cell{
        int a, b;
        public cell(int x, int y) {
            a = x;
            b = y;
        }
    }
   static class Pair implements Comparable<Pair>{

       int a;
       int b;
//       int ind;
//       public Pair(int x, long y) {a = x;b=y;}
       public Pair(int x, int y) {a = x;b=y;}
//       public Pair(int x,int y, int z){a=x;b=y;ind = z;}
       public int compareTo(Pair p){
           if(a == p.a)
               return b - p.b;
           else
               return a - p.a;
       }
//        @Override
//        public int hashCode() {
//            final int prime = 31;
//            int result = 1;
//            result = prime * result + a;
//            result = prime * result + b;
//
//            return result;
//        }
//        @Override
//        public boolean equals(Object obj) {
//            Pair cur = (Pair)obj;
//            if((a==cur.a && b==cur.b))return true;
//            return false;
//        }
 }

public static void main(String[] args) throws Exception {
   new Thread(null, null, "Anshum Gupta", 99999999) {
        public void run() {
            try {
                solve();
            } catch(Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }.start();
}
public static long gcd(long a,long b)
{
  if(a<b)
    return gcd(b,a);
  if(b==0)
    return a;
  return gcd(b,a%b);

}
static long lcm(int a,int b) {
  return  a*b / gcd(a,b);
}
static int[] z(char[]arr) {
    int l = 0, r = 0;
    int[]z = new int[n];
    for(int i=1; i<n; i++) {
        if(i > r) {
            l = r = i;
            while(r < n && arr[r-l] == arr[r])r++;
            z[i] = r-- - l;
        }else {
            int k = i - l;
            if(z[k] < r - i + l)z[i] = z[k];
            else {
                l = i;
                while(r < n && arr[r-l] == arr[r])r++;
                z[i] = r-- - l;
            }
        }
    }
    return z;
}
static long pow(long x,long y){
    if(y == 0)return 1;
    if(y==1)return x;
    long a = pow(x,y/2);
    a = (a*a)%mod;
    if(y%2==0){
        return a;
    }
    return (a*x)%mod;
}

static long[]fact,inv_fact;
static long my_inv(long a) {
    return pow(a,mod-2);
}
static long bin(int a,int b) {
    if(a < b || a<0 || b<0)return 0;
    return ((fact[a]*inv_fact[a-b])%mod * inv_fact[b])%mod;
}

static void make_facts() {
  fact=new long[mxN];
  inv_fact = new long[mxN];
  fact[0]=inv_fact[0]=1L;
  for(int i=1;i<mxN;i++) {
       fact[i] = (i*fact[i-1])%mod;
       inv_fact[i] = my_inv(fact[i]);
  }
}
static void lazy(int st, int e, int tn) {
    if(lazy[tn] != INF) {
        tree[tn] = Math.min(tree[tn], lazy[tn]);
        if(st != e) {
            lazy[2*tn] = Math.min(lazy[2*tn], lazy[tn]);
            lazy[2*tn+1] = Math.min(lazy[2*tn+1], lazy[tn]);
        }
        lazy[tn] = INF;
    }
}
static void update(int ind, int val, int st, int e, int tn) {
    if(st == e) {
        tree[tn] = val;
        return;
    }
    int mid = (st + e) >> 1;
      if(ind <= mid)
        update(ind, val, st, mid, 2*tn);
      else
        update(ind, val, mid+1, e, 2*tn+1);
    tree[tn] = Math.min(tree[2*tn], tree[2*tn+1]);
}
static int query(int l, int r, int st, int e, int tn) {
    if(st > r || e < l)return INF;

    if(st >= l && e <= r) {
        return tree[tn];
    }

    int mid = (st + e) >> 1;
    int x = query(l, r, st, mid, 2 * tn);
    int y = query(l, r, mid+1, e, 2 * tn + 1);
    return Math.min(x, y);
}
static final long mxx = (long)(3e18+5);
static final int mxN = (int)(1e5);
static final int mxV = (int)(1e5+5);
static long mod = (long)(1e9+7); //998244353;//
static int[]tree, lazy;
static final int INF = (int)2e9+5;
static boolean[]vis;
static ArrayList<ArrayList<Integer>> adj;
static int n, m, q, t, k, p, z;
static int[]a, c, pre;
static char[]arr;
static int[][]dp;
static boolean pos(int val) {
	assert(val % 2 == 0);
	int[]cnt = new int[10];
	int[]consec = new int[10];
	for(int i=0; i<n; i++) {
		cnt[arr[i]-'0']++;
	}
	for(int i=0; i<n; ) {
		int j = i+1;
		while(j < n && arr[j] == arr[i]) {
			consec[arr[i]-'0']++;
			j++;
		}
		i = j;
	}
	for(int i=0; i<10; i++) {
		for(int j=0; j<10; j++) {

		}
	}
	int x = 0;
	for(int i=0; i<10; i++) {
		if(cnt[i] >= val)return true;
		cnt[i] -= consec[i];
		if(cnt[i] >= val / 2) {
			x++;
		}
	}
	return (x >= 2);
}
static int mv() {
	int[]cnt = new int[10];
	int[]consec = new int[10];
	for(int i=0; i<n; i++) {
		cnt[arr[i]-'0']++;
	}
	for(int i=0; i<n; ) {
		int j = i+1;
		while(j < n && arr[j] == arr[i]) {
			consec[arr[i]-'0']++;
			j++;
		}
		i = j;
	}
	int res = 0;
	for(int i=0; i<10; i++)res = Math.max(res, cnt[i]);
	int v1 = 0, v2 =0;
	for(int i=0; i<10;i++) {
		cnt[i] -= consec[i];
		if(cnt[i] > v1) {
			v2 = v1;
			v1 = cnt[i];
		}
		else if(cnt[i] > v2) {
			v2 = cnt[i];
		}
	}
	return Math.min(v1, v2) * 2;
}
public static void solve() throws Exception {
   // solve the problem here
   MyScanner s = new MyScanner();
        out = new PrintWriter(new BufferedOutputStream(System.out), true);
        int tc = s.nextInt();

        while(tc-->0){
        	arr = s.next().toCharArray();
        	n = arr.length;
        	int mv = mv();
        	out.println(n - mv);
//        	int lo = 1, hi = n/2, ans = lo;
//        	while(lo <= hi) {
//        		int mid = (lo + hi) >> 1;
//        		if(pos(mid*2)) {
//        			lo = mid + 1;
//        			ans = mid;
//        		}else {
//        			hi = mid - 1;
//        		}
//        	}
//        	out.println(n - ans * 2);
        }

        out.flush();
}

    //-----------PrintWriter for faster output---------------------------------
    public static PrintWriter out;

    //-----------MyScanner class for faster input----------
    public static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        public MyScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() { return Integer.parseInt(next()); }
        long nextLong() { return Long.parseLong(next()); }
        double nextDouble() { return Double.parseDouble(next()); }

        String nextLine(){
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    //--------------------------------------------------------
}


import java.io.*;
import java.util.*;
import java.math.*;
import java.util.regex.*;

 public class Main    {
    static class cell{
        int a, b;
        public cell(int x, int y) {
            a = x;
            b = y;
        }
    }
   static class Pair implements Comparable<Pair>{

       int a;
       int b;
//       int ind;
//       public Pair(int x, long y) {a = x;b=y;}
       public Pair(int x, int y) {a = x;b=y;}
//       public Pair(int x,int y, int z){a=x;b=y;ind = z;}
       public int compareTo(Pair p){
           if(a == p.a)
               return b - p.b;
           else
               return a - p.a;
       }
//        @Override
//        public int hashCode() {
//            final int prime = 31;
//            int result = 1;
//            result = prime * result + a;
//            result = prime * result + b;
//
//            return result;
//        }
//        @Override
//        public boolean equals(Object obj) {
//            Pair cur = (Pair)obj;
//            if((a==cur.a && b==cur.b))return true;
//            return false;
//        }
 }

public static void main(String[] args) throws Exception {
   new Thread(null, null, "Anshum Gupta", 99999999) {
        public void run() {
            try {
                solve();
            } catch(Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }.start();
}
public static long gcd(long a,long b)
{
  if(a<b)
    return gcd(b,a);
  if(b==0)
    return a;
  return gcd(b,a%b);

}
static long lcm(int a,int b) {
  return  a*b / gcd(a,b);
}
static int[] z(char[]arr) {
    int l = 0, r = 0;
    int[]z = new int[n];
    for(int i=1; i<n; i++) {
        if(i > r) {
            l = r = i;
            while(r < n && arr[r-l] == arr[r])r++;
            z[i] = r-- - l;
        }else {
            int k = i - l;
            if(z[k] < r - i + l)z[i] = z[k];
            else {
                l = i;
                while(r < n && arr[r-l] == arr[r])r++;
                z[i] = r-- - l;
            }
        }
    }
    return z;
}
static long pow(long x,long y){
    if(y == 0)return 1;
    if(y==1)return x;
    long a = pow(x,y/2);
    a = (a*a)%mod;
    if(y%2==0){
        return a;
    }
    return (a*x)%mod;
}

static long[]fact,inv_fact;
static long my_inv(long a) {
    return pow(a,mod-2);
}
static long bin(int a,int b) {
    if(a < b || a<0 || b<0)return 0;
    return ((fact[a]*inv_fact[a-b])%mod * inv_fact[b])%mod;
}

static void make_facts() {
  fact=new long[mxN];
  inv_fact = new long[mxN];
  fact[0]=inv_fact[0]=1L;
  for(int i=1;i<mxN;i++) {
       fact[i] = (i*fact[i-1])%mod;
       inv_fact[i] = my_inv(fact[i]);
  }
}
static void lazy(int st, int e, int tn) {
    if(lazy[tn] != INF) {
        tree[tn] = Math.min(tree[tn], lazy[tn]);
        if(st != e) {
            lazy[2*tn] = Math.min(lazy[2*tn], lazy[tn]);
            lazy[2*tn+1] = Math.min(lazy[2*tn+1], lazy[tn]);
        }
        lazy[tn] = INF;
    }
}
static void update(int ind, int val, int st, int e, int tn) {
    if(st == e) {
        tree[tn] = val;
        return;
    }
    int mid = (st + e) >> 1;
      if(ind <= mid)
        update(ind, val, st, mid, 2*tn);
      else
        update(ind, val, mid+1, e, 2*tn+1);
    tree[tn] = Math.min(tree[2*tn], tree[2*tn+1]);
}
static int query(int l, int r, int st, int e, int tn) {
    if(st > r || e < l)return INF;

    if(st >= l && e <= r) {
        return tree[tn];
    }

    int mid = (st + e) >> 1;
    int x = query(l, r, st, mid, 2 * tn);
    int y = query(l, r, mid+1, e, 2 * tn + 1);
    return Math.min(x, y);
}
static final long mxx = (long)(3e18+5);
static final int mxN = (int)(1e5);
static final int mxV = (int)(1e5+5);
static long mod = (long)(1e9+7); //998244353;//
static int[]tree, lazy;
static final int INF = (int)2e9+5;
static boolean[]vis;
static ArrayList<ArrayList<Integer>> adj;
static int n, m, q, t, k, p, z;
static int[]a, c, pre;
static char[]arr;
static int[][]dp;
static boolean pos(int val) {
	assert(val % 2 == 0);
	int[]cnt = new int[10];
	int[]consec = new int[10];
	for(int i=0; i<n; i++) {
		cnt[arr[i]-'0']++;
	}
	for(int i=0; i<n; ) {
		int j = i+1;
		while(j < n && arr[j] == arr[i]) {
			consec[arr[i]-'0']++;
			j++;
		}
		i = j;
	}
	int x = 0;
	for(int i=0; i<10; i++) {
		if(cnt[i] >= val)return true;
		cnt[i] -= consec[i];
		if(cnt[i] >= val / 2) {
			x++;
		}
	}
	return (x >= 2);
}
public static void solve() throws Exception {
   // solve the problem here
   MyScanner s = new MyScanner();
        out = new PrintWriter(new BufferedOutputStream(System.out), true);
        int tc = s.nextInt();

        while(tc-->0){
        	arr = s.next().toCharArray();
        	n = arr.length;
        	int lo = 1, hi = n/2, ans = lo;
//        	if(n % 2 == 0 && pos(n)) {
//        		out.println("0");
//        		continue;
//        	}
        	while(lo <= hi) {
        		int mid = (lo + hi) >> 1;
        		if(pos(mid*2)) {
        			lo = mid + 1;
        			ans = mid;
        		}else {
        			hi = mid - 1;
        		}
        	}
        	out.println(n - ans * 2);
        }

        out.flush();
}

    //-----------PrintWriter for faster output---------------------------------
    public static PrintWriter out;

    //-----------MyScanner class for faster input----------
    public static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        public MyScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() { return Integer.parseInt(next()); }
        long nextLong() { return Long.parseLong(next()); }
        double nextDouble() { return Double.parseDouble(next()); }

        String nextLine(){
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    //--------------------------------------------------------
}


import java.util.*;
import java.io.*;

public final class Codechef {
	static void swap(int[] a, int i, int j) {
		int tmp=a[i];
		a[i]=a[j];
		a[j]=tmp;
	}
	static int zzis(int arr[], int n)
	{
	    /*las[i][0] = Length of the longest
	        alternating subsequence ending at
	        index i and last element is
	        greater than its previous element
	    las[i][1] = Length of the longest
	        alternating subsequence ending at
	        index i and last element is
	        smaller than its previous
	        element */
	    int las[][] = new int[n][2];

	    /* Initialize all values from 1 */
	    for (int i = 0; i < n; i++)
	        las[i][0] = las[i][1] = 1;

	    int res = 1; // Initialize result

	    /* Compute values in bottom up manner */
	    for (int i = 1; i < n; i++)
	    {
	        // Consider all elements as
	        // previous of arr[i]
	        for (int j = 0; j < i; j++)
	        {
	            // If arr[i] is greater, then
	            // check with las[j][1]
	            if (arr[j] < arr[i] &&
	                las[i][0] < las[j][1] + 1)
	                las[i][0] = las[j][1] + 1;

	            // If arr[i] is smaller, then
	            // check with las[j][0]
	            if( arr[j] > arr[i] &&
	              las[i][1] < las[j][0] + 1)
	                las[i][1] = las[j][0] + 1;
	        }

	        /* Pick maximum of both values at
	        index i */
	        if (res < Math.max(las[i][0], las[i][1]))
	            res = Math.max(las[i][0], las[i][1]);
	    }

	    return res;
	}
	static ArrayList<Integer>[] a;
	static int[] vis;
	public static void main(String[] args){
		Scanner sc=new Scanner(System.in);
		int t=sc.nextInt();
		while(t-->0) {
			//int n=sc.nextInt(), k=sc.nextInt(), z=sc.nextInt();
			String s=sc.next();
			char[] c=s.toCharArray();
			int[] a=new int[s.length()];
			int[] fq=new int[10];
			for(int i=0;i<s.length();i++) {
				a[i]=Character.digit(c[i], 10);
				fq[a[i]]++;
			}
			int ans=0;
			for(int i=0;i<10;i++) ans=Math.max(ans, fq[i]);
			ans=Math.max(a.length-ans, a.length-zzis(a, a.length));
			if(ans==0) ans=a.length-2;
			else if(zzis(a, a.length)==a.length) ans=0;
			else if(ans==a.length-1) ans--;
			System.out.println(ans);
		}
  }

  static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }

}


import java.util.*;
import java.io.*;

public final class Codechef {
	static void swap(int[] a, int i, int j) {
		int tmp=a[i];
		a[i]=a[j];
		a[j]=tmp;
	}
	static ArrayList<Integer>[] a;
	static int[] vis;
	public static void main(String[] args){
		Scanner sc=new Scanner(System.in);
		int t=sc.nextInt();
		while(t-->0) {
			char[] c=sc.next().toCharArray();
			int n=c.length;
			int[] fq=new int[10];
			for(int i=0;i<n;i++) {
				fq[Character.digit(c[i], 10)]++;
			}
			int ans=0;
			for(int i=0;i<10;i++) ans=Math.max(ans, fq[i]);
			for(int i=0;i<10;i++) {
				for(int j=0;j<10;j++) {
					int tmp=0;boolean f=false;
					for(int k=0;k<n;k++) {
						int x=Character.digit(c[k], 10);
						if(x==i && !f) {
							tmp++;
							f=!f;
						}
						else if(x==j && f) {
							tmp++;
							f=!f;
						}
					}
					ans=Math.max(ans, f?tmp-1:tmp);
				}
			}
			System.out.println(n-ans);

		}
  }

  static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }

}


import java.io.*;
import java.util.*;

public class TestClass {

    static final class InputReader {
        private final InputStream stream;
        private final byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        private int read() throws IOException {
            if (curChar >= numChars) {
                curChar = 0;
                numChars = stream.read(buf);
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public final int readInt() throws IOException {
            return (int) readLong();
        }

        public final long readLong() throws IOException {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
                if (c == -1) throw new IOException();
            }
            boolean negative = false;
            if (c == '-') {
                negative = true;
                c = read();
            }
            long res = 0;
            do {
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return negative ? -res : res;
        }

        public final int[] readIntArray(int size) throws IOException {
            int[] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = readInt();
            }
            return array;
        }

        public final long[] readLongArray(int size) throws IOException {
            long[] array = new long[size];
            for (int i = 0; i < size; i++) {
                array[i] = readLong();
            }
            return array;
        }

        public final String readString() throws IOException {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.append((char) c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        private boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }
    }

    static long mulmod(long a, long b,
                       long mod) {
        long res = 0; // Initialize result
        a = a % mod;
        while (b > 0) {
            // If b is odd, add 'a' to result
            if (b % 2 == 1) {
                res = (res + a) % mod;
            }

            // Multiply 'a' with 2
            a = (a * 2) % mod;

            // Divide b by 2
            b /= 2;
        }

        // Return result
        return res % mod;
    }

    static long pow(long a, long b, long MOD) {
        long x = 1, y = a;
        while (b > 0) {
            if (b % 2 == 1) {
                x = (x * y);
                if (x > MOD) x %= MOD;
            }
            y = (y * y);
            if (y > MOD) y %= MOD;
            b /= 2;
        }
        return x;
    }

    static long[] f = new long[100011];

    static long InverseEuler(long n, long MOD) {
        return pow(n, MOD - 2, MOD);
    }

    static long C(int n, int r, long MOD) {

        return (f[n] * ((InverseEuler(f[r], MOD) * InverseEuler(f[n - r], MOD)) % MOD)) % MOD;
    }

    static int[] h = {0, 0, -1, 1};
    static int[] v = {1, -1, 0, 0};

    static class Pair2 {
        public int from;
        int to;

        int pos;

        public Pair2(int from, int to, int pos) {
            this.from = from;
            this.to = to;
            this.pos = pos;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Pair2 pair2 = (Pair2) o;
            return from == pair2.from &&
                    to == pair2.to &&
                    pos == pair2.pos;
        }

        @Override
        public int hashCode() {
            return Objects.hash(from, to, pos);
        }
    }

    static long l[][] = new long[100011][6];

    static long compute_hash(String s) {
        int p = 31;
        int m = 1000000007;
        long hash_value = 0;
        long p_pow = 1;
        for (int i = 0; i < s.length(); ++i) {
            char c = s.charAt(i);
            hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m;
            p_pow = (p_pow * p) % m;
        }
        return hash_value;
    }

    public static class SegmentTree {
        int[][] tree;
        long[] sumtree;
        long[] count;
        int n;

        public SegmentTree(int[] nodes) {
            tree = new int[nodes.length * 4][31];
            sumtree = new long[nodes.length * 4];
            count = new long[nodes.length * 4];
            n = nodes.length;
            build(0, n - 1, 0, nodes);
        }

        private void build(int l, int r, int pos, int[] nodes) {
            if (l == r) {
                sumtree[pos] = nodes[l];
                boolean neg = false;
                if (nodes[l] < 0) {
                    neg = true;
                }
                count[pos] = 1;
                if (neg) {
                    count[pos] = -1;
                }
                for (int i = 0; i < 31; ++i) {
                    tree[pos][i] = (neg ? -1 : 1) * (((nodes[l] < 0 ? -1 * nodes[l] : nodes[l]) & (1 << i)) != 0 ? 1 : 0);
                }
                return;
            }
            int mid = (l + r) / 2;
            build(l, mid, 2 * pos + 1, nodes);
            build(mid + 1, r, 2 * pos + 2, nodes);
            sumtree[pos] = sumtree[2 * pos + 1] + sumtree[2 * pos + 2];
            count[pos] = count[2 * pos + 1] + count[2 * pos + 2];

            for (int i = 0; i < 31; ++i) {
                tree[pos][i] = tree[2 * pos + 1][i] + tree[2 * pos + 2][i];
            }
        }

        public long getSum(int l, int r) {
            return getSumUtil(0, n - 1, 0, l, r);
        }

        private long getSumUtil(int l, int r, int pos, int ql, int qr) {
            if (l > qr || r < ql) return 0L;
            if (l >= ql && r <= qr) {
                return sumtree[pos];
            }
            int mid = (l + r) >> 1;
            return getSumUtil(l, mid, 2 * pos + 1, ql, qr) + getSumUtil(mid + 1, r, 2 * pos + 2, ql, qr);
        }

        public long getCount(int l, int r) {
            return getCountUtil(0, n - 1, 0, l, r);
        }

        private long getCountUtil(int l, int r, int pos, int ql, int qr) {
            if (l > qr || r < ql) return 0L;
            if (l >= ql && r <= qr) {
                return count[pos];
            }
            int mid = (l + r) >> 1;
            return getCountUtil(l, mid, 2 * pos + 1, ql, qr) + getCountUtil(mid + 1, r, 2 * pos + 2, ql, qr);
        }

        public int[] getBitCount(int l, int r) {
            return getBitCountUtil(0, n - 1, 0, l, r);
        }

        private int[] getBitCountUtil(int l, int r, int pos, int ql, int qr) {
            if (l > qr || r < ql) return null;
            if (l >= ql && r <= qr) {
                int[] returs = new int[30];
                for (int i = 0; i < 30; ++i) {
                    returs[i] = tree[pos][i];
                }
                return returs;
            }
            int mid = (l + r) >> 1;

            int[] left = getBitCountUtil(l, mid, 2 * pos + 1, ql, qr);
            int[] right = getBitCountUtil(mid + 1, r, 2 * pos + 2, ql, qr);
            if (left == null) return right;
            if (right == null) return left;
            // int[] returs = new int[30];
            for (int i = 0; i < 30; ++i) {
                left[i] += right[i];
            }
            return left;
        }

    }

    static int counter = 0;
    static int[] In;
    static int[] Out;
    private static int[] flatten;
    private static int[][] lca;
    static long answer = 0;

    static int VISITED = 1;
    static int VISITING = 2;

    public static class MD {
        public class Pair {
            long val;
            int count;

            public Pair(long val, int count) {
                this.val = val;
                this.count = count;
            }
        }

        Deque<Pair> dq = new LinkedList<>();

        public void remove() {
            Pair first = dq.getFirst();
            dq.removeFirst();
            if (first.count != 1) {
                dq.addFirst(new Pair(first.val, first.count - 1));
            }
        }

        public void add(long val) {
            int count = 1;
            while (dq.size() != 0) {

                Pair last = dq.peekLast();
                if (last.val >= val) {
                    count += last.count;
                } else {
                    break;
                }
                dq.removeLast();

            }

            dq.addLast(new Pair(val, count));
        }

        public long get() {
            return dq.getFirst().val;
        }
    }

    public static void main(String[] args) throws Exception {
        //https://i...content-available-to-author-only...e.com/ebRGa6
//        File initialFile = new File("Madarchod.txt");
//        InputStream targetStream = new FileInputStream(initialFile);
//
//        InputReader in = new InputReader(targetStream);
//
//        PrintStream o = new PrintStream(new File("Madarchod2.txt"));
//
//        // Store current System.out before assigning a new value
//        PrintStream console = System.out;
//
//        // Assign o to output stream
//        System.setOut(o);

        InputReader in = new InputReader(System.in);

//        l[0][0] = 1;
//        for (int i = 1; i < 100008; i++) {
//            // Set every nCr = 1 where r = 0
//            l[i][0] = 1;
//            for (int j = 1; j < 5; j++) {
//
//                // Value for the current cell of Pascal's triangle
//                l[i][j] = (l[i - 1][j - 1] + l[i - 1][j]) % 1000000007;
//            }
//        }

        int t = in.readInt();

        for (int kk = 1; kk <= t; ++kk) {

            String s = in.readString();

            int[] count = new int[10];
            int[] compressedcount = new int[10];

            for (int i = 0; i < s.length(); ++i) {
                count[s.charAt(i) - '0'] ++;

            }
            for (int i = 0; i < s.length(); ) {
                char lookup = s.charAt(i);
                while (i <s.length() && lookup == s.charAt(i)) {
                    i++;
                }

                compressedcount[lookup - '0'] ++;
            }

            int maxEqu = 0;
            for (int i = 0; i < 10; ++i) {

                maxEqu = Math.max( maxEqu, count[i]);
            }

//            for (int i = 0; i < 10; ++i) {
//                System.out.println(compressedcount[i]);
//            }

            for (int i = 0; i < 10; ++i) {
                for (int j = 0; j < 10; ++j) {
                    if (i != j &&  compressedcount[i] > 0 && compressedcount[j]> 0) {
                        int min = Math.min(compressedcount[i], compressedcount[j]);

                        maxEqu = Math.max( maxEqu, 2* min);
                    }
                }
            }
            System.out.println(s.length() - maxEqu);

        }

    }

    private static void dfs(List<List<Integer>> tree, int node, int last, int[] size, int[] max, long[] sum, int[] color, List<Map<Integer, Integer>> colorCounts) {
        size[node] = 1;
        int biggest = -1;
        List<Integer> childs = new ArrayList<>();
        for (int i = 0; i < tree.get(node).size(); ++i) {
            int ntb = tree.get(node).get(i);

            if (ntb != last) {
                dfs(tree, ntb, node, size, max, sum, color, colorCounts);
                size[node] += size[ntb];
                childs.add(ntb);
                biggest = ntb;
            }
        }
        if (biggest != -1) {

//            System.out.println(node);
            long curBiggest = sum[biggest];
            if (colorCounts.get(biggest).getOrDefault(color[node], 0) == max[biggest]) {
                colorCounts.get(biggest).put(color[node], colorCounts.get(biggest).get(color[node]) + 1);
                curBiggest = color[node];
                max[biggest] = max[biggest] + 1;
            } else if (colorCounts.get(biggest).getOrDefault(color[node], 0) + 1 == max[biggest]) {
                colorCounts.get(biggest).put(color[node], colorCounts.get(biggest).getOrDefault(color[node], 0) + 1);
                curBiggest += color[node];

//                System.out.println("chiutadd");
            } else {
                colorCounts.get(biggest).put(color[node], colorCounts.get(biggest).getOrDefault(color[node], 0) + 1);
            }

//            System.out.println(max[biggest]);

            for (int i = 0; i < childs.size(); ++i) {
                if (childs.get(i) != biggest) {

                    int noder = childs.get(i);

                    for (Map.Entry<Integer, Integer> entry : colorCounts.get(noder).entrySet()) {
                        Integer noderColor = entry.getKey();
                        Integer counts = entry.getValue();
                        if (node == 3) {
//                            System.out.println(colorCounts.get(biggest).getOrDefault(noderColor, 0) + " " +  max[biggest] + " " + noderColor + " " + counts + " ");
                        }
                        if (colorCounts.get(biggest).getOrDefault(noderColor, 0) + counts > max[biggest]) {
                            if (node == 3) {
//                                System.out.println("A");
                            }
                            max[biggest] = colorCounts.get(biggest).getOrDefault(noderColor, 0) + counts;
                            colorCounts.get(biggest).put(noderColor, colorCounts.get(biggest).getOrDefault(noderColor, 0) + counts);
                            curBiggest = noderColor;
                        } else if (colorCounts.get(biggest).getOrDefault(noderColor, 0) + counts == max[biggest]) {
                            if (node == 3) {
//                                System.out.println("B");
                            }
                            colorCounts.get(biggest).put(noderColor, colorCounts.get(biggest).getOrDefault(noderColor, 0) + counts);
                            curBiggest += noderColor;
                        } else {
                            if (node == 3) {
//                                System.out.println("C");
                            }
                            colorCounts.get(biggest).put(noderColor, colorCounts.get(biggest).getOrDefault(noderColor, 0) + counts);
                        }
                    }

                }
            }

//            System.out.println(curBiggest);

            sum[node] = curBiggest;
            max[node] = max[biggest];
            colorCounts.set(node, colorCounts.get(biggest));
        } else {
            sum[node] = color[node];
            max[node] = 1;
            HashMap<Integer, Integer> e = new HashMap<>();
            e.put(color[node], 1);
            colorCounts.set(node, e);
        }
    }

    private static long solved(Long pos, TreeMap<Long, Long> mapPos, Map<Long, Long> dp) {
        if (!mapPos.containsKey(pos)) return 0;
        if (dp.containsKey(pos)) return dp.get(pos);
        long len = solved(pos + mapPos.get(pos), mapPos, dp) + mapPos.get(pos);
        dp.put(pos, len);
        return len;
    }

    private static long solve(int pos, int curK, int k, int[] arr, int m, long[][] dp) {
        System.out.println(pos);
        if (pos == arr.length) {
            if (curK == k) return 0;
            return -1000000000000L;
        }

        if (curK > k) return -1000000000000L;

        if (dp[pos][curK] != -1) return dp[pos][curK];

        long with = -1000000000000L;
        if (curK < k)
            with = solve(pos + 1, curK + 1, k, arr, m, dp) + arr[pos] * (((curK + 1) % m));
        long without = solve(pos + 1, curK, k, arr, m, dp);

        return dp[pos][curK] = Math.max(with, without);
    }

    static int countFreq(String pattern, String text) {
        int m = pattern.length();
        int n = text.length();
        int res = 0;

        for (int i = 0; i <= n - m; i++) {
            int j;
            for (j = 0; j < m; j++) {
                if (text.charAt(i + j) != pattern.charAt(j)) {
                    break;
                }
            }
            if (j == m) {
                res++;
                j = 0;
            }
        }
        return res;
    }

    private static void preprocess(int pos, int[][] pre, List<List<Integer>> tree, int[] traverse, int depth, int last, int[] tin, int[] tout) {
        tin[pos] = counter++;
        traverse[depth] = pos;

        for (int i = 0; depth - (1 << i) >= 0; ++i) {
            pre[pos][i] = traverse[depth - (1 << i)];
        }

        for (int i = 0; i < tree.get(pos).size(); ++i) {
            if (tree.get(pos).get(i) != last)
                preprocess(tree.get(pos).get(i), pre, tree, traverse, depth + 1, pos, tin, tout);
        }
        tout[pos] = counter++;
    }

    static int gcd(int a, int b) {

        while (b != 0) {
            int t = a;
            a = b;
            b = t % b;
        }
        return a;
    }

    static boolean submit = true;

    static void debug(String s) {
        if (!submit)
            System.out.println(s);
    }

    static void debug(int s) {
        if (!submit)
            System.out.println(s);
    }

}