import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

immutable int letters = 26;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip.map !(q{a - 'a'}).array;
		auto t = readln.strip.map !(q{a - 'a'}).array;
		auto where = new int [] [letters];
		foreach (i, ref c; s)
		{
			where[c] ~= i.to !(int);
		}

		auto half = 1;
		while (half < n)
		{
			half <<= 1;
		}
		auto total = half << 1;
		auto r = new int [total];
		foreach (i; 0..n)
		{
			r[i + half] = i;
		}

		void alter (int lo, int hi, int delta)
		{
			for (lo += half, hi += half; lo < hi;
			    lo >>= 1, hi >>= 1)
			{
				if (lo & 1)
				{
					r[lo++] += delta;
				}
				if (hi & 1)
				{
					r[--hi] += delta;
				}
			}
		}

		int value (int pos)
		{
			int res = 0;
			for (pos += half; pos > 0; pos >>= 1)
			{
				res += r[pos];
			}
			return res;
		}

		long res = long.max;
		long cur = 0;
main_loop:
		foreach (i; 0..n)
		{
			foreach (z; 0..t[i])
			{
				if (!where[z].empty)
				{
					auto temp = value (where[z].front);
					res = min (res, cur + temp - i);
					if (temp == i)
					{
						break main_loop;
					}
				}
			}
			auto z = t[i];
			if (where[z].empty)
			{
				break;
			}
			auto temp = value (where[z].front);
			cur += temp - i;
			alter (0, where[z].front, +1);
			where[z].popFront ();
		}
		if (res == long.max)
		{
			res = -1;
		}
		writeln (res);
	}
}
