// Travis Roe
// Solution to BHCSI Problem dilemma - 7/10/08

import java.util.*;
import java.io.*;

public class dilemma {

	public static void main(String[] args) throws IOException {
		
		Scanner scanner = new Scanner(new File("dilemma.in"));
		
		int N = scanner.nextInt();
		
		// Loop through the cases.
		for(int x = 0; x < N; x++){
			
			// Read in the input for this case.
			String letters = scanner.next();
			String word = scanner.next();
			
			// Store all the permutations of the scrabble tiles (5040 in all).
			ArrayList<String> perms = Permutations.getAllPerms(letters);
			
			// Sort them.
			Collections.sort(perms);
			
			// Look through the array, one string at a time until you find one
			// that comes after the dictionary word.
			
			// Note: This is fairly inefficient since a binary search would
			//       suffice, but in a contest situation, since we know that 
			//       no more than 5040 permutations will be searched, it will
			//		 generally work and is more simple to code.
			boolean success = false;
			for(String current : perms){
				if(current.compareTo(word) > 0){
					success = true;
					System.out.println(current);
					break;
				}
			}
			
			// If no word was found...
			if(!success) System.out.println("No answer exists: closest answer = " + perms.get(perms.size() - 1));
		}
		
		scanner.close();
	}
}


//class a modified and reduced version of the source found here: http://www.cs.princeton.edu/introcs/23recursion/Permutations.java.html
//Copyright © 2006, Robert Sedgewick and Kevin Wayne.
//Last updated: Wed Apr 4 07:07:00 EDT 2007.
//Modified by Travis Roe, Thurs, July 10, 2008 @ 13:30 EDT
class Permutations {

	private static ArrayList<String> tempHolder;

    // print N! permutation of the characters of the string s (in order)
    private static void perm1(String s) { perm1("", s); }
    private static void perm1(String prefix, String s) {
        int N = s.length();
        if (N == 0) tempHolder.add(prefix); //System.out.println(prefix);
        else {
            for (int i = 0; i < N; i++)
               perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
        }

    }
	
	public static ArrayList<String> getAllPerms(String s){
		tempHolder = new ArrayList<String>();
		perm1(s);
		return tempHolder;
	}
}