You are given $n$ strings $a_1, a_2, \ldots, a_n$: all of them have the same length $m$. The strings consist of lowercase English letters.

Find any string $s$ of length $m$ such that each of the given $n$ strings differs from $s$ in at most one position. Formally, for each given string $a_i$, there is no more than one position $j$ such that $a_i[j] \ne s[j]$.

Note that the desired string $s$ may be equal to one of the given strings $a_i$, or it may differ from all the given strings.

For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.


-----Input-----

The first line contains an integer $t$ ($1 \le t \le 100$) — the number of test cases. Then $t$ test cases follow.

Each test case starts with a line containing two positive integers $n$ ($1 \le n \le 10$) and $m$ ($1 \le m \le 10$) — the number of strings and their length.

Then follow $n$ strings $a_i$, one per line. Each of them has length $m$ and consists of lowercase English letters.


-----Output-----

Print $t$ answers to the test cases. Each answer (if it exists) is a string of length $m$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).


-----Example-----
Input
5
2 4
abac
zbab
2 4
aaaa
bbbb
3 3
baa
aaa
aab
2 2
ab
bb
3 1
a
b
c

Output
abab
-1
aaa
ab
z


-----Note-----

The first test case was explained in the statement.

In the second test case, the answer does not exist.

Source: codeforces | Difficulty: MEDIUM_HARD
Tags: Bit manipulation

Constructive algorithms

String algorithms

Complete search

Dynamic programming


Solutions:
for _ in range(int(input())):
	string = []
	(n, m) = map(int, input().split())
	for i in range(n):
		st = input()
		sr = []
		for j in st:
			sr.append(j)
		string.append(sr)
	ans = string[0]
	gl_ok = False
	gl_ans = ''
	for i in range(m):
		s = ans[i]
		for j in range(ord('a'), ord('z') + 1):
			ans[i] = chr(j)
			ok = True
			for k in range(n):
				cnt = 0
				for l in range(m):
					if string[k][l] != ans[l]:
						cnt += 1
				if cnt > 1:
					ok = False
					break
			if ok:
				gl_ok = True
				gl_ans = ans[:]
		ans[i] = s
	if gl_ok:
		print(''.join(gl_ans))
	else:
		print(-1)


t = int(input())
for a in range(t):
	(n, m) = map(int, input().split())
	possible = []
	l2 = []
	done = False
	for _ in range(n):
		s = input()
		l2.append(s)
		if not done:
			for i in range(m):
				done = True
				for j in range(26):
					x = chr(97 + j)
					t = list(s)
					t[i] = x
					t = ''.join(t)
					possible.append(t)
	z = 0
	for each in possible:
		f = 0
		g = [0] * n
		if f == 0:
			for j in range(m):
				for i in range(n):
					if each[j] != l2[i][j] and g[i] == 0:
						g[i] = 1
					elif each[j] != l2[i][j] and g[i] == 1:
						f = 1
			if f == 0:
				ans = each
				z = 1
	if z == 1:
		print(ans)
	else:
		print(-1)


t = int(input())
for q in range(t):
	(n, m) = map(int, input().split())
	strings = []
	for x in range(n):
		strings.append([x for x in input()])
	ans = strings[0][:]
	letters = 'abcdefghijklmnopqrstuvwxyz'
	for a in range(m):
		for l in letters:
			ans = strings[0][:]
			ans[a] = l
			flag = True
			for x in strings:
				diffs = 0
				for y in range(m):
					if ans[y] != x[y]:
						diffs += 1
					if diffs > 1:
						flag = False
						break
				if not flag:
					break
			if flag:
				break
		if flag:
			break
	if flag:
		for x in ans:
			print(x, end='')
		print()
	else:
		print(-1)


t = int(input())
for _ in range(t):
	(m, n) = map(int, input().split())
	mat = []
	for i in range(m):
		mat.append(list(input()))
	mat.sort()
	ans = []
	tmpans = []
	b = True
	if n == 1:
		b = False
	if m == 1:
		b = False
	if m >= 2 and n >= 2:
		tmp1 = mat[0]
		tmp2 = mat[1]
		tmpf = False
		for i in mat:
			for j in mat:
				c = 0
				for k in range(n):
					if i[k] != j[k]:
						c += 1
				if c == 2:
					tmp1 = i
					tmp2 = j
					tmpf = True
					break
				if c == 1:
					tmp1 = i
					tmp2 = j
				if c > 2:
					b = False
			if tmpf:
				break
		c = 0
		for i in range(n):
			if tmp1[i] == tmp2[i]:
				ans.append(tmp1[i])
				tmpans.append(tmp1[i])
			if tmp1[i] != tmp2[i]:
				if c == 0:
					ans.append(tmp1[i])
					tmpans.append(tmp2[i])
					c += 1
				elif c == 1:
					tmpans.append(tmp1[i])
					ans.append(tmp2[i])
					c += 1
				else:
					b = False
					break
	ct1 = 0
	ct2 = 0
	if b and len(ans) == n:
		for i in mat:
			c1 = 0
			c2 = 0
			for j in range(n):
				if i[j] != ans[j]:
					c1 += 1
				if i[j] != tmpans[j]:
					c2 += 1
			if c1 < 2:
				ct1 += 1
			if c2 < 2:
				ct2 += 1
	if ct1 != m and ct2 != m:
		b = False
	if ct2 == m:
		ans = tmpans
	if m == 1:
		s = ''
		for i in mat[0]:
			s += i
		print(s)
	elif b:
		s = ''
		for i in ans:
			s += i
		print(s)
	elif n == 1:
		print('a')
	else:
		print('-1')


import sys

def diff(s1, s2, m):
	ctr = 0
	for w in range(m):
		if s1[w] != s2[w]:
			ctr += 1
	return ctr

def solve():
	answer = []
	for h in range(m):
		answer.append(arr[0][h])
	ans = False
	for pos in range(m):
		tmp = answer[pos]
		for ch in range(26):
			answer[pos] = s[ch]
			flag = 1
			for w in range(1, len(arr)):
				val = diff(answer, arr[w], m)
				if val > 1:
					flag = 0
					break
			if flag == 1:
				ans = True
				break
		if ans == True:
			break
		answer[pos] = tmp
	if ans:
		answ = ''
		for k in range(m):
			answ += answer[k]
		return answ
	return '-1'
t = int(sys.stdin.readline())
ans_arr = []
for i in range(t):
	[n, m] = [int(j) for j in sys.stdin.readline().split()]
	arr = []
	for g in range(n):
		arr.append(sys.stdin.readline().strip())
	s = 'abcdefghijklmnopqrstuvwxyz'
	ans_arr.append(solve())
print('\n'.join(ans_arr))


import sys
LI = lambda : list(map(int, sys.stdin.readline().strip('\n').split()))
MI = lambda : map(int, sys.stdin.readline().strip('\n').split())
SI = lambda : sys.stdin.readline().strip('\n')
II = lambda : int(sys.stdin.readline().strip('\n'))
for _ in range(II()):
	(n, m) = MI()
	inp = [list(SI()) for i in range(n)]
	ans = ''
	cnt = 0
	for i in range(n):
		cur = 0
		for j in range(m):
			if inp[0][j] != inp[i][j]:
				cur += 1
		if cur > 1:
			cnt += 1
	if cnt == 0:
		ans = inp[0]
	tmp = inp[0].copy()
	for i in range(m):
		for j in range(n):
			cnt = 0
			tmpp = tmp[i]
			tmp[i] = inp[j][i]
			for k in range(n):
				cur = 0
				for l in range(m):
					if tmp[l] != inp[k][l]:
						cur += 1
				if cur > 1:
					cnt += 1
			if cnt == 0:
				ans = tmp.copy()
			tmp[i] = tmpp
	print(''.join(ans) if ans else -1)


def checkIfOk(str, arr):
	for i in range(len(arr)):
		t = 0
		for g in range(len(arr[0])):
			if arr[i][g] != str[g]:
				t += 1
		if t >= 2:
			return False
	return True

def generate(str, arr):
	letters = 'abcdefghijklmnopqrstuvwxyz'
	for i in range(len(str)):
		for g in range(26):
			newStr = str[:]
			newStr[i] = letters[g]
			res = checkIfOk(newStr, arr)
			if res:
				return newStr
				break
		else:
			continue
	else:
		return False
for i in range(int(input())):
	(am, l) = list(map(int, input().split()))
	strs = []
	for i in range(am):
		strs.append(list(input()))
	out = generate(strs[0], strs)
	print(''.join(out) if out else -1)


def check(a, b):
	cnt = 0
	for i in range(m):
		cnt += a[i] != b[i]
	return cnt
for u in range(int(input())):
	(n, m) = map(int, input().split())
	matrix = [list(input()) for i in range(n)]
	cnt = []
	for i in range(m):
		cur = set()
		for j in range(n):
			cur.add(matrix[j][i])
		cnt += [list(cur)]
	s = ''
	ind = 0
	while ind < m:
		if len(cnt[ind]) >= 2:
			break
		ind += 1
	if ind == m:
		s = matrix[0]
		print(''.join(s))
		continue
	fl = 0
	for el in cnt[ind]:
		for i in range(n):
			if matrix[i][ind] != el:
				s = matrix[i].copy()
				s[ind] = el
				fl = 1
				for j in range(n):
					if check(matrix[j], s) > 1:
						fl = 0
						break
			if fl:
				break
		if fl:
			break
	if fl:
		print(''.join(s))
	else:
		print(-1)


R = range
t = int(input())
for o in R(t):
	(n, m) = map(int, input().split())
	f = []
	c = set()
	r = []
	for i in ' ' * n:
		s = []
		for j in input():
			s += [j]
			c.add(j)
		f += [s]
	for i in R(m):
		for j in c:
			r += [s[:i] + [j] + s[i + 1:]]
	for x in r:
		F = 1
		for i in R(n):
			F &= sum([x[j] != f[i][j] for j in R(m)]) <= 1
		if F:
			a = x
			break
	print(''.join(a) if F else -1)


import sys
inp = [x for x in sys.stdin.read().split()]
ii = 0
ttt = int(inp[ii])
ii += 1
res = []
for _ in range(ttt):
	(n, m) = (int(inp[ii]), int(inp[ii + 1]))
	ii += 2
	a = inp[ii:ii + n]
	ii += n
	cur = ''
	ok = False
	for p in range(m):
		for c in range(ord('a'), ord('z') + 1):
			s = ''.join([chr(c) if p == j else a[0][j] for j in range(m)])
			if all([sum((s[j] != x[j] for j in range(m))) <= 1 for x in a]):
				cur = s
				ok = True
				break
		if ok:
			break
	res.append(cur if ok else '-1')
print('\n'.join((str(x) for x in res)))


import sys
T = int(sys.stdin.readline().strip())

def cmp(s1, s2, m):
	diff = 0
	for i in range(m):
		if s1[i] != s2[i]:
			diff += 1
	return diff
for t in range(T):
	(n, m) = map(int, sys.stdin.readline().strip().split(' '))
	cache = []
	for i in range(n):
		s = sys.stdin.readline().strip()
		cache.append(s)
	can = -2
	if n == 1:
		print(cache[0])
		continue
	for i in range(1, n):
		diff = cmp(cache[0], cache[i], m)
		if diff > 2:
			can = 0
			break
		if diff == 2:
			can = i
			break
	if can == 0:
		print('-1')
		continue
	if can == -2:
		print(cache[0])
		continue
	base1 = list(cache[0])
	base2 = list(cache[0])
	diff = []
	for i in range(m):
		if cache[0][i] != cache[can][i]:
			diff.append(i)
	base1[diff[0]] = cache[can][diff[0]]
	base2[diff[1]] = cache[can][diff[1]]
	can = True
	for i in range(n):
		if cmp(base1, cache[i], m) >= 2:
			can = False
			break
	if can:
		print(''.join(base1))
		continue
	can = True
	for i in range(n):
		if cmp(base2, cache[i], m) >= 2:
			can = False
			break
	if can:
		print(''.join(base2))
	else:
		print('-1')


for t in range(int(input())):
	(n, k) = list(map(int, input().split()))
	mat = []
	for i in range(n):
		mat += [input()]
	if n == 1:
		print(mat[0])
		continue
	elif k == 1:
		print('a')
		continue
	done = False
	for ch in range(k):
		for new_c in 'abcdefghijklmnopqrstuvwxyz':
			if not done:
				ans = mat[0]
				ans = ans[:ch] + new_c + ans[ch + 1:]
				good = True
				for i in range(n):
					count = 0
					for j in range(k):
						if mat[i][j] != ans[j]:
							count += 1
					if count > 1:
						good = False
						break
				if good:
					print(ans)
					done = True
	if not done:
		print(-1)


alpha = 'abcdefghijklmnopqrstuvwxyz'

def bruteForce(container, val, val2):
	global alpha
	temp = []
	for x in range(len(val)):
		if val[x] != val2[x]:
			temp.append(x)
	if len(temp) == 0:
		container.append(val)
	elif len(temp) == 1:
		for a in alpha:
			container.append(val[:temp[0]] + a + val[temp[0] + 1:])
	elif len(temp) == 2:
		for a in alpha:
			container.append(val[:temp[0]] + a + val[temp[0] + 1:])
		for a in alpha:
			container.append(val[:temp[1]] + a + val[temp[1] + 1:])
for _ in range(int(input())):
	(container, capt) = ([], [])
	(n, size) = map(int, input().split())
	for _ in range(n):
		capt.append(input())
	if len(capt) == 1:
		print(capt[0])
	else:
		(a, b) = (capt[0], capt[1])
		for n in capt[1:]:
			if a != n:
				b = n
				break
		bruteForce(container, a, b)
		if container:
			(sol, flag) = ('', 0)
			for j in container:
				(sol, flag) = (j, 1)
				for y in range(1, len(capt)):
					count = 0
					for f in range(size):
						if capt[y][f] != sol[f]:
							count += 1
					if count > 1:
						flag = 0
						break
				if flag:
					break
			print(sol if flag else -1)
		else:
			print('-1')


from math import *
t = int(input())
while t > 0:
	(n, m) = [int(x) for x in input().split()]
	a = []
	for i in range(n):
		s = input()
		a.append(s)
	for k in range(m):
		for l in range(26):
			s = ''
			for i in range(m):
				if i == k:
					s = s + chr(l + 97)
				else:
					s = s + a[0][i]
			flag = 0
			for i in range(n):
				c = 0
				for j in range(m):
					if a[i][j] != s[j]:
						c += 1
					if c > 1:
						flag = 1
						break
				if flag == 1:
					break
			if flag == 0:
				ans = s
				break
		if flag == 0:
			break
	if flag == 0:
		print(s)
	else:
		print(-1)
	t -= 1


def find(a, b):
	c = 0
	for (x, y) in zip(a, b):
		c += x != y
	return c
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [input() for i in range(n)]
	res = True
	ans = ''
	for i in range(m):
		s = a[0][:i] + '?' + a[0][i + 1:]
		temp = a[0]
		res = True
		for j in range(n):
			if find(s, a[j]) > 1:
				temp = a[0][:i] + a[j][i] + a[0][i + 1:]
				break
		for j in range(n):
			if find(temp, a[j]) > 1:
				res = False
				break
		if res:
			ans = temp
			break
	print([-1, ans][min(len(ans), 1)])


def main():
	letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
	t = int(input())
	for _ in range(t):
		(n, m) = list(map(int, input().split()))
		strings = []
		for __ in range(n):
			strings.append(input())
		impossible = False
		for index in range(m):
			for letter in letters:
				first = strings[0][:index] + letter + strings[0][index + 1:]
				for string in strings[1:]:
					level_of_difference = 0
					for i in range(m):
						if string[i] != first[i]:
							level_of_difference += 1
					if level_of_difference > 1:
						impossible = True
						break
					elif level_of_difference <= 1:
						impossible = False
				if not impossible:
					break
			if not impossible:
				break
		if impossible:
			print('-1')
		else:
			print(first)
main()


t = int(input())

def check(strings):
	for i in range(1, n):
		c = 0
		for j in range(m):
			if strings[0][j] != strings[i][j]:
				c += 1
		if c > 1:
			return 0
	return 1
for _ in range(t):
	(n, m) = map(int, input().split())
	strings = list()
	for i in range(n):
		x = input()
		strings.append(list(x))
	for i in range(m):
		flag = 0
		temp = strings[0][i]
		for j in range(97, 123):
			strings[0][i] = chr(j)
			if check(strings):
				print(''.join(strings[0]))
				flag = 0
				break
			else:
				flag = 1
		strings[0][i] = temp
		if flag == 0:
			break
	if flag:
		print(-1)


from fractions import Fraction
import sys
import bisect
import heapq
from math import *
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
mod = pow(10, 9) + 7

def inp():
	return sys.stdin.readline().strip()

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def graph(vertex):
	return [[] for i in range(0, vertex + 1)]

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def solve():
	(n, m) = sep()
	a = []
	for i in range(0, n):
		temp = list(inp())
		a.append(temp)
	ans = -1
	temp = []
	for i in range(0, n):
		flag = True
		for j in range(0, n):
			cnt = 0
			f = 0
			for k in range(0, m):
				if a[i][k] != a[j][k]:
					cnt += 1
			if cnt > 1:
				f = 1
			if cnt == 2:
				temp.append([a[i], a[j]])
			if f == 1:
				flag = False
				break
		if flag:
			ans = a[i]
			break
	if ans == -1:
		tochck = []
		for i in range(0, len(temp)):
			string = []
			string2 = []
			cnt = 0
			for k in range(0, m):
				if temp[i][0][k] == temp[i][1][k]:
					string.append(temp[i][0][k])
					string2.append(temp[i][0][k])
				elif cnt % 2 == 0:
					string.append(temp[i][0][k])
					string2.append(temp[i][1][k])
					cnt += 1
				else:
					string.append(temp[i][1][k])
					string2.append(temp[i][0][k])
			tochck.append(string)
			tochck.append(string2)
		an = -1
		for i in range(0, len(tochck)):
			flag = True
			for j in range(0, n):
				cnt = 0
				f = False
				for k in range(0, m):
					if tochck[i][k] != a[j][k]:
						cnt += 1
					if cnt > 1:
						f = True
						break
				if f:
					flag = False
					break
			if flag:
				an = tochck[i]
				break
		if an == -1:
			print(-1)
		else:
			lol = ''
			for i in range(0, len(an)):
				lol += an[i]
			print(lol)
	else:
		lol = ''
		for i in range(0, len(ans)):
			lol += ans[i]
		print(lol)
testcase(int(inp()))


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	(n, m) = list(map(int, input().split()))
	A = [input().strip() for i in range(n)]
	X = A[0]
	flag = 0
	for i in range(m):
		for j in range(26):
			Y = X[:i] + chr(97 + j) + X[i + 1:]
			for k in range(n):
				score = 0
				for l in range(m):
					if Y[l] != A[k][l]:
						score += 1
				if score <= 1:
					True
				else:
					break
			else:
				print(Y)
				flag = 1
				break
		if flag:
			break
	if flag == 0:
		print(-1)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	s = [input() for _ in range(n)]
	a = 'qwertyuiopasdfghjklzxcvbnm'
	for i in range(m):
		v = 0
		for l in a:
			p = s[0][:i] + l + s[0][i + 1:]
			t = 0
			for u in s:
				r = 0
				for h in range(m):
					if u[h] != p[h]:
						if r:
							t = 1
							break
						else:
							r = 1
				if t:
					break
			else:
				print(p)
				v = 1
				break
		if v:
			break
	else:
		print(-1)


import sys
import string
input = sys.stdin.readline
letters = list(string.ascii_lowercase)
t = int(input())
for i in range(t):
	(a, b) = input().split()
	(a, b) = (int(a), int(b))
	stri = []
	for j in range(a):
		stri.append(input().rstrip())
	o = stri[0]
	modif = []
	for j in range(b):
		for l in letters:
			new = o[:j] + l + o[j + 1:]
			modif.append(new)
	poss = 0
	for s in modif:
		max_counter = 0
		for o in stri:
			counter = 0
			for c in range(b):
				if s[c] != o[c]:
					counter += 1
			max_counter = max(max_counter, counter)
		if max_counter < 2:
			print(s)
			poss = 1
			break
	if poss == 0:
		print(-1)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	l = []
	for j in range(n):
		l.append(list(input()))
	s = ''
	for j in range(m):
		ans = l[0].copy()
		for k in range(97, 123):
			z = 1
			ans[j] = chr(k)
			for p in range(n):
				c = 0
				for q in range(m):
					if l[p][q] != ans[q]:
						c += 1
				if c > 1:
					z = 0
					break
			if z == 1:
				s = ''.join(ans)
				break
		if z == 1:
			break
	if s == '':
		print(-1)
	else:
		print(s)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [input() for _ in range(n)]
	found = False
	for i in range(m):
		for c in range(26):
			sol = list(a[0])
			sol[i] = chr(c + ord('a'))
			sol = ''.join(sol)
			found = True
			for j in range(n):
				d = 0
				for k in range(m):
					if sol[k] != a[j][k]:
						d += 1
				if d > 1:
					found = False
					break
			if found:
				break
		if found:
			break
	print(sol) if found else print(-1)


import sys
import string
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass

def check(arr1, arr2):
	count = 0
	for i in range(len(arr1)):
		if arr1[i] != arr2[i]:
			count += 1
	return count <= 1
for tt in range(int(input())):
	(n, m) = map(int, input().split())
	arr = []
	for _ in range(n):
		arr.append(list(input()))
	ans = -1
	for i in range(m):
		start = list(arr[0])
		for ch in string.ascii_lowercase:
			start[i] = ch
			for j in range(n):
				if not check(start, arr[j]):
					break
			else:
				ans = list(start)
	if ans == -1:
		print(-1)
	else:
		print(''.join(ans))


def check(li, t, n, m):
	for i in range(n):
		see = li[i]
		diff = 0
		for j in range(m):
			if see[j] != t[j]:
				diff += 1
		if diff > 1:
			return False
	return True

def solve():
	(n, m) = [int(x) for x in input().split()]
	li = []
	for i in range(n):
		li.append(input())
	s = li[0]
	if check(li, s, n, m):
		print(s)
		return
	else:
		for i in range(m):
			for j in range(97, 123, 1):
				new = s[:i] + chr(j) + s[i + 1:]
				if check(li, new, n, m):
					print(new)
					return
		else:
			print(-1)
			return
t = int(input())
for i in range(t):
	solve()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	s = [list(input().strip('\n')) for i in range(n)]
	ans = s[0][:]
	for x in range(m):
		curr = str(ans[x])
		for i in range(97, 123):
			ans[x] = chr(i)
			found = True
			for j in range(n):
				c = 0
				for y in range(m):
					if ans[y] != s[j][y]:
						c += 1
				if c > 1:
					found = False
			if found:
				print(''.join(ans))
				break
		if found:
			break
		ans[x] = curr
	if not found:
		print(-1)


import collections
import time
import os
import sys
import bisect
import heapq
from typing import List

def diff(a, b):
	return sum([1 if u != v else 0 for (u, v) in zip(a, b)])

def solve(N, M, A):

	def check(val):
		return all([diff(val, v) < 2 for v in A])
	ans = list(A[0])
	if check(ans):
		return ''.join(ans)
	for (i, v) in enumerate(ans):
		possible = {a[i] for a in A}
		for c in possible:
			ans[i] = c
			if check(ans):
				return ''.join(ans)
		ans[i] = v
	return '-1'
T = int(input())
ans = []
for ti in range(T):
	(N, M) = map(int, input().split())
	A = []
	for i in range(N):
		A.append(input())
	ans.append(solve(N, M, A))
print('\n'.join(ans))


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	letter = list('abcdefghijklmnopqrstuvwxyz')
	string = []
	for i in range(n):
		string.append(list(input()))
	temp = string[0]
	z = False
	for i in range(m):
		for j in letter:
			new_string = string[0].copy()
			new_string[i] = j
			for k in string:
				count = 0
				flag = False
				for l in range(m):
					if new_string[l] != k[l]:
						count += 1
					if count > 1:
						flag = True
						break
				if flag:
					break
			else:
				print(''.join(new_string))
				z = True
				break
		if z:
			break
	else:
		print('-1')


import sys, heapq
from collections import *
from functools import lru_cache
sys.setrecursionlimit(10 ** 6)

def main():

	def dfs(idx, path, diff):
		nonlocal res
		if idx == m:
			res = path
			return True
		(s0, s1) = (set(), set())
		for i in range(n):
			if diff & 1 << i:
				s1.add(arr[i][idx])
			else:
				s0.add(arr[i][idx])
		if len(s1) > 1:
			return False
		for ch in s0 | s1:
			newdiff = diff
			for i in range(n):
				if newdiff & 1 << i and arr[i][idx] != ch:
					break
				if arr[i][idx] != ch:
					newdiff = newdiff | 1 << i
			else:
				if dfs(idx + 1, path + ch, newdiff):
					return True
		return False
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, input().split(' '))
		arr = []
		res = ''
		for i in range(n):
			s = input()
			arr.append(s)
		if dfs(0, '', 0):
			print(res)
		else:
			print(-1)
main()


def find(n, m, ss):
	s1 = ss[0]
	for i in range(m):
		for j in range(26):
			s1n = s1[:i] + [chr(97 + j)] + s1[i + 1:]
			worked = True
			for s in ss:
				diffs = [a for a in range(m) if s[a] != s1n[a]]
				if len(diffs) >= 2:
					worked = False
					break
			if worked:
				print(''.join(s1n))
				return
	print(-1)
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	ss = []
	for j in range(n):
		ss.append(list(input()))
	find(n, m, ss)


global m, a

def f():
	for i in range(26):
		ch2 = chr(ord('b') + i)
		for st in a:
			for l in range(m):
				s = st[:l] + ch2 + st[l + 1:]
				if check(s):
					return s
	for st in a:
		if check(st):
			return st
	return ''

def check(s):
	global m, a
	f = True
	for i in a:
		ct = 0
		for j in range(m):
			if i[j] != s[j]:
				ct += 1
			if ct > 1:
				f = False
				break
	return f
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	ll = set()
	st = [chr(ord('a') + i) for i in range(26)]
	for i in range(n):
		s = input()
		a.append(s)
	ans = f()
	if ans == '':
		print(-1)
		continue
	print(ans)


import sys
input = sys.stdin.readline
from math import *

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return res

def upper_bound(a, x, lo=0):
	hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(1000000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

def int_array():
	return list(map(int, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')

def isValid(this):
	for i in range(n):
		count = 0
		for j in range(m):
			if this[j] != a[i][j]:
				count += 1
			if count > 1:
				return False
	return True
for _ in range(int(input())):
	(n, m) = int_array()
	a = []
	for __ in range(n):
		a.append(list(input().strip()))
	x = a[0]
	f = 1
	for i in range(m):
		if not f:
			break
		for j in range(26):
			this = x.copy()
			this[i] = chr(97 + j)
			if isValid(this):
				print(''.join(this))
				f = 0
				break
	if f:
		print(-1)


def get_num_diff(s1, s2, m):
	total = 0
	idxs = []
	for i in range(m):
		if s1[i] != s2[i]:
			total += 1
			idxs.append(i)
	return (total, idxs)

def main():
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, input().split())
		M = 0
		d = {}
		strings = []
		spy = input()
		for i in range(n - 1):
			s = input()
			strings.append(s)
			(diff, idxs) = get_num_diff(spy, s, m)
			M = max(M, diff)
			if diff in d:
				d[diff].append([s, idxs])
			else:
				d[diff] = [[s, idxs]]
		if M >= 3:
			print(-1)
		elif M <= 1:
			print(spy)
		else:
			(test_s, test_idxs) = d[2][0]
			good = False
			for j in range(2):
				idx = test_idxs[j]
				new_spy = spy[:idx] + test_s[idx] + spy[idx + 1:]
				M = 0
				for string in strings:
					(diff, idxs) = get_num_diff(new_spy, string, m)
					M = max(M, diff)
				if M <= 1:
					good = True
					break
			if good:
				print(new_spy)
			else:
				print(-1)
main()


def check(s, st):
	for u in range(len(s)):
		cnt = 0
		for k in range(len(st)):
			if s[u][k] != st[k]:
				cnt += 1
		if cnt > 1:
			return False
	return True
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	s = []
	for i in range(n):
		s.append(input())
	if check(s, s[0]):
		print(''.join(s[0]))
	else:
		f = 0
		final = ''
		var = 'abcdefghijklmnopqrstuvwxyz'
		for j in range(len(s[0])):
			st = list(s[0])
			for ch in var:
				st[j] = ch
				if check(s, st):
					f = 1
					final = st
					break
			if f == 1:
				break
		if f == 0:
			print(-1)
		else:
			print(''.join(final))


import copy
t = int(input())

def dist(s, t):
	diff = 0
	for i in range(len(s)):
		if s[i] != t[i]:
			diff += 1
	return diff
for _ in range(t):
	(n, m) = map(int, input().split())
	A = []
	for _ in range(n):
		s = list(input())
		A.append(s)
	maxdist = 0
	for i in range(n - 1):
		for j in range(i + 1, n):
			d = dist(A[i], A[j])
			if d > maxdist:
				maxdist = d
			if d == 2:
				imem = i
				jmem = j
		if maxdist >= 3:
			break
	if maxdist <= 1:
		print(''.join(A[0]))
	elif maxdist >= 3:
		print('-1')
	else:
		a = A[imem]
		b = A[jmem]
		inds = []
		for i in range(m):
			if a[i] != b[i]:
				inds.append(i)
		c = copy.copy(a)
		d = copy.copy(b)
		c[inds[0]] = b[inds[0]]
		d[inds[0]] = a[inds[0]]
		(a, b) = (c, d)
		mda = 0
		mdb = 0
		for i in range(n):
			da = dist(a, A[i])
			db = dist(b, A[i])
			if da > mda:
				mda = da
			if db > mdb:
				mdb = db
		if mda <= 1:
			print(''.join(a))
		elif mdb <= 1:
			print(''.join(b))
		else:
			print('-1')


from collections import Counter
from collections import defaultdict
from itertools import product
t = int(input())
for i in range(t):
	(n, m) = list(map(int, input().split()))
	store = [defaultdict(int) for i in range(m)]
	strings = []
	for j in range(n):
		s = input()
		strings.append(s)
		for k in range(len(s)):
			store[k][s[k]] += 1
	ans = [set() for i in range(m)]
	for mi in range(len(store)):
		m = store[mi]
		for (i, j) in m.items():
			ans[mi].add(i)
	test = sorted(ans, key=lambda x: len(x))
	if len(test) > 1 and len(test[-2]) > 5:
		final = False
	else:
		final = False
		for answer in product(*ans):
			main = answer
			got = True
			for string in strings:
				count = 0
				for ind in range(len(main)):
					if string[ind] != main[ind]:
						count += 1
					if count > 1:
						got = False
						break
				if count > 1:
					got = False
					break
			if got:
				print(''.join(answer))
				final = True
				break
	if not final:
		print(-1)


import math
t = int(input())

def check(n, m, l, temp):
	for i in range(n):
		count = 0
		for j in range(m):
			if l[i][j] != temp[j]:
				count += 1
			if count > 1:
				return False
	return True
for q in range(t):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(list(input()))
	ans = l[0]
	ttt = False
	for i in range(m):
		for j in range(26):
			temp = ans[:]
			temp[i] = chr(97 + j)
			if check(n, m, l, temp):
				print(''.join(temp))
				ttt = True
				break
		if ttt == True:
			break
	if ttt == False:
		print(-1)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	if n == 1:
		print(input())
	else:
		ls = []
		for _ in range(n):
			ls.append(list(input()))
		first = ls[0]
		flag = 0
		ans = []
		for i in range(m):
			tem = first[i]
			for char in range(97, 123):
				first[i] = chr(char)
				ma = 0
				count = 0
				for j in range(1, n):
					count = 0
					for k in range(m):
						if first[k] != ls[j][k]:
							count += 1
					ma = max(ma, count)
				if ma == 0 or ma == 1:
					flag = 1
					ans = first
					break
				if flag == 1:
					break
			if flag == 1:
				break
			first[i] = tem
		if flag == 1:
			print(''.join(ans))
		else:
			print(-1)


def comparision(st1, st2, m):
	error = 0
	for i in range(m):
		if st1[i] != st2[i]:
			error += 1
	return error <= 1
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		s = list(input())
		a.append(s)
	correct_ans = []
	for j in range(m):
		ans = a[0].copy()
		for k in range(26):
			ans[j] = chr(97 + k)
			count = 0
			for elem in a:
				if comparision(ans, elem, m):
					count += 1
			if count == n:
				correct_ans = ans
				break
		if correct_ans:
			break
	if correct_ans:
		print(''.join(correct_ans))
	else:
		print(-1)


t = int(input())

def convert(s):
	new = ''
	for x in s:
		new += x
	return new
for i in range(t):
	(a, b) = map(int, input().split())
	m = []
	for j in range(a):
		s = input()
		m.append(s)
	found2 = 0
	fail = 0
	for j in range(a):
		for k in range(j + 1, a):
			if m[j] == m[k]:
				continue
			else:
				differencecounter = 0
				differences = []
				for s in range(b):
					if m[j][s] != m[k][s]:
						differencecounter += 1
						differences.append(s)
				if differencecounter == 2:
					first = j
					second = k
					interest = differences.copy()
					found2 = 1
					break
				if differencecounter > 2:
					fail = 1
					break
			if fail == 1 or found2 == 1:
				break
		if fail == 1 or found2 == 1:
			break
	if fail == 1:
		print(-1)
	elif found2 == 0:
		print(m[0])
	else:
		option1 = []
		for j in range(interest[1]):
			option1.append(m[first][j])
		for k in range(interest[1], b):
			option1.append(m[second][k])
		option2 = []
		for j in range(interest[0] + 1):
			option2.append(m[second][j])
		for k in range(interest[0] + 1, b):
			option2.append(m[first][k])
		option1allowed = [0] * a
		option2allowed = [0] * a
		for j in range(b):
			for k in range(a):
				if m[k][j] != option1[j]:
					option1allowed[k] += 1
				if m[k][j] != option2[j]:
					option2allowed[k] += 1
		if max(option1allowed) < 2:
			print(convert(option1))
		elif max(option2allowed) < 2:
			print(convert(option2))
		else:
			print(-1)


import sys
import os
import time
import collections
from collections import Counter, deque
import itertools
import math
import timeit
import random
import string

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=1):
	divisors = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				divisors.append(i)
			else:
				divisors.extend([i, n // i])
	return divisors

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def flin(d, x, default=-1):
	left = right = -1
	for i in range(len(d)):
		if d[i] == x:
			if left == -1:
				left = i
			right = i
	if left == -1:
		return (default, default)
	else:
		return (left, right)

def ceil(n, k):
	return n // k + (n % k != 0)

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return list(map(int, input().split()))

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def prr(a, sep=' ', end='\n'):
	print(sep.join(map(str, a)), end=end)

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)

def good(s, t, j=-1):
	n = 0
	for i in range(len(s)):
		if i != j and s[i] != t[i]:
			n += 1
		if n > 1:
			return False
	return True
for _ in range(ii()):
	(n, m) = mi()
	d = []
	for _ in range(n):
		d.append([x for x in input()])
	res = d[0]
	r = [set() for i in range(n)]
	for i in range(n):
		for j in range(m):
			if good(d[i], res, j):
				r[i].add(j)
	k = r.pop()
	for rs in r:
		k &= rs
	f = 0
	ans = []
	for pos in k:
		tmp = res[:]
		for c in string.ascii_lowercase:
			tmp[pos] = c
			if all((good(tmp, line) for line in d)):
				f = 1
				ans = tmp
				break
		if f:
			break
	prr(ans, '') if ans else print(-1)


import sys
input = sys.stdin.readline
t = int(input())
import math
z = ''
n = 0
char = []
strings = []

def func(s, index, count):
	global z, n, char, strings
	if index == m:
		z = s
		return
	global char
	for i in char[index]:
		temp = []
		fl = 0
		for j in range(len(count)):
			temp.append(count[j])
		for j in range(n):
			if strings[j][index] != i:
				if temp[j] == 0:
					temp[j] = 1
				else:
					fl = 1
					break
		if fl == 0:
			func(s + i, index + 1, temp)
for t1 in range(t):
	(n, m) = list(map(int, input().split(' ')))
	strings = []
	char = []
	for i in range(m):
		char.append({})
	z = ''
	count = [0] * n
	for i in range(n):
		s = input()
		s = s.strip()
		strings.append(s)
		for j in range(m):
			char[j][s[j]] = 1
	func('', 0, count)
	if z == '':
		print(-1)
	else:
		print(z)


from sys import stdin
import math
input = stdin.readline

def get_diff(s1, s2):
	diff = []
	for i in range(len(s1)):
		if s1[i] != s2[i]:
			diff.append(i)
	return diff

def check(s, arr):
	for i in range(len(arr)):
		diff = get_diff(s, arr[i])
		if len(diff) > 1:
			return False
	return True

def get_me(arr):
	max_diff = 0
	s1 = arr[0]
	s2 = arr[1]
	for i in range(len(arr) - 1):
		for j in range(i + 1, len(arr)):
			diff = get_diff(arr[i], arr[j])
			if len(diff) > max_diff:
				max_diff = len(diff)
				s1 = arr[i]
				s2 = arr[j]
	return (s1, s2)
t = int(input().strip())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	arr = []
	for i in range(n):
		arr.append(input().strip())
	if n == 1:
		print(arr[0])
		continue
	(s1, s2) = get_me(arr)
	diff = get_diff(s1, s2)
	if len(diff) <= 1:
		ans = s1
		print(ans)
	elif len(diff) == 2:
		for i in arr:
			if check(i, arr):
				ans = i
				print(i)
				break
		else:
			ans = list(s1)
			ans[diff[1]] = s2[diff[1]]
			ans = ''.join(ans)
			if check(ans, arr):
				print(ans)
			else:
				ans = list(s2)
				ans[diff[1]] = s1[diff[1]]
				ans = ''.join(ans)
				if check(ans, arr):
					print(ans)
				else:
					print(-1)
	else:
		ans = -1
		print(ans)


from sys import stdin

def poss(c, l, n, m):
	f = 0
	for j in l:
		diff = 0
		for k in range(m):
			if c[k] != j[k]:
				diff += 1
			if diff > 1:
				f = 1
				break
		if f == 1:
			break
	if f == 0:
		return i
	return -1
for _ in range(int(stdin.readline())):
	(n, m) = map(int, stdin.readline().split())
	l = []
	for i in range(n):
		l.append(input())
	c = l[0]
	arr = []
	for i in range(m):
		k = set()
		for j in range(n):
			k.add(l[j][i])
		arr.append(list(k))
	for i in range(m):
		f = 0
		for j in range(len(arr[i])):
			if poss(c[:i] + arr[i][j] + c[i + 1:], l, n, m) != -1:
				f = 1
				print(c[:i] + arr[i][j] + c[i + 1:])
			if f == 1:
				break
		if f == 1:
			break
	if f == 0:
		print(-1)


from sys import stdin, setrecursionlimit as srl
from threading import stack_size, Thread
srl(int(1000000000.0) + 7)
stack_size(int(100000000.0))

def conf(a, b):
	cnt = 0
	for i in range(len(a)):
		if a[i] != b[i]:
			cnt += 1
	return cnt

def check(x, s):
	for i in s:
		if conf(i, x) > 1:
			return 0
	return 1

def solve():
	t = int(input())
	for _ in range(t):
		ans = -1
		(n, m) = map(int, input().split())
		s = []
		end = 0
		for i in range(n):
			s.append(input())
		for i in range(m):
			sg = s[0]
			for j in range(ord('a'), ord('z') + 1):
				try:
					x = sg[:i] + chr(j) + sg[i + 1:]
				except:
					x = sg[:i] + chr(j)
				end = check(x, s)
				if end:
					ans = x
					break
			if end:
				break
		print(ans)
global ans
Thread(target=solve).start()


import math
import collections
from sys import stdin, stdout, setrecursionlimit
from bisect import bisect_left as bsl
from bisect import bisect_right as bsr
import heapq as hq
setrecursionlimit(2 ** 20)

def strcmp(s1, s2, m):
	cnt = 0
	for i in range(m):
		if s1[i] != s2[i]:
			cnt += 1
	return cnt
t = int(stdin.readline())
for _ in range(t):
	(n, m) = list(map(int, stdin.readline().rstrip().split()))
	a = []
	for i in range(n):
		a.append(stdin.readline().split()[0])
	if m == 1:
		print(a[0])
		continue
	else:
		ans = -1
		if n == 2:
			l = []
			for i in range(m):
				if a[0][i] != a[1][i]:
					l.append(i)
			if len(l) >= 3:
				ans = -1
			elif len(l) == 1 or len(l) == 0:
				ans = a[0]
			else:
				ans = ''
				for i in range(m):
					if i == l[0]:
						ans += a[1][i]
					else:
						ans += a[0][i]
			print(ans)
			continue
		else:
			d = [[0] * n for i in range(n)]
			for i in range(n):
				for j in range(i + 1, n):
					d[i][j] = strcmp(a[i], a[j], m)
					d[j][i] = d[i][j]
			pos = -1
			for i in range(n):
				mx = -1
				for j in range(n):
					mx = max(mx, d[i][j])
				if mx <= 1:
					pos = i
					break
				if mx == 2:
					pos = -1
					for j in range(n):
						if d[i][j] == 2:
							pos = j
							break
					l = []
					for k in range(m):
						if a[i][k] != a[pos][k]:
							l.append(k)
					ans = ''
					for k in range(m):
						if k == l[0]:
							ans += a[pos][k]
						else:
							ans += a[i][k]
					mx = -1
					for k in range(n):
						mx = max(mx, strcmp(ans, a[k], m))
					if mx <= 1:
						a[pos] = ans
						break
					else:
						pos = -1
			if pos == -1:
				print(pos)
			else:
				print(a[pos])


def solve():
	(n, m) = map(int, input().split())
	a = []
	for _ in range(n):
		a.append(list(input()))
	for i in range(m):
		tmp = a[0][:]
		flg = False
		for j in range(1, n):
			flg2 = False
			for k in range(m):
				if i == k and (not flg):
					continue
				if tmp[k] != a[j][k]:
					if flg and flg2:
						break
					flg2 = True
					if not flg:
						tmp[i] = a[j][i]
						flg = True
			else:
				continue
			break
		else:
			return ''.join(tmp)
	return -1
t = int(input())
for _ in range(t):
	print(solve())


import typing

def choose_letter(strings: typing.List[str], penalties: typing.List[bool], n: int, position: int):
	if position == n:
		return ''
	letters = set((string[position] for (string, penalty) in zip(strings, penalties)))
	for letter in letters:
		new_penalties = penalties.copy()
		double_penalty = False
		for (i, string) in enumerate(strings):
			if string[position] != letter:
				if new_penalties[i]:
					double_penalty = True
					break
				new_penalties[i] = True
		if double_penalty:
			continue
		next_letter = choose_letter(strings, new_penalties, n, position + 1)
		if next_letter is None:
			continue
		return letter + next_letter
	return None
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	strings = [input() for _ in range(n)]
	word = choose_letter(strings, n * [False], m, 0)
	if word is None:
		print(-1)
	else:
		print(word)


import sys
import math
from collections import defaultdict, deque
import heapq
t = int(sys.stdin.readline())
for _ in range(t):
	(n, m) = map(int, sys.stdin.readline().split())
	l = []
	for i in range(n):
		s = sys.stdin.readline()[:-1]
		l.append(s)
	ind = -1
	z = True
	till = -1
	for i in range(m):
		let = l[0][i]
		for j in range(n):
			if l[j][i] != let:
				z = False
				ind = j
				till = i
				break
		if not z:
			break
	if z:
		print(l[0])
		continue
	z = True
	for k in range(26):
		ans = l[0][:till] + chr(97 + k) + l[0][till + 1:]
		z = True
		for i in range(n):
			cnt = 0
			for j in range(m):
				if l[i][j] != ans[j]:
					cnt += 1
			if cnt > 1:
				z = False
				break
		if z:
			print(ans)
			break
	if z:
		continue
	z = True
	for k in range(26):
		ans = l[ind][:till] + chr(97 + k) + l[ind][till + 1:]
		z = True
		for i in range(n):
			cnt = 0
			for j in range(m):
				if l[i][j] != ans[j]:
					cnt += 1
			if cnt > 1:
				z = False
				break
		if z:
			print(ans)
			break
	if not z:
		print(-1)


def strgntr(s, m):
	return set((s[:i] + chr(97 + j) + s[i + 1:] for i in range(m) for j in range(26)))
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	s = input()
	st = strgntr(s, m)
	for i in range(n - 1):
		st = strgntr(input(), m) & st
	print(-1 if not st else list(st)[0])


import sys
input = lambda : sys.stdin.readline().rstrip()
inp = sys.stdin.buffer.readline

def I():
	return list(map(int, inp().split()))
from math import sqrt, inf
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append([j for j in input()])
	alp = [chr(i) for i in range(97, 123)]
	ans = a[0][:]
	done = 0
	for i in range(len(ans)):
		if i > 0:
			ans[i - 1] = a[0][i - 1]
		for j in alp:
			ans[i] = j
			flag = 0
			for p in range(n):
				cnt = 0
				for q in range(m):
					if ans[q] != a[p][q]:
						cnt += 1
					if cnt == 2:
						flag = 1
						break
				if flag == 1:
					break
			if flag == 0:
				print(''.join(ans))
				done = 1
				break
		if flag == 0:
			break
	if done == 0:
		print(-1)


def find(a, b):
	c = 0
	for (x, y) in zip(a, b):
		c += x != y
	return c
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(input())
	res = True
	for i in range(n - 1):
		for j in range(i + 1, n):
			res &= find(a[i], a[j]) < 3
	if not res:
		print(-1)
		continue
	ans = ''
	for i in range(m):
		if len(ans):
			break
		s = a[0][:i] + '?' + a[0][i + 1:]
		t = list(s)
		temp = a[0]
		for j in range(n):
			if find(s, a[j]) > 1:
				t[i] = a[j][i]
				temp = ''.join(t)
				break
		res = True
		for j in range(n):
			if find(temp, a[j]) > 1:
				res = False
				break
		if res:
			ans = temp
			break
	if not len(ans):
		print(-1)
		continue
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split(' '))
	arr = []
	for i in range(n):
		s = input()
		arr.append(s)
	f = 0
	for i in arr:
		flag = 0
		for j in arr:
			cnt = 0
			for k in range(m):
				if i[k] != j[k]:
					cnt += 1
			if cnt > 1:
				flag = 1
				break
		if flag == 0:
			f = 1
			break
	if f == 1:
		print(i)
	else:
		s = []
		for i in arr[0]:
			s.append(i)
		q = 'abcdefghijklmnopqrstuvwxyz'
		f = 0
		for j in range(m):
			for i in q:
				s[j] = i
				flag = 0
				for k in arr:
					cnt = 0
					for k1 in range(m):
						if s[k1] != k[k1]:
							cnt += 1
					if cnt > 1:
						flag = 1
						break
				if flag == 0:
					f = 1
					break
			if f == 1:
				f = 2
				break
			s[j] = arr[0][j]
		if f == 2:
			ans = ''
			for i in s:
				ans = ans + i
			print(ans)
		else:
			print(-1)


def isvalid(s):
	nonlocal l
	for i in l:
		count = 0
		for j in range(len(i)):
			if s[j] != i[j]:
				count += 1
		if count > 1:
			return 0
	return 1
t = int(input())
for you in range(t):
	l = input().split()
	n = int(l[0])
	m = int(l[1])
	l = []
	for i in range(n):
		s = input()
		l.append(s)
	poss = 0
	ans = 0
	for i in range(m):
		copy = [x for x in l[0]]
		for j in range(26):
			copy[i] = chr(97 + j)
			if isvalid(copy):
				poss = 1
				ans = copy
				break
		if poss == 1:
			break
	if poss:
		for i in ans:
			print(i, end='')
		print()
	else:
		print(-1)


def true_str(s1, s2, m):
	true_s = 0
	for i in range(m):
		if s1[i] != s2[i]:
			true_s += 1
	return true_s <= 1

def all_str(s, m):
	all_s = []
	for i in range(m):
		for j in range(ord('a'), ord('z') + 1):
			all_s.append(s[:i] + chr(j) + s[i + 1:])
	return all_s
t = int(input())
for k in range(t):
	(n, m) = list(map(int, input().split()))
	list_str = []
	for i in range(n):
		list_str.append(input())
	lh = all_str(list_str[0], m)
	ans = False
	i = 0
	while i < len(lh) and (not ans):
		j = 0
		count_true = 0
		while j < n:
			if true_str(lh[i], list_str[j], m):
				count_true += 1
			j += 1
		if count_true == n:
			ans = True
		else:
			i += 1
	if ans:
		print(lh[i])
	else:
		print(-1)


import queue
import math
t = int(input())

def dist(a, b):
	cnt = 0
	for i in range(len(a)):
		cnt += a[i] != b[i]
	return cnt
while t:
	line = input().split()
	(n, m) = (int(line[0]), int(line[1]))
	a = []
	for i in range(n):
		a.append(list(input()))
	for i in range(m):
		for c in 'abcdefghijklmnopqrstuvwxyz':
			tmp = a[0][i]
			a[0][i] = c
			flag = True
			for j in range(1, n):
				if dist(a[0], a[j]) > 1:
					flag = False
					break
			if flag:
				break
			a[0][i] = tmp
		if flag:
			break
	if flag:
		print(''.join(a[0]))
	else:
		print(-1)
	t -= 1


t = int(input())
for i in range(t):
	(n, m) = list(map(int, input().split()))
	lis = []
	for j in range(n):
		s = str(input())
		lis.append(s)
	string = lis[0]
	arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
	b = 0
	j = 0
	temp = string
	while j < m:
		k = 0
		while k < 26:
			string = temp
			string = string[:j] + arr[k] + string[j + 1:]
			max1 = 0
			l = 1
			while l < n:
				a = 0
				p = 0
				while p < m:
					if string[p] != lis[l][p]:
						a += 1
					p += 1
				max1 = max(max1, a)
				l += 1
			if max1 <= 1:
				b += 1
				ans = string
				k = 26
				j = 11
			k += 1
		j += 1
	if b == 1:
		print(ans)
	else:
		print(-1)


import sys
input = sys.stdin.readline
from collections import *

def check(s):
	for ai in a[1:]:
		cnt = 0
		for i in range(m):
			if s[i] != ai[i]:
				cnt += 1
		if cnt >= 2:
			return False
	return True
t = int(input())
alpha = 'abcdefghijklmnopqrstuvwxyz'
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [list(input()[:-1]) for _ in range(n)]
	ans = ''
	for i in range(m):
		for alp in alpha:
			b = a[0][:]
			b[i] = alp
			if check(b):
				ans = b
	if ans == '':
		print(-1)
	else:
		print(''.join(ans))


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(int(data())):
	(n, m) = sp()
	mat = []
	for i in range(n):
		mat.append(list(data()))
	arr = mat[0][:]
	answer = ['-1']
	for i in range(m):
		temp = arr[i]
		r = True
		for j in range(26):
			r = True
			arr[i] = chr(j + 97)
			for k in range(1, n):
				cnt = 0
				for o in range(m):
					if arr[o] != mat[k][o]:
						cnt += 1
				if cnt > 1:
					r = False
					break
			if r:
				answer = arr
				break
		if r:
			break
		arr[i] = temp
	out(''.join(answer))


def check(n, m, A, B):
	for i in range(n):
		count = 0
		for j in range(m):
			if A[i][j] != B[j]:
				count += 1
		if count > 1:
			return False
	return True

def answer(n, m, A):
	ans = ''
	for i in range(m):
		B = A[0]
		for j in range(ord('a'), ord('z') + 1):
			if i == m - 1:
				B = B[:i] + chr(j)
			else:
				B = B[:i] + chr(j) + B[i + 1:]
			if check(n, m, A, B):
				return B
	return -1
t = int(input())
for i in range(t):
	(n, m) = map(int, input().strip().split())
	A = []
	for i in range(n):
		A.append(input())
	print(answer(n, m, A))


letters = list('abcdefghijklmnopqrstuvwxyz')
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	strings = set()
	for i in range(n):
		strings.add(input())
	word = strings.pop()
	answer = ''
	for i in range(m):
		for letter in letters:
			answer = word[:i] + letter + word[i + 1:]
			for string in strings:
				flag = -1
				for j in range(m):
					if string[j] != answer[j]:
						flag += 1
				if flag > 0:
					answer = ''
					break
			else:
				i = m
				break
		if i == m:
			break
	print(answer if len(answer) else -1)


import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15

def main():
	T = int(input())
	for _ in range(T):
		(N, M) = map(int, input().split())
		W = [input() for _ in range(N)]
		S = list(W[0])
		ans = None
		for i in range(M):
			for j in range(N):
				S[i] = W[j][i]
				flag = True
				for k in range(N):
					cnt = 0
					for l in range(M):
						if S[l] != W[k][l]:
							cnt += 1
							if cnt > 1:
								flag = False
								break
					if not flag:
						break
				if flag:
					ans = ''.join(S)
					break
			S[i] = W[0][i]
		print(ans if ans else -1)
main()


import io
import os

def solve(N, M, A):

	def twoDiffAnswer(word1, word2, i, j):
		candidates = [word1[:i] + word2[i] + word1[i + 1:], word1[:j] + word2[j] + word1[j + 1:]]
		for w1 in candidates:
			if all((sum((1 for (x, y) in zip(w1, w2) if x != y)) <= 1 for w2 in A)):
				return ''.join(w1)
		return -1
	w1 = A[0]
	for i in range(1, N):
		w2 = A[i]
		indices = [i for i in range(M) if w1[i] != w2[i]]
		if len(indices) > 2:
			return -1
		elif len(indices) == 2:
			return twoDiffAnswer(w1, w2, indices[0], indices[1])
	return w1
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
	(N, M) = [int(x) for x in input().split()]
	A = [input().decode().rstrip() for i in range(N)]
	ans = solve(N, M, A)
	print(ans)


import sys
import math
import itertools
import random
from collections import deque

def solve():
	(n, m) = map(int, input().split())
	s = [input() for _ in range(n)]
	for i in range(m):
		ans = list(s[0])
		for j in range(26):
			ans[i] = chr(j + ord('a'))
			if check(ans, n, m, s):
				ans = ''.join(ans)
				print(ans)
				return
	print(-1)

def check(ans, n, m, s):
	for i in range(n):
		cnt = 0
		for j in range(m):
			if s[i][j] != ans[j]:
				cnt += 1
		if cnt > 1:
			return False
	return True
t = int(input())
while t > 0:
	solve()
	t -= 1


import sys
input = sys.stdin.readline
t = int(input())
for test in range(t):
	(n, m) = list(map(int, input().split()))
	words = []
	for i in range(n):
		words.append(str(input()))
	not_possible = 0
	check_two = 0
	for i in range(n):
		for j in range(i + 1, n):
			word1 = words[i]
			word2 = words[j]
			diff = 0
			for k in range(m):
				if word1[k] != word2[k]:
					diff += 1
			if diff > 2:
				not_possible = 1
				break
			elif diff == 2:
				differs_at = []
				for k in range(m):
					if word1[k] != word2[k]:
						differs_at.append(k)
				opt_1 = word1[:differs_at[0]] + word1[differs_at[0]] + word2[differs_at[0] + 1:]
				opt_2 = word2[:differs_at[0]] + word2[differs_at[0]] + word1[differs_at[0] + 1:]
				check_two = 1
				break
			else:
				continue
		if not_possible == 1:
			break
		if check_two == 1:
			break
	if not_possible == 1:
		print(-1)
	elif check_two == 1:
		options = [opt_1, opt_2]
		for i in range(n):
			w = words[i]
			for opt in range(len(options) - 1, -1, -1):
				diff = 0
				for j in range(m):
					if options[opt][j] != w[j]:
						diff += 1
				if diff > 1:
					options.pop(opt)
		if len(options) == 0:
			print(-1)
		else:
			ans = options[0]
			print(ans, end='')
	else:
		ans = words[0]
		print(ans, end='')


from sys import stdin, stdout
input = stdin.readline
for t in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(input().strip())
	ans = '-1'
	b = [a[0]]
	for i in range(m):
		for j in range(97, 123):
			k = chr(j)
			if a[0][i] == k:
				continue
			else:
				b.append(a[0][:i] + k + a[0][i + 1:])
	d = 0
	for i in b:
		for j in range(1, n):
			d = 0
			for k in range(m):
				if i[k] != a[j][k]:
					d += 1
				if d > 1:
					break
			if d > 1:
				break
		if d <= 1:
			ans = i
			break
	stdout.write(ans + '\n')


def dist(w1, w2):
	total = 0
	for i in range(len(w1)):
		if w1[i] != w2[i]:
			total += 1
	return total
cases = int(input())
for case in range(cases):
	(n, m) = map(int, input().split())
	words = []
	for i in range(n):
		words.append(input())
	total = False
	for i in range(m):
		letter = [word[i] for word in words]
		if letter.count(letter[0]) < n:
			found = False
			for c in letter:
				invalid = [word[i + 1:] for word in words if word[i] != c]
				if invalid.count(invalid[0]) == len(invalid):
					valid = [word[i + 1:] for word in words if word[i] == c]
					maxdist = max([dist(word, invalid[0]) for word in valid])
					if maxdist <= 1:
						found = True
						break
			break
		if i == m - 1:
			total = True
	if total:
		print(words[0])
	elif found:
		print(words[0][:i] + c + invalid[0])
	else:
		print(-1)


TT = int(input())
alp = 'abcdefghijklmnopqrstuvwxyz'
for loop in range(TT):
	(n, m) = map(int, input().split())
	s = []
	for i in range(n):
		tmp = list(input())
		s.append(tmp)
	blf = False
	for i in range(m):
		now = []
		for x in range(m):
			now.append(s[0][x])
		for j in range(26):
			now[i] = alp[j]
			difnum = [0] * n
			for a in range(n):
				for b in range(m):
					if s[a][b] != now[b]:
						difnum[a] += 1
			if max(difnum) <= 1:
				print(''.join(now))
				blf = True
				break
		if blf:
			break
	if not blf:
		print(-1)


import sys
import math

def diff(a, b):
	r = zip(a, b)
	cnt = 0
	for e in r:
		if e[0] != e[1]:
			cnt += 1
	if cnt >= 3:
		return False
	if cnt <= 1:
		return True
	p1 = ''
	p2 = ''
	reverse = False
	for e in zip(a, b):
		if e[1] != e[0]:
			if reverse:
				p1 += e[0]
				p2 += e[1]
				reverse = not reverse
			else:
				p1 += e[1]
				p2 += e[0]
				reverse = not reverse
		else:
			p1 += e[0]
			p2 += e[1]
	return [p1, p2]

def simplediff(a, b):
	r = zip(a, b)
	cnt = 0
	for e in r:
		if e[0] != e[1]:
			cnt += 1
		if cnt >= 2:
			return False
	return True

def solve(arr, n, m):
	found = None
	for i in range(len(arr)):
		for j in range(i + 1, len(arr)):
			d = diff(arr[i], arr[j])
			if d == False:
				return -1
			elif d == True:
				continue
			else:
				found = d
				break
	if not found:
		return arr[0]
	else:
		zerook = True
		for i in range(len(arr)):
			if not simplediff(arr[i], found[0]):
				zerook = False
				break
		if zerook:
			return found[0]
		for i in range(len(arr)):
			if not simplediff(arr[i], found[1]):
				return -1
		return found[1]
t = int(sys.stdin.readline().strip())
for i in range(t):
	(n, m) = list(map(int, sys.stdin.readline().strip().split(' ')))
	s = []
	for j in range(n):
		s.append(sys.stdin.readline().strip())
	print(solve(s, n, m))


t = int(input())
for i in range(0, t):
	(n, m) = list(map(int, input().split()))
	l = []
	a = ''
	for j in range(0, n):
		s = input()
		l.append(list(s))
		a += s
	a = list(set(a))
	s = l[0]
	f = 0
	for j in range(0, m):
		s1 = []
		for b in range(0, m):
			s1.append(s[b])
		f = 0
		for b in a:
			s1[j] = b
			f = 0
			for k in range(0, n):
				c = 0
				for p in range(0, m):
					if s1[p] != l[k][p]:
						c += 1
				if c > 1:
					f = 2
					break
			if f == 0:
				s2 = ''
				for p in range(0, m):
					s2 += s1[p]
				print(s2)
				f = 1
				break
			s1 = []
			for k in range(0, m):
				s1.append(s[k])
			if f == 1:
				break
		if f == 1:
			break
	if f != 1:
		print(-1)


for t in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(input())
	if n < 2:
		print(l[0])
	elif m < 2:
		print('a')
	else:
		done = False
		for i in range(m):
			for j in 'abcdefghijklmnopqrstuvwxyz':
				if not done:
					ans = l[0]
					ans = ans[:i] + j + ans[i + 1:]
					good = True
					for x in range(n):
						count = 0
						for y in range(m):
							if ans[y] != l[x][y]:
								count += 1
						if count > 1:
							good = False
							break
					if good:
						print(ans)
						done = True
						break
		if not done:
			print('-1')


import sys
from collections import Counter
input = sys.stdin.readline

def f(x):
	for i in range(n):
		c = 0
		for j in range(m):
			if x[j] != s[i][j]:
				c += 1
			if c > 1:
				break
		if c > 1:
			break
	else:
		return 1
	return 0
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	(s, c) = ([], 0)
	ans = ''
	for i in range(n):
		s.append(input())
	for j in range(m):
		for i in range(97, 97 + 26):
			x = list(s[0])
			x[j] = chr(i)
			x = ''.join(x).strip()
			if f(x):
				c = 1
				break
		if c:
			break
	print(x if c else -1)


from sys import stdin, stdout

def chardiff1(s1, s2):
	diff = 0
	for i in range(len(s1)):
		if s1[i] != s2[i]:
			diff += 1
	return diff <= 1
t = int(stdin.readline())
for _ in range(t):
	(a, b) = map(int, stdin.readline().split())
	s = []
	for _ in range(a):
		s.append(stdin.readline().strip())
	cand = ['']
	imp = False
	for i in range(b):
		ch = set((ss[i] for ss in s))
		new_cand = []
		for cs in cand:
			for c in ch:
				new_cand.append(cs + c)
		cand = new_cand
		if len(cand) > 1024:
			imp = True
			break
	if imp:
		print(-1)
		continue
	ans = None
	for c in cand:
		if all((chardiff1(c, ss) for ss in s)):
			ans = c
			break
	if ans:
		print(ans)
	else:
		print(-1)


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))

def check(s, x):
	for i in x:
		h = 0
		for j in range(len(s)):
			h += int(i[j] != s[j])
		if h > 1:
			return False
	return True
for _ in range(int(input())):
	(a, b) = I()
	l = []
	for i in range(a):
		l.append(input())
	an = list(l[0])[:b]
	x = list(an)
	for i in range(b):
		for j in 'abcdefghijklmnopqrstuvwxyz':
			an[i] = j
			if check(an, l):
				print(''.join(an))
				an = 1
				break
		if an == 1:
			break
		an = list(x)
	if an != 1:
		print(-1)


a = int(input())
for i in range(a):
	(x, y) = map(int, input().split())
	ans = []
	for i in range(x):
		s = input()
		t = []
		for i in range(len(s)):
			t.append(s[i])
		ans.append(t)
	glag = 0
	for i in range(len(ans)):
		m = ans[i].copy()
		temp = []
		temp = m.copy()
		for j in range(len(m)):
			temp = m.copy()
			for t in range(26):
				temp = m.copy()
				temp[j] = chr(97 + t)
				count = 0
				flag = 0
				for w in range(len(ans)):
					t2 = []
					t2 = ans[w]
					count = 0
					for u in range(len(t2)):
						if t2[u] != temp[u]:
							count += 1
					if count >= 2:
						flag = 1
						break
				if flag == 0:
					glag = 1
					fin = []
					fin = temp
	if glag == 1:
		print(''.join(map(str, fin)))
	else:
		print(-1)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	mat = []
	for i in range(n):
		mat.append(input())
	li = []
	x = mat[0]
	for i in range(m):
		for j in range(97, 123):
			y = x[:i] + chr(j) + x[i + 1:]
			li.append(y)
	for x in li:
		flag = 1
		for i in range(n):
			diff = 0
			for j in range(m):
				if x[j] != mat[i][j]:
					diff += 1
				if diff > 1:
					flag = 0
					break
			if flag == 0:
				break
		if flag:
			print(x)
			break
	else:
		print(-1)


import sys
from collections import defaultdict, deque
from math import log10, sqrt, ceil
from pprint import pprint

def input():
	return sys.stdin.readline()[:-1]

def solve():
	(n, m) = [int(x) for x in input().split()]
	p = [[] for _ in range(m)]
	b = []
	for _ in range(n):
		a = input()
		b.append([x for x in a])
		for j in range(m):
			p[j].append(a[j])
	for i in range(n):
		for j in range(m):
			for e in set(p[j]):
				x = b[i][:]
				x[j] = e
				ok = 1
				for k in range(n):
					cnt = 0
					for o in range(m):
						if b[k][o] != x[o]:
							cnt += 1
					if cnt > 1:
						ok = 0
						break
				if ok:
					print(''.join(x))
					return
	print(-1)
t = 1
t = int(input())
for case in range(1, t + 1):
	ans = solve()


import math

def dist(a, b):
	ans = 0
	for i in range(len(a)):
		if a[i] != b[i]:
			ans += 1
	return ans

def check(words, candidate):
	for word in words:
		if dist(word, candidate) > 1:
			return False
	return True

def main():
	(n, m) = (int(x) for x in input().split())
	words = [input() for i in range(n)]
	candidate = list(words[0])
	if check(words, ''.join(candidate)):
		return ''.join(candidate)
	for i in range(len(candidate)):
		candidate = list(words[0])
		for char in range(ord('a'), ord('z') + 1):
			candidate[i] = chr(char)
			if check(words, candidate):
				return ''.join(candidate)
	return '-1'
t = int(input())
while t > 0:
	t -= 1
	ans = main()
	print(ans)


t = int(input())

def chk(s0, s):
	m = len(s[0])
	for s1 in s[1:]:
		d = sum((1 for i in range(m) if s0[i] != s1[i]))
		if d > 1:
			return False
	return True
for _ in range(t):
	(n, m) = map(int, input().split())
	s = []
	for _ in range(n):
		s.append(input())
	tmp = [s[0]]
	res = -1
	for i in range(m):
		for j in range(26):
			c = chr(j + ord('a'))
			if c == s[0][i]:
				continue
			new = s[0][:i] + c + s[0][i + 1:]
			tmp.append(new)
	for v in tmp:
		if chk(v, s):
			res = v
			break
	print(res)


import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def main():
	for _ in range(II()):
		(n, m) = MI()
		ss = [SI() for _ in range(n)]

		def dfs(j=0, ans='', bit=0):
			if j == m:
				return ans
			cc = set()
			for i in range(n):
				cc.add(ss[i][j])
			for c in cc:
				br = False
				nbit = bit
				for i in range(n):
					if ss[i][j] != c:
						if bit >> i & 1:
							br = True
							break
						nbit |= 1 << i
				if br:
					continue
				ret = dfs(j + 1, ans + c, nbit)
				if ret != '-1':
					return ret
			return '-1'
		print(dfs())
main()


import collections
import difflib

def find_str():
	(n, m) = list(map(int, input().split()))
	input_str = []
	for i in range(n):
		input_str.append(input())
	if n == 1:
		return input_str[0]
	if m == 1:
		return input_str[0]
	input_str = list(set(input_str))
	same = []
	for i in range(1, len(input_str)):
		not_same = 0
		for j in range(m):
			if input_str[0][j] != input_str[i][j]:
				not_same += 1
		if not_same <= 1:
			same.append(i)
	if len(same) == len(input_str) - 1:
		return input_str[0]
	for same_val in same:
		same2 = [0]
		for i in range(1, len(input_str)):
			not_same = 0
			for j in range(m):
				if input_str[same_val][j] != input_str[i][j]:
					not_same += 1
			if not_same <= 1:
				same2.append(i)
		if len(same2) == len(input_str):
			return input_str[same_val]
	for b in range(m):
		prediction = input_str[0]
		for a in range(1, len(input_str)):
			replace = input_str[a][b]
			to_be_replaced = prediction[b]
			if replace == to_be_replaced:
				continue
			prediction = prediction[:b] + replace + prediction[b + 1:]
			same3 = []
			for i in range(len(input_str)):
				not_same = 0
				for j in range(m):
					if prediction[j] != input_str[i][j]:
						not_same += 1
				if not_same <= 1:
					same3.append(i)
			if len(same3) == len(input_str):
				return prediction
	return -1
t = int(input())
result = []
for i in range(t):
	result.append(find_str())
for i in result:
	print(i)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	s = [input() for _ in range(n)]
	ans = -1
	alpha = [chr(ord('a') + i) for i in range(26)]
	for i in range(m):
		for c in alpha:
			x = list(s[0])
			x[i] = c
			x = ''.join(x)
			found = True
			for j in range(n):
				d = 0
				for k in range(m):
					if x[k] != s[j][k]:
						d += 1
				if d > 1:
					found = False
					break
			if found:
				break
		if found:
			break
	print(x if found else -1)


def main():
	import sys
	from collections import deque
	sys.setrecursionlimit(10 ** 6)
	input = sys.stdin.readline
	T = int(input())

	def dfs(i, list_, flags, ans):
		if i == m:
			print(ans)
			return True
		for s in list_[i]:
			flags_ = flags[:]
			for (j, word) in enumerate(words):
				if word[i] != s:
					if flags_[j]:
						flags_[j] = False
					else:
						break
			else:
				if dfs(i + 1, list_, flags_, ans + s):
					return True
		else:
			return None
	for t in range(T):
		(n, m) = [int(x) for x in input().strip().split()]
		list_ = [[] for _ in range(m)]
		words = [0] * n
		for i in range(n):
			words[i] = input().strip()
			for (j, s) in enumerate(words[i]):
				if s not in list_[j]:
					list_[j].append(s)
		flags = [True] * n
		if dfs(0, list_, flags[:], ''):
			pass
		else:
			print(-1)
main()


def valid(string, strings):
	for s in strings:
		c = 0
		for j in range(len(s)):
			if string[j] != s[j]:
				c += 1
			if c > 1:
				return False
	return True if c <= 1 else False
t = int(input())
for i in range(t):
	(n, m) = list(map(int, input().split()))
	strings = [list(input()) for i in range(n)]
	ans = None
	for string in strings:
		for j in range(len(string)):
			temp = str(string[j])
			for char in 'abcdefghijklmnopqrstuvwxyz':
				string[j] = char
				if valid(string, strings):
					ans = list(string)
					break
			string[j] = temp
			if ans is not None:
				break
		if ans is not None:
			break
	if ans is None:
		print(-1)
	else:
		print(''.join(ans))


def compare(l, s, n, m):
	for i in range(n):
		c = 0
		for j in range(m):
			if s[j] != l[i][j]:
				c += 1
			if c > 1:
				return 0
	return 1
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		s = input()
		l.append(s)
	s = []
	for i in range(m):
		s.append(l[0][i])
	f = 0
	b = []
	for i in range(m):
		b.append(s[i])
	for i in range(m):
		for j in range(26):
			s[i] = chr(97 + j)
			a = compare(l, s, n, m)
			if a == 1:
				f = 1
				break
		if f == 1:
			break
		s[i] = b[i]
	if f == 1:
		for i in range(m):
			print(s[i], end='')
		print()
	else:
		print(-1)


def poss(all_str, l, n, m):
	for i in all_str:
		f = 0
		for j in l:
			diff = 0
			for k in range(m):
				if i[k] != j[k]:
					diff += 1
				if diff > 1:
					f = 1
					break
		if f == 0:
			return i
	return -1
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(input())
	c = l[0]
	arr = []
	for i in range(m):
		k = set()
		for j in range(n):
			k.add(l[j][i])
		arr.append(list(k))
	all_str = set()
	for i in range(m):
		for j in range(len(arr[i])):
			all_str.add(c[:i] + arr[i][j] + c[i + 1:])
	all_str = list(all_str)
	print(poss(all_str, l, n, m))


alb = 'qwertyuiopasdfghjklzxcvbnm'
T = int(input())
for hohoho in range(T):
	(N, M) = map(int, input().split())
	Sl = [set() for i in range(N)]
	for i in range(N):
		S = list(input())
		for j in range(M):
			for t in alb:
				sv = S[j]
				S[j] = t
				Sl[i].add(''.join(S))
				S[j] = sv
	ans = Sl[0]
	for i in Sl:
		ans = ans & i
	for i in ans:
		print(i)
		break
	if not ans:
		print(-1)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ls = []
	for i in range(n):
		ls.append(list(input()))
	ans = -1
	for i in range(m):
		startchar = 'a'
		st = ls[0][:]
		for j in range(26):
			st[i] = chr(ord(startchar) + j)
			done = True
			for k in range(1, n):
				cnt = 0
				f = 0
				for p in range(m):
					if ls[k][p] != st[p]:
						cnt += 1
					if cnt == 2:
						f = 1
						break
				if f == 1:
					done = False
					break
			if done:
				ans = st
				break
		if ans != -1:
			break
	if ans == -1:
		print(ans)
	else:
		print(''.join(ans))


from sys import stdin, stdout

def spy_string(a, n, m):
	ca = list(a[0])
	for i in range(m):
		org = ca[i]
		for j in range(26):
			ca[i] = chr(ord('a') + j)
			found = True
			for k in range(1, n):
				dif = 0
				for l in range(m):
					if a[k][l] != ca[l]:
						dif += 1
				if dif > 1:
					found = False
					break
			if found:
				return ''.join(ca)
		ca[i] = org
	return '-1'
t = int(stdin.readline())
for i in range(t):
	(n, m) = list(map(int, stdin.readline().split()))
	a = []
	for j in range(n):
		a.append(stdin.readline().strip())
	stdout.write(spy_string(a, n, m) + '\n')


def solve(n, m, string):
	for i in range(m):
		ans = string[0][:]
		for j in range(26):
			ans[i] = j
			for a in string:
				count = 0
				for l in range(m):
					if a[l] != ans[l]:
						count += 1
				if count > 1:
					break
			else:
				return ans
	return False
t = int(input())
for ii in range(t):
	(n, m) = map(int, input().split())
	string = []
	for i in range(n):
		l = [int(ord(c) - ord('a')) for c in input()]
		string.append(l)
	output = solve(n, m, string)
	if output:
		print(''.join((chr(c + ord('a')) for c in output)))
	else:
		print(-1)


def main():
	import sys
	input = sys.stdin.readline
	sys.setrecursionlimit(10 ** 7)
	from collections import Counter, deque
	from itertools import combinations, permutations, accumulate, groupby, product
	from bisect import bisect_left, bisect_right
	from heapq import heapify, heappop, heappush
	import math
	t = int(input())
	alphabet = 'abcdefghijklmnopqrstuvwxyz'
	for _ in range(t):
		(n, m) = map(int, input().split())
		s = [list(input().rstrip()) for _ in range(n)]
		res = -1
		for i in range(m):
			if res != -1:
				continue
			temp = s[0][:]
			for j in range(26):
				if res != -1:
					continue
				temp[i] = alphabet[j]
				for k in range(1, n):
					diff = 0
					for c in range(m):
						if temp[c] != s[k][c]:
							diff += 1
					if diff >= 2:
						break
				else:
					res = temp
		if res == -1:
			print(-1)
		else:
			print(''.join(res))
main()


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [None] * n
	for i in range(n):
		a[i] = input()
	now = a[0]
	ans = []
	for i in range(m):
		for j in range(27):
			err = 0
			for k in range(1, n):
				e = 0
				for q in range(m):
					if i == q:
						if a[k][q] != chr(ord('a') + j):
							e = e + 1
					elif a[k][q] != a[0][q]:
						e = e + 1
				if e > 1:
					err = err + 1
					break
			if err == 0:
				ans = [i, chr(ord('a') + j)]
				break
		if len(ans) != 0:
			break
	if len(ans) == 0:
		print(-1)
	else:
		for i in range(m):
			if i == ans[0]:
				print(ans[1], end='')
			else:
				print(a[0][i], end='')
		print()


def getString(stringArray):
	n = len(stringArray)
	if n == 1:
		return stringArray[0]
	m = len(stringArray[0])
	possibleTemplates = []
	first = stringArray[0]
	for i in range(m):
		possibleTemplates.append(first[:i] + '*' + first[i + 1:])
	for word in possibleTemplates:
		for i in range(97, 97 + 26):
			word2 = word.replace('*', chr(i))
			ok = True
			for j in range(n):
				differenceCount = 0
				for k in range(m):
					if stringArray[j][k] != word2[k]:
						differenceCount += 1
				if differenceCount > 1:
					ok = False
					break
			if ok:
				return word2
	return '-1'
t = int(input())
for _ in range(t):
	(n, m) = [int(x) for x in input().split()]
	stringArray = []
	for i in range(n):
		stringArray.append(input())
	print(getString(stringArray))


def solve(n, m, arr):
	if n == 1:
		print(arr[0])
		return
	(s1, s2) = ('', '')
	for i in range(1, n):
		diff = check(arr[0], arr[i])
		if len(diff) <= 1:
			continue
		elif len(diff) == 2:
			(idx1, idx2) = diff
			s1 = arr[0][:idx1] + arr[i][idx1] + arr[0][idx1 + 1:]
			s2 = arr[i][:idx1] + arr[0][idx1] + arr[i][idx1 + 1:]
			break
		else:
			print(-1)
			return
	if s1 == '':
		print(arr[0])
		return
	(f1, f2) = (True, True)
	for s in arr:
		diff = check(s1, s)
		if len(diff) > 1:
			f1 = False
			break
	if f1:
		print(s1)
		return
	for s in arr:
		diff = check(s2, s)
		if len(diff) > 1:
			f2 = False
			break
	if f2:
		print(s2)
		return
	print(-1)
	return

def check(s1, s2):
	diff = []
	for i in range(len(s1)):
		if s1[i] != s2[i]:
			diff.append(i)
	return diff
t = int(input())
for i in range(0, t):
	(n, m) = map(int, input().split())
	arr = []
	for j in range(n):
		arr.append(input())
	solve(n, m, arr)


import sys
import math
import collections
from sys import stdin, stdout, setrecursionlimit
import bisect as bs
setrecursionlimit(2 ** 20)
M = 10 ** 9 + 7
T = int(stdin.readline())

def check(s1, s2):
	co = 0
	for i in range(m):
		if s1[i] != s2[i]:
			co += 1
	if co > 1:
		return False
	return True
for _ in range(T):
	(n, m) = list(map(int, stdin.readline().split()))
	ss = []
	for i in range(n):
		ss.append(list(stdin.readline().strip('\n')))
	res = False
	for i in range(m):
		for a in range(26):
			c = chr(ord('a') + a)
			t = ss[0].copy()
			t[i] = c
			cc = 0
			for j in range(1, n):
				if not check(t, ss[j]):
					break
				cc += 1
			if cc == n - 1:
				res = True
				break
		if res:
			break
	if res:
		print(''.join(t))
		continue
	print(-1)


from collections import defaultdict

def res(a):
	s = a[0]
	t = False
	for i in range(m):
		b = s[i]
		for j in range(ord('a'), ord('z') + 1):
			s = s[:i] + chr(j) + s[i + 1:]
			t = True
			for u in range(n):
				c = 0
				for v in range(m):
					if a[u][v] != s[v]:
						c += 1
				if c > 1:
					t = False
					break
			if t:
				break
		if t:
			break
		s = s[:i] + b + s[i + 1:]
	if t:
		print(s)
	else:
		print(-1)
for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	a = [input() for i in range(n)]
	res(a)


t = int(input())
while t:
	t += -1
	(n, m) = map(int, input().split())
	l = []
	ans = -1
	for i in range(n):
		l.append(input())
	for i in range(m):
		check = 1
		s = []
		for j in range(m):
			if j == i:
				s.append('*')
			else:
				s.append(l[0][j])
		for j in range(1, n):
			count = 0
			for k in range(m):
				if s[k] != l[j][k]:
					if s[k] != '*':
						count -= -1
			if count > 1:
				check = 0
				break
			elif count == 1:
				if s[i] == '*':
					s[i] = l[j][i]
		if check == 1:
			if s[i] == '*':
				s[i] = 'a'
			ans = s
			break
	if ans == -1:
		print(-1)
	else:
		print(*ans, sep='')


from sys import stdin, stdout
import math

def main():
	t = int(stdin.readline())
	for _ in range(t):
		(n, m) = list(map(int, stdin.readline().split()))
		s = []
		for _ in range(n):
			s.append(stdin.readline().rstrip())
		is_real_ok = False
		ans = ''
		for exc in range(m):
			for th in range(0, n):
				sr = list(s[0])
				sr[exc] = s[th][exc]
				is_ok = True
				for k in range(1, n):
					cnt = 0
					for pos in range(m):
						if sr[pos] != s[k][pos]:
							cnt += 1
							if cnt > 1:
								is_ok = False
								break
					if not is_ok:
						break
				if is_ok:
					is_real_ok = True
					ans = sr
					break
			if is_real_ok:
				break
		if is_real_ok:
			stdout.write(''.join(ans) + '\n')
		else:
			stdout.write('-1\n')
main()


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	s = []
	for _ in range(n):
		s.append(input())
	ans = list(s[0])
	l = []
	for i in range(m):
		for j in range(26):
			ans[i] = chr(j + 97)
			l.append(''.join(ans))
		ans[i] = s[0][i]
	nf = 0
	for i in l:
		flag = 0
		for j in s:
			ct = 0
			for k in range(m):
				if j[k] != i[k]:
					ct += 1
			if ct > 1:
				flag = 1
				break
		if flag == 0:
			print(''.join(i))
			nf = 1
			break
	if nf == 0:
		print('-1')


T = int(input())

def fn_check(arr, n, m):
	first = arr[0]
	res = []
	for i in range(m):
		for j in range(26):
			res.append(first[:i] + chr(j + 97) + first[i + 1:])
	for s in res:
		found = True
		for c in arr[1:]:
			count = 0
			for j in range(m):
				if s[j] != c[j]:
					count += 1
			if count > 1:
				found = False
		if found:
			return s
	return -1
for t in range(T):
	(n, m) = map(int, input().split())
	arr = []
	for i in range(n):
		arr.append(input())
	print(fn_check(arr, n, m))


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(list(input()))
	res = a[0]
	found = 0
	for i in range(m):
		tmp = res[i]
		for j in 'abcdefghijklmnopqrstuvwxyz':
			res[i] = j
			failed = 0
			for k in range(n):
				diff = 0
				for l in range(m):
					if a[k][l] != res[l]:
						diff += 1
				if diff > 1:
					failed = 1
					break
			if not failed:
				print(''.join(res))
				found = 1
				break
		if found:
			break
		res[i] = tmp
	if not found:
		print(-1)


def diff(ideal, dummy):
	ans = 0
	for i in range(len(ideal)):
		if ideal[i] != dummy[i]:
			ans += 1
	return ans
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = []
	for i in range(n):
		s = input()
		arr.append(s)
	s = arr[0]
	ok = False
	for i in range(m):
		for j in range(1, 27):
			t = [i for i in s]
			t[i] = chr(96 + j)
			t = ''.join(t)
			ok = True
			for x in range(1, n):
				if diff(t, arr[x]) > 1:
					ok = False
					break
			if ok:
				print(t)
				break
		if ok:
			break
	if not ok:
		print(-1)


def ans():
	(N, M) = map(int, input().split())
	if N == 1:
		return input()
	init = input()
	Done = False
	N -= 1
	while not Done:
		A = input()
		N -= 1
		if A != init:
			Done = True
		elif N == 0:
			return A
	dif = 0
	common = ''
	pos1 = ''
	pos2 = ''
	for (i, a) in zip(init, A):
		if i == a:
			common += i
			pos1 += i
			pos2 += i
		else:
			if dif == 0:
				pos1 += i
				pos2 += a
			else:
				pos1 += a
				pos2 += i
			common += ' '
			dif += 1
			if dif > 2:
				for _ in range(N):
					input()
				return -1
	if dif == 1:
		for s in range(N):
			A = input()
			dif = 0
			ans = ''
			for (c, a) in zip(common, A):
				if c != ' ' and c != a:
					dif += 1
					if dif > 1:
						for _ in range(N - s - 1):
							input()
						return -1
				if c != ' ':
					ans += c
				else:
					ans += a
			if dif == 1:
				common = ans
		ans = ''
		for elt in common:
			if elt == ' ':
				ans += 'z'
			else:
				ans += elt
		return ans
	else:
		ans = ''
		for s in range(N):
			A = input()
			if ans == '':
				if A == pos1 or A == pos2:
					ans = A
			if ans == '':
				dif1 = 0
				for (a, p) in zip(A, pos1):
					if a != p:
						dif1 += 1
						if dif1 > 1:
							ans = pos2
			if ans == '':
				dif2 = 0
				for (a, p) in zip(A, pos2):
					if a != p:
						dif2 += 1
						if dif2 > 1:
							ans = pos1
			if ans != '':
				dif = 0
				for (a, c) in zip(A, ans):
					if a != c:
						dif += 1
						if dif > 1:
							for _ in range(N - s - 1):
								input()
							return -1
		if ans == '':
			return pos1
		return ans
T = int(input())
for _ in range(T):
	print(ans())


import sys
import math
import collections

def set_debug(debug_mode=False):
	if debug_mode:
		fin = open('input.txt', 'r')
		sys.stdin = fin
t = int(input())
alph = 'abcdefghijklmnopqrstuvwxyz'
for ti in range(1, t + 1):
	(n, m) = map(int, input().split())
	s = [input() for i in range(n)]
	for i in range(m):
		for char in alph:
			cand = s[0][0:i] + char + s[0][i + 1:]
			flag = False
			for j in range(n):
				cnt = 0
				for k in range(m):
					if cand[k] != s[j][k]:
						cnt += 1
				if cnt > 1:
					flag = True
			if not flag:
				print(cand)
				break
		else:
			continue
		break
	else:
		print(-1)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	s = 'abcdefghijklmnopqrstuvwxyz'
	l = []
	a = ''
	for _ in range(n):
		l.append(input())
	for i in range(n):
		for y in range(m):
			for z in range(26):
				l1 = list(l[i])
				l1[y] = s[z]
				f = 0
				for u in range(n):
					k = 0
					for p in range(m):
						if l1[p] != l[u][p]:
							k += 1
						if k > 1:
							break
					if k > 1:
						break
					f += 1
					if f == n:
						a = l1
	if a == '':
		print(-1)
	else:
		print(''.join(a))


from collections import defaultdict
t = int(input())

def can(m, n, ans, A):
	found = True
	for i in range(n):
		diff = 0
		for j in range(m):
			if ans[j] != A[i][j]:
				diff += 1
			if diff > 1:
				found = False
				break
	return found
for _ in range(t):
	(n, m) = map(int, input().split(' '))
	A = [input() for _ in range(n)]
	found = False
	for i in range(m):
		for j in range(26):
			ans = list(A[0])
			ans[i] = chr(ord('a') + j)
			found = can(m, n, ans, A)
			if found:
				break
		if found:
			break
	if found:
		print(''.join(ans))
	else:
		print(-1)


t = int(input())

def check(n, m, a, s):
	flag = 0
	for i in a:
		c = 0
		for j in range(m):
			if i[j] != s[j]:
				c += 1
		if c > 1:
			flag += 1
			break
	if flag:
		return False
	else:
		return True

def fun(n, m, a):
	ans = ''
	ap = 'qwertyuiopasdfghjklzxcvbnm'
	ap = list(ap)
	ap.sort()
	for i in range(m):
		ans = ''
		ans += a[0]
		flag = 0
		for j in ap:
			ans = ans[0:i] + j + ans[i + 1:]
			if check(n, m, a, ans):
				flag += 1
				break
		if flag:
			print(ans)
			break
		elif i == m - 1:
			print(-1)
while t:
	t -= 1
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		b = input()
		a.append(b)
	fun(n, m, a)


t = int(input())

def solve():
	(n, m) = map(int, input().split())
	s = []
	for j in range(n):
		s.append(input())
	save = s[0]
	a = 'qwertyuiopasdfghjklzxcvbnm'
	for pos in range(m):
		for letter in a:
			ans = s[0][:pos] + letter + s[0][pos + 1:]
			fail = False
			for l in range(1, n):
				counter = 0
				for k in range(m):
					if ans[k] != s[l][k]:
						counter += 1
					if counter == 2:
						fail = True
						break
				if fail == True:
					break
			if fail == False:
				print(ans)
				return
	print(-1)
for i in range(t):
	solve()


import sys
from collections import Counter

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7

def rec(i, used):
	if i == M:
		return True
	for c in se[i]:
		if used & (mask ^ prep[i][c]) == 0:
			if rec(i + 1, used | mask ^ prep[i][c]):
				ans.append(c)
				return True
	return False
for _ in range(INT()):
	(N, M) = MAP()
	A = [[ord(c) - 97 for c in input()] for i in range(N)]
	prep = list2d(M, 26, 0)
	for i in range(M):
		for j in range(N):
			prep[i][A[j][i]] |= 1 << j
	se = [set() for i in range(M)]
	for S in A:
		for (i, s) in enumerate(S):
			se[i].add(s)
	ans = []
	mask = (1 << N) - 1
	if rec(0, 0):
		ans = [chr(c + 97) for c in ans[::-1]]
		print(''.join(ans))
	else:
		print(-1)


from sys import stdin, gettrace
if not gettrace():

	def input():
		return next(stdin)[:-1]

def main():

	def solve():
		(n, m) = map(int, input().split())
		ss = []
		for _ in range(n):
			ss.append(input())
		ssr = list(zip(*ss))

		def tailstr(i, counts):
			if i == m:
				return ['']
			chrs = ssr[i]
			for c in chrs:
				counts2 = counts.copy()
				for j in range(n):
					if c != chrs[j]:
						if counts2[j] == 1:
							break
						counts2[j] = 1
				else:
					ts = tailstr(i + 1, counts2)
					if ts:
						return [c] + ts
			return None
		ts = tailstr(0, [0] * n)
		if ts:
			print(''.join(ts))
		else:
			print(-1)
	q = int(input())
	for _ in range(q):
		solve()
main()


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [list(input()) for _ in range(n)]
	for i in range(m):
		s = 0
		for j in range(26):
			x = chr(97 + j)
			u = 1
			for k in range(1, n):
				c = 0
				for l in range(m):
					if i == l:
						if not a[k][l] == x:
							c += 1
					elif not a[0][l] == a[k][l]:
						c += 1
				if c > 1:
					u = 0
					break
			if u == 1:
				ans = a[0]
				ans[i] = chr(97 + j)
				print(''.join(ans))
				s = 1
				break
		if s == 1:
			break
	if not s == 1:
		print(-1)


T = int(input())
for t_itr in range(T):
	(N, M) = map(int, input().rstrip().split())
	S = []
	for _ in range(N):
		S.append(list(input()))
	is_valid = True
	for i in range(M):
		result = S[0].copy()
		for c in range(ord('a'), ord('z') + 1):
			result[i] = chr(c)
			is_valid = True
			for s in S:
				one_fail = False
				for j in range(M):
					if result[j] != s[j]:
						if one_fail:
							is_valid = False
							break
						else:
							one_fail = True
				if not is_valid:
					break
			if is_valid:
				break
		if is_valid:
			break
	if is_valid:
		print(''.join(result))
	else:
		print('-1')


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().strip().split(' '))

def msi():
	return map(str, input().strip().split(' '))

def li():
	return list(mi())

def dmain():
	sys.setrecursionlimit(1000000)
	threading.stack_size(1024000)
	thread = threading.Thread(target=main)
	thread.start()
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def getKey(item):
	return item[1]

def sort2(l):
	return sorted(l, key=getKey, reverse=True)

def d2(n, m, num):
	return [[num for x in range(m)] for y in range(n)]

def isPowerOfTwo(x):
	return x and (not x & x - 1)

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def ntl(n):
	return [int(i) for i in str(n)]

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def ceil(x, y):
	if x % y == 0:
		return x // y
	else:
		return x // y + 1

def powerMod(x, y, p):
	res = 1
	x %= p
	while y > 0:
		if y & 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def main():
	for _ in range(ii()):
		(n, m) = mi()
		s = []
		for i in range(n):
			s.append(list(si()))
		flag = 0
		ans = []
		for i in range(m):
			p = s[0][:]
			for j in range(26):
				cnt1 = 0
				p[i] = abc[j]
				f1 = 1
				for k in range(n):
					cnt = 0
					if s[k] == p:
						cnt1 += 1
					for l in range(m):
						if p[l] != s[k][l]:
							cnt += 1
					if cnt > 1:
						f1 = 0
						break
				if f1:
					ans = p
					flag = 1
					break
			if flag:
				break
		if flag:
			for i in range(m):
				print(ans[i], end='')
			print()
		else:
			print(-1)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from math import sqrt
t = int(input())
for q in range(0, t):
	(n, m) = map(int, input().split())
	arr = []
	for i in range(0, n):
		arr.append(input())
	ans = []
	for i in range(0, m):
		ans.append(arr[0][i])
	flag = False
	for i in range(0, m):
		if flag:
			break
		for j in range(ord('a'), ord('z') + 1):
			mem = ans[i]
			ans[i] = chr(j)
			flagNow = True
			for k in range(0, n):
				number = 0
				for l in range(0, m):
					if ans[l] != arr[k][l]:
						number += 1
				if number > 1:
					flagNow = False
			if flagNow:
				flag = True
				break
			ans[i] = mem
	if flag:
		s = ''
		for i in range(0, m):
			s += ans[i]
		print(s)
	else:
		print(-1)


INF = 10 ** 18
t = int(input())
abc = 'abcdefghijklmnopqrstuvwxyz'

def solve():
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(input())
	if n == 1:
		print(a[0])
		return
	ans = '-1'
	for i in range(m):
		for j in range(26):
			temp = a[0][0:i] + abc[j] + a[0][i + 1:]
			md = 0
			for k in range(1, n):
				d = 0
				for p in range(m):
					if a[k][p] != temp[p]:
						d += 1
				md = max(md, d)
			if md <= 1:
				ans = temp
	print(ans)
for tt in range(t):
	solve()


def solve(arr, n, m):
	fix = arr[0]
	for t in range(m):
		ch = fix[t]
		for k in range(26):
			fix[t] = chr(ord('a') + k)
			flag = True
			for i in range(n):
				count = 0
				for j in range(m):
					if arr[i][j] != fix[j]:
						count += 1
				if count > 1:
					flag = False
					break
			if flag == True:
				return ''.join(fix)
		fix[t] = ch
	return -1
for T in range(int(input())):
	(n, m) = list(map(int, input().split()))
	arr = []
	for i in range(n):
		arr.append(list(input()))
	v = solve(arr, n, m)
	print(v)


import sys
import math as mt
t = int(input())
for __ in range(t):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(input())
	s = l[0]
	l1 = []
	for i in range(m):
		for j in range(26):
			l1.append(s[:i] + str(chr(j + 97)) + s[i + 1:])
	ch = 0
	for i in range(len(l1)):
		maxi = 0
		for j in range(n):
			diff = 0
			for j1 in range(m):
				if l1[i][j1] != l[j][j1]:
					diff += 1
			maxi = max(maxi, diff)
		if maxi <= 1:
			ans = l1[i]
			ch = 1
			break
	if ch == 1:
		print(ans)
	else:
		print(-1)


import string

def spystring(words):

	def neigh(word):
		candidates = {word}
		for i in range(len(word)):
			for c in string.ascii_lowercase:
				candidates.add(word[:i] + c + word[i + 1:])
		return candidates
	intersection = neigh(words[0])
	for word in words[1:]:
		intersection &= neigh(word)
	return intersection and intersection.pop() or -1

def solve():
	(n, m) = map(int, input().split())
	s = [input() for _ in range(n)]
	print(spystring(s))
for _ in range(int(input())):
	solve()


def check(ar1, ar2):
	c = 0
	for (x, y) in zip(ar1, ar2):
		if x != y:
			c += 1
	if c <= 1:
		return True
	else:
		return False
t = int(input())
while t > 0:
	(n, l) = map(int, input().split())
	ar = []
	ok = 0
	for i in range(n):
		ar.append(list(input()))
	for i in range(l):
		temp = [k for k in ar[0]]
		for j in range(ord('a'), ord('a') + 26):
			okk = 0
			temp[i] = chr(j)
			for pp in range(1, n):
				if check(temp, ar[pp]) == False:
					okk = 1
					break
			if okk == 0:
				ok = 1
				break
		if ok == 1:
			break
	if ok == 1:
		print(''.join(temp))
	else:
		print(-1)
	t -= 1


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		s = str(input())
		l.append(s)
	for z in range(m):
		for i in range(26):
			k = list(l[0])
			k[z] = chr(ord('a') + i)
			found = True
			for j in range(n):
				d = 0
				for x in range(m):
					if l[j][x] != k[x]:
						d += 1
				if d > 1:
					found = False
					break
			if found:
				break
		if found:
			break
	if found:
		print(''.join(k))
	else:
		print(-1)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	s = [input() for _ in range(n)]
	for i in range(m):
		v = 0
		for l in range(26):
			p = s[0][:i] + chr(97 + l) + s[0][i + 1:]
			t = 0
			for u in s:
				r = 0
				for h in range(m):
					if u[h] != p[h]:
						if r:
							t = 1
							break
						else:
							r = 1
				if t:
					break
			else:
				print(p)
				v = 1
				break
		if v:
			break
	else:
		print(-1)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def print_list(l):
	print(' '.join(map(str, l)))
from collections import defaultdict as dc

def count(a, b):
	tmp = 0
	for (i, j) in zip(a, b):
		if i != j:
			tmp += 1
	return tmp
for _ in range(N()):
	(n, m) = RL()
	data = []
	dic = [dc(int) for _ in range(m)]
	for _ in range(n):
		s = input()
		data.append(s)
		for i in range(m):
			dic[i][s[i]] += 1
	res = ''
	for i in range(m):
		flag = 0
		for c in dic[i]:
			tmp = set((s[i + 1:] for s in data if s[i] != c))
			if not tmp:
				res += c
				flag = 1
				break
			elif len(tmp) == 1:
				ss = tmp.pop()
				ff = True
				for s in data:
					if s[i] == c and count(s[i + 1:], ss) > 1:
						ff = False
				if ff:
					res += c + ss
					flag = 2
					break
		if flag != 1:
			break
	if len(res) == m:
		print(res)
	else:
		print(-1)


import sys
input = sys.stdin.readline
from sys import stdin, stdout
from collections import defaultdict, Counter
M = 10 ** 9 + 7

def main():
	for _ in range(int(input())):
		(n, m) = [int(s) for s in input().split()]
		l = [input().strip() for i in range(n)]
		s = list(l[0])
		if m == 1:
			print('a')
		else:
			for i in range(m):
				o = set()
				flag = 0
				for j in range(1, n):
					c = 0
					for k in range(m):
						if k != i:
							if s[k] != l[j][k]:
								c += 1
					if c > 1:
						flag = 1
						break
					if c == 1:
						o.add(l[j][i])
				if len(o) == 1 and flag == 0:
					s[i] = list(o)[0]
					print(''.join(s))
					break
				elif len(o) == 0 and flag == 0:
					print(''.join(s))
					break
			else:
				print(-1)
main()


from copy import deepcopy
from sys import stdin, stdout
from math import gcd, ceil, sqrt
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
mod = 1000000007
let = 'abcdefghijklmnopqrstuvwxyz'

def check(s1, s2):
	count = 0
	for (i, j) in zip(s1, s2):
		if i != j:
			count += 1
	if count > 1:
		return False
	else:
		return True
tc = ii1()
for _ in range(tc):
	(n, m) = iia()
	arr = []
	for i in range(n):
		arr.append(list(is1()))
	flag = False
	for i in range(m):
		for j in range(n):
			for aplha in let:
				cur = arr[j].copy()
				cur[i] = aplha
				for s in arr:
					if not check(s, cur):
						break
				else:
					flag = True
					print(''.join(cur))
					break
			if flag:
				break
		if flag:
			break
	if not flag:
		print('-1')


from sys import stdout
from sys import stdin

def get():
	return stdin.readline().strip()

def getf():
	return [int(i) for i in get().split()]

def put(a, end='\n'):
	stdout.write(str(a) + end)

def putf(a, sep=' ', end='\n'):
	stdout.write(sep.join(map(str, a)) + end)

def mod(s, i, x):
	s[i] = x[i]
	return s

def dist(a, b, m):
	k = 0
	p = []
	for i in range(m):
		if a[i] != b[i]:
			k += 1
			p += [i]
	return (k, p)

def solve(a, n, m):
	pt = a[0]
	p = []
	cur = 0
	for i in range(1, n):
		(z, x) = dist(pt, a[i], m)
		cur = max(cur, z)
		p += [x]
	if cur > 2:
		return [-1]
	if cur <= 1:
		return pt
	for i in range(1, n):
		if len(p[i - 1]) == 0:
			continue
		pt1 = mod(pt * 1, p[i - 1][0], a[i])
		f = True
		for j in range(n):
			if dist(pt1, a[j], m)[0] > 1:
				f = False
				break
		if f == True:
			return pt1
		f = True
		if len(p[i - 1]) == 1:
			continue
		pt2 = mod(pt * 1, p[i - 1][1], a[i])
		for j in range(n):
			if dist(pt2, a[j], m)[0] > 1:
				f = False
				break
		if f == True:
			return pt2
	return [-1]

def main():
	tests = int(get())
	for test in range(tests):
		(n, m) = getf()
		a = [list(get()) for i in range(n)]
		putf(solve(a, n, m), '')
main()


from collections import defaultdict
import sys, math
f = None
try:
	f = open('q1.input', 'r')
except IOError:
	f = sys.stdin
if 'xrange' in dir(__builtins__):
	range = xrange

def print_case_iterable(case_num, iterable):
	print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
	print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
	print(' '.join(A))

def read_int():
	return int(f.readline().strip())

def read_int_array():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def read_string():
	return list(f.readline().strip())

def bi(x):
	return bin(x)[2:]
from collections import deque

def solution(a, n, m):
	ans = []
	s = [set() for _ in range(m)]
	for i in range(n):
		for j in range(m):
			s[j].add(a[i][j])
	for i in range(m):
		if len(s[i]) == 1:
			ans.append(s[i].pop())
			continue
		for option in s[i]:
			for j in range(n):
				if a[j][i] != option:
					cand = a[j][i + 1:]
					break
			option_good = True
			for j in range(n):
				if a[j][i] == option:
					diff = 0
					sing = a[j][i + 1:]
					for l in range(len(sing)):
						if sing[l] != cand[l]:
							diff += 1
					if diff > 1:
						option_good = False
						break
				elif a[j][i + 1:] != cand:
					option_good = False
					break
			if option_good:
				return ''.join(ans) + option + ''.join(cand)
		return -1
	return ''.join(ans)

def main():
	T = read_int()
	for i in range(T):
		(n, m) = read_int_array()
		a = []
		for j in range(n):
			a.append(read_string())
		x = solution(a, n, m)
		if 'xrange' not in dir(__builtins__):
			print(x)
		else:
			(print >> output, str(x))
	if 'xrange' in dir(__builtins__):
		print(output.getvalue())
		output.close()
if 'xrange' in dir(__builtins__):
	import cStringIO
	output = cStringIO.StringIO()
main()


def check(first):
	for i in l:
		cnt = 0
		for j in range(n):
			if i[j] != first[j]:
				cnt += 1
		if cnt > 1:
			return False
	return True
for _ in range(int(input())):
	(q, n) = map(int, input().split())
	first = list(input())
	l = []
	for i in range(q - 1):
		l.append(list(input()))
	chk = check(first)
	if not chk:
		for i in l:
			for j in range(n):
				if i[j] != first[j]:
					chk = check(first[:j] + [i[j]] + first[j + 1:])
				if chk:
					first[j] = i[j]
					break
			if chk:
				break
	print(''.join(first) if chk else -1)


import sys
import math
import collections
import threading

def diffcnt(s1, s2):
	diff = 0
	for i in range(len(s1)):
		if s1[i] != s2[i]:
			diff += 1
	return diff

def main():
	(n, m) = map(int, input().split())
	a = [input() for _ in range(n)]
	if n == 1:
		print(a[0])
		return
	(z1, z2) = (a[0], a[1])
	for i in range(n):
		found = False
		for j in range(n):
			if i == j:
				continue
			if diffcnt(a[i], a[j]) == 2:
				(z1, z2) = (a[i], a[j])
				found == True
		if found:
			break
	diff = 0
	(c1, c2) = ('', '')
	for i in range(m):
		if z1[i] == z2[i]:
			c1 += z1[i]
			c2 += z2[i]
			continue
		diff += 1
		if diff > 2:
			print(-1)
			return
		if diff == 1:
			c1 += z1[i]
			c2 += z2[i]
		else:
			c1 += z2[i]
			c2 += z1[i]
	cand = [c1, c2, z1, z2]
	for c in cand:
		goodc = True
		for w in a:
			diff = 0
			for i in range(m):
				if w[i] != c[i]:
					diff += 1
			if diff > 1:
				goodc = False
				break
		if goodc:
			print(c)
			return
	print(-1)
tn = int(input())
for _ in range(tn):
	main()


import math
import sys

def diff(s1, s2, ignore):
	ans = 0
	for i in range(0, m):
		if i != ignore:
			ans += s1[i] != s2[i]
	return ans

def solve(a):
	for diff0 in range(0, m):
		s = list(a[0])
		for i in range(1, n):
			d = diff(s, a[i], diff0)
			if d > 1:
				s = None
				break
			elif d == 1:
				if diff0 < m:
					s[diff0] = a[i][diff0]
					diff0 += m
				else:
					continue
		if s is not None:
			break
	if s is None:
		return '-1'
	return ''.join(s)
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = [input() for i in range(n)]
	print(solve(a))


from sys import stdin
input = stdin.readline

def diff(a, b):
	cnt = 0
	for i in range(len(a)):
		if a[i] != b[i]:
			cnt += 1
	return cnt

def check(s, a):
	for i in a:
		if diff(s, i) > 1:
			return False
	return True
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [input() for i in range(n)]
	if check(a[0], a):
		print(a[0][:m])
		continue
	flag = 0
	for i in range(m):
		for j in range(n):
			if a[0][i] != a[j][i]:
				if check(a[0][:i] + a[j][i] + a[0][i + 1:m], a):
					print(a[0][:i] + a[j][i] + a[0][i + 1:m])
					flag = 1
					break
		if flag:
			break
	else:
		print(-1)


T = int(input())
for t in range(T):
	(n, m) = [int(i) for i in input().split()]
	l = []
	for i in range(n):
		s = input()
		l.append(s)
	flag = 1
	count = 0
	for i in range(1, n):
		count = 0
		for j in range(m):
			if l[i][j] != l[0][j]:
				count += 1
		if count > 1:
			flag = 0
			break
	if flag == 1:
		print(l[0])
	else:
		index = 0
		while index < m and flag == 0:
			flag = 1
			s = list(l[0])
			temp = []
			for i in range(n):
				count = 0
				for j in range(m):
					if j != index:
						if l[i][j] != l[0][j]:
							count += 1
							ind = j
				if count == 1:
					temp.append(l[i])
				elif count > 1:
					flag = 0
					break
			if flag == 1:
				ex = temp[0][index]
				for i in range(len(temp)):
					if temp[i][index] != ex:
						flag = 0
						break
				if flag == 1:
					s[index] = ex
					x = ''
					for i in range(m):
						x += s[i]
					print(x)
			index += 1
		if flag == 0:
			print(-1)


class Stop(Exception):
	pass
t = int(input())

def validate(s1, s2):
	s = sum((i != j for (i, j) in zip(s1, s2)))
	return s
for _ in range(t):
	(n, m) = input().split()
	(n, m) = (int(n), int(m))
	strings = [input() for _ in range(n)]
	output = ''

	def dfs(i):
		global output
		if i == m:
			print(output)
			raise Stop
		candidates = {k[i] for k in strings}
		for candidate in candidates:
			output += candidate
			mx_error = max((validate(output, s) for s in strings))
			if mx_error <= 1:
				dfs(i + 1)
			output = output[:-1]
	try:
		dfs(0)
	except Stop:
		pass
	else:
		print('-1')


from pprint import pprint
import sys
from copy import deepcopy

def do(idx, usedbuffer, s):
	if idx == m:
		print(s)
		return True
	for nextcand in range(n):
		nextused = deepcopy(usedbuffer)
		isok = True
		for i in range(n):
			if dat[i][idx] != dat[nextcand][idx]:
				if nextused[i] is True:
					isok = False
				nextused[i] = True
		if isok is False:
			continue
		ret = do(idx + 1, nextused, s + dat[nextcand][idx])
		if ret is True:
			return True
	return False
q = int(input())
for _ in range(q):
	(n, m) = map(int, input().split())
	dat = []
	used = [False] * n
	for i in range(m):
		pass
	for i in range(n):
		s = input()
		dat.append(list(s))
	res = do(0, used, '')
	if res is False:
		print(-1)


tests = int(input())
while tests > 0:
	(n, l) = list(map(int, input().split()))
	inps = []
	for i in range(n):
		inps.append(input())
	ans = inps[0]
	finalAns = '-1'
	for pos in range(l):
		for j in range(97, 123):
			ch = chr(j)
			letstr = ans[:pos] + ch + ans[pos + 1:]
			flag = True
			for curstr in inps[1:]:
				c = 0
				for (x, y) in zip(letstr, curstr):
					if x != y:
						c += 1
					if c > 1:
						flag = False
						break
				if flag == False:
					break
			if flag == True:
				finalAns = letstr
				break
	print(finalAns)
	tests -= 1


import sys
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def read():
	tc = 0
	if tc:
		input = sys.stdin.readline
	else:
		sys.stdin = open('input1.txt', 'r')
		sys.stdout = open('output1.txt', 'w')

def solve():
	for _ in range(ii()):
		(n, m) = mi()
		a = []
		for i in range(n):
			a.append(list(si()))
		f = 0
		ok = True
		for i in range(m):
			x = []
			for j in range(n):
				x.append(a[j][i])
			if len(set(x)) > 1:
				f = 1
				x = list(set(x))
				for i1 in x:
					s = ''
					c = ''
					for j1 in range(n):
						if a[j1][i] != i1:
							s = a[j1][:]
							s[i] = i1
					f1 = [0] * n
					for k in range(n):
						for k1 in range(m):
							if a[k][k1] != s[k1]:
								f1[k] += 1
					if max(f1) <= 1:
						print(''.join(s))
						ok = False
						break
				break
		if f == 0:
			print(''.join(a[0]))
		elif ok:
			print('-1')
solve()


def try_with_s(strings, s):
	N = len(strings)
	M = len(strings[0])
	for i in range(N):
		string_i = strings[i]
		diff_count = 0
		for k in range(M):
			diff_count += string_i[k] != s[k]
			if diff_count > 1:
				return False
	return True
T = int(input())
for t in range(T):
	(N, M) = list(map(int, input().split()))
	strings = []
	possible_s = ''
	for i in range(N):
		s = input()
		strings.append(s)
	if N == 1:
		print(strings[0])
	else:
		possible = True
		toto = []
		try:
			for i in range(N):
				string_i = strings[i]
				for j in range(i + 1, N):
					string_j = strings[j]
					diff_count = 0
					for k in range(M):
						diff_count += string_i[k] != string_j[k]
						if diff_count > 2:
							assert False
					toto.append((diff_count, string_i, string_j))
		except Exception:
			possible = False
		if possible:
			stoto = sorted(toto, reverse=True)
			s1 = stoto[0][1]
			s2 = stoto[0][2]
			diff_indexes = []
			for i in range(M):
				if s1[i] != s2[i]:
					diff_indexes.append(i)
			diff_count = len(diff_indexes)
			if diff_count == 0:
				possible_s = s1
			elif diff_count == 1:
				res = try_with_s(strings, s1)
				if res:
					possible_s = s1
				else:
					res = try_with_s(strings, s2)
					if res:
						possible_s = s2
			elif diff_count == 2:
				possible_s = list(s1)
				possible_s[diff_indexes[0]] = s2[diff_indexes[0]]
				possible_s = ''.join(possible_s)
				res = try_with_s(strings, possible_s)
				if not res:
					possible_s = list(s1)
					possible_s[diff_indexes[1]] = s2[diff_indexes[1]]
					possible_s = ''.join(possible_s)
					res = try_with_s(strings, possible_s)
					if not res:
						possible_s = ''
			if possible_s != '':
				print(possible_s)
			else:
				print(-1)
		else:
			print(-1)


def solution():
	(n, m) = map(lambda x: int(x), input().split())
	a = []
	for i in range(n):
		a.append(input())
	answer = list(a[0])
	for pos in range(m):
		saved_char = answer[pos]
		for letter in range(26):
			answer[pos] = chr(ord('a') + letter)
			is_wrong_letter = False
			for i in range(n):
				errors_cnt = 0
				for j in range(m):
					if answer[j] != a[i][j]:
						errors_cnt += 1
				if errors_cnt > 1:
					is_wrong_letter = True
				if is_wrong_letter:
					break
			if not is_wrong_letter:
				print(''.join(answer))
				return
		answer[pos] = saved_char
	print('-1')
t = int(input())
for _ in range(t):
	solution()


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().split())

def li():
	return list(mi())

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
mod = 1000000007
import math
import bisect
abc = 'abcdefghijklmnopqrstuvwxyz'
pi = 3.141592653589793

def comp(x, y):
	c = 0
	for i in range(len(x)):
		if x[i] != y[i]:
			c += 1
	return c

def main():
	for _ in range(ii()):
		(n, m) = mi()
		l = []
		s = ['.'] * n
		for i in range(n):
			s[i] = si()
			if i == 0:
				l.append(s[i])
		c = list(s[0])
		for i in range(m):
			for j in range(97, 123):
				c[i] = chr(j)
				c = ''.join(c)
				l.append(c)
				c = list(s[0])
		f = 0
		for i in range(len(l)):
			g = 0
			for j in range(1, n):
				x = l[i]
				y = s[j]
				z = comp(x, y)
				if z <= 1:
					g += 1
			if g == n - 1:
				ans = l[i]
				f = 1
				break
		if f:
			print(ans)
		else:
			print(-1)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from sys import stdin
from collections import deque
mod = 10 ** 9 + 7
import sys
import random
from queue import PriorityQueue
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt, factorial, gcd, log2, inf, ceil
import heapq
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
from itertools import permutations
from math import factorial as f

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p
import sys
t = int(input())
for _ in range(t):
	l = []
	(n, m) = map(int, input().split())
	la = []
	for i in range(n):
		la.append(input())
	ans = []
	for i in range(m):
		seti = []
		for j in la:
			z = j[i]
			seti.append(z)
		if len(set(seti)) == 1:
			continue
		else:
			for k in range(n):
				for ka in range(n):
					z1 = seti[k]
					z2 = la[ka][i]
					if z1 != z2:
						ans.append(la[ka][:i] + z1 + la[ka][i + 1:])
			break
	if ans == []:
		print(la[0])
	else:
		flag = 0
		final = ''
		for i in range(len(ans)):
			for j in range(n):
				cnt = 0
				for k in range(m):
					if la[j][k] != ans[i][k]:
						cnt += 1
					if cnt > 1:
						break
				if cnt > 1:
					break
			if cnt <= 1:
				final = ans[i]
				break
		if final == '':
			print(-1)
		else:
			print(final)


from sys import stdin
input = stdin.readline
for Ti in range(int(input().strip())):
	(n, m) = [int(x) for x in input().strip().split()]
	sa = []
	for ni in range(n):
		sa.append(input().strip())
	s1 = sa[0]
	val = True
	ans = ''
	for m1 in range(m):
		for ci in list('abcdefghijklmnopqrstuvwwxyz'):
			s1 = sa[0]
			s1 = s1[:m1] + ci + s1[m1 + 1:]
			val = True
			for ni in range(n):
				dc = 0
				for mi in range(m):
					if sa[ni][mi] != s1[mi]:
						dc += 1
				if dc > 1:
					val = False
					break
			if val:
				ans = s1
				break
		else:
			continue
		break
	if not ans:
		print('-1')
	else:
		print(ans)


def f(s, n, m, A):
	res = True
	for i in range(n):
		cnt = 0
		for j in range(m):
			if s[j] != A[i][j]:
				cnt += 1
		if cnt > 1:
			res = False
			break
	return res
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	A = [list(input()) for _ in range(n)]
	ans = -1
	for j in range(m):
		s = [0] * m
		for k in range(m):
			s[k] = A[0][k]
		for x in range(26):
			s[j] = chr(x + 97)
			if f(s, n, m, A):
				ans = ''.join(s)
				break
		if ans != -1:
			break
	print(ans)


import collections

def solve(n, m, sarr):

	def recur(i, fullset, sett, s):
		if i < 0:
			return s
		for (key, value) in dd[i].items():
			tset = sett - value
			if tset:
				continue
			else:
				news = s + key
				newsett = sett | fullset - value
				x = recur(i - 1, fullset, newsett, news)
				if x:
					return x
		return ''
	dd = dict()
	for j in range(m):
		dd[j] = collections.defaultdict(set)
		used = set(list('abcdefghijklmnopqrstuvwxyz'))
		for i in range(n):
			dd[j][sarr[i][j]].add(i)
			if sarr[i][j] in used:
				used.remove(sarr[i][j])
		char = list(used)[0]
		dd[j][char] = set()
	ret = recur(m - 1, set(list(range(n))), set(), '')
	if not ret:
		return '-1'
	return ret[::-1]
t = int(input())
for _ in range(t):
	inp = input().split()
	(n, m) = (int(inp[0]), int(inp[1]))
	sarr = []
	for _ in range(n):
		sarr.append(str(input()))
	print(solve(n, m, sarr))


from collections import defaultdict as dd
from collections import deque
import bisect
import heapq

def ri():
	return int(input())

def rl():
	return list(map(int, input().split()))

def solve():
	(n, m) = rl()
	S = []
	for i in range(n):
		S.append(input())

	def diff(a, b):
		d = 0
		for i in range(m):
			if a[i] != b[i]:
				d += 1
		return d

	def test(w):
		for a in S:
			if diff(a, w) > 1:
				return False
		return True
	word = ''
	for pos in range(m):
		occ = {}
		for a in S:
			occ[a[pos]] = a
		if len(occ) == 1:
			word += S[0][pos]
			continue
		for letter in occ.keys():
			for a in S:
				if a[pos] != letter:
					new_word = word + letter + a[pos + 1:]
					if test(new_word):
						print(new_word)
						return
		print(-1)
		return
	print(word)
mode = 'T'
if mode == 'T':
	t = ri()
	for i in range(t):
		solve()
else:
	solve()


from sys import stdin
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')

def chk():
	f = []
	for i in range(n):
		sum = 0
		for j in range(m):
			if s[j] != a[i][j]:
				sum += 1
		f += (sum,)
	return bool(max(f) < 2)
for _ in range(int(input())):
	(n, m) = R()
	a = []
	v = [[] for i in range(m)]
	for ss in range(n):
		a += (list(S()),)
		for i in range(m):
			v[i] += a[-1][i]
	p = a[0].copy()
	flg = True
	for i in range(m):
		s = p.copy()
		for j in range(n):
			s[i] = v[i][j]
			if chk():
				print(''.join(s))
				flg = False
				break
		if not flg:
			break
	if flg:
		print(-1)


def check(grid, n, m, s):
	for s1 in grid:
		diff = 0
		for i in range(m):
			if s[i] != s1[i]:
				diff += 1
		if diff > 1:
			return False
	return True

def solve(grid, n, m):
	s = list(grid[0])
	for col in range(m):
		for row in range(n):
			prev = s[col]
			s[col] = grid[row][col]
			if check(grid, n, m, s):
				s1 = ''
				for i in s:
					s1 += i
				return s1
			s[col] = prev
	return -1
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	lis = []
	for __ in range(n):
		lis.append(input())
	print(solve(lis, n, m))


def solve():
	for i in range(m):
		for j in range(26):
			check = spystr[0][:i] + chr(j + 97) + spystr[0][i + 1:]
			maxdiff = 0
			for k in range(n):
				diff = 0
				for l in range(m):
					if spystr[k][l] != check[l]:
						diff += 1
				maxdiff = max(diff, maxdiff)
				if diff > 1:
					break
			if maxdiff <= 1:
				return check
	return -1
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	spystr = []
	for i in range(n):
		spystr.append(input())
	print(solve())


cin = lambda : int(input())
mi = lambda : map(int, input().split())

def reduce(fn, s):
	ans = ''
	for el in s:
		ans = fn(ans, el)
	return ans
for _ in range(cin()):
	(n, m) = mi()
	s = list(input())
	a = []
	for i in range(n - 1):
		a.append(input())
	flag = False
	if a == []:
		print(reduce(lambda x, y: x + y, s))
		continue
	for i in range(m):
		lc = s[i]
		flag = True
		for el in 'abcdefghijklmnopqrstuvwxyz':
			s[i] = el
			flag = True
			for j in range(n - 1):
				ct = 0
				for k in range(m):
					if s[k] != a[j][k]:
						ct += 1
				if ct > 1:
					flag = False
					break
			if flag:
				break
		if flag:
			break
		else:
			s[i] = lc
	if flag:
		print(reduce(lambda x, y: x + y, s))
	else:
		print(-1)


def solve():
	alphas = list('abcdefghijklmnopqrstuvwxyz')
	(n, m) = map(int, input().split())
	strings = [input() for i in range(n)]
	s = strings[0]
	que = []
	for i in range(m):
		for j in range(26):
			if i == 0:
				que.append(alphas[j] + s[i + 1:])
			elif i == m - 1:
				que.append(s[:i] + alphas[j])
			else:
				que.append(s[:i] + alphas[j] + s[i + 1:])

	def judge(string):
		flag = True
		for v in strings:
			cnt = 0
			for j in range(m):
				cnt += string[j] != v[j]
			if cnt > 1:
				flag = False
				break
		return flag
	for st in que:
		if judge(st) == True:
			print(st)
			return
	print(-1)
	return

def main():
	t = int(input())
	for i in range(t):
		solve()
	return
main()


import sys
import math
import functools
input = sys.stdin.readline

def ini():
	return int(input())

def inli():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def soln():
	nm = inli()
	n = nm[0]
	m = nm[1]
	st = []
	for i in range(n):
		st.append(input()[:-1])
	for i in range(n):
		string = st[i]
		for j in range(len(st[i])):
			for x in range(97, 123):
				replace = chr(x)
				newstr = string[:j] + replace + string[j + 1:]
				flag = False
				for p in range(n):
					comp = st[p]
					diff = 0
					for t in range(m):
						if newstr[t] != comp[t]:
							diff += 1
					if diff >= 2:
						flag = True
						break
				if not flag:
					print(newstr)
					return
	print(-1)
for i in range(ini()):
	soln()


import sys
import math
import heapq
import collections

def inputnum():
	return int(input())

def inputnums():
	return map(int, input().split())

def inputlist():
	return list(map(int, input().split()))

def inputstring():
	return [x for x in input()]
t = int(input())
for q in range(t):
	(n, m) = inputnums()
	a = []
	for i in range(n):
		a.append(input())
	done = False
	alphabet = 'abcdefghijklmnopqrstuvwxyz'
	for i in range(m):
		ans = a[0]
		for j in range(26):
			ans = ans[:i] + alphabet[j] + ans[i + 1:]
			good = True
			for k in range(n):
				diff = 0
				for l in range(m):
					if a[k][l] != ans[l]:
						diff += 1
				if diff > 1:
					good = False
					break
			if good:
				print(ans)
				done = True
				break
		if done:
			break
	if done:
		continue
	else:
		print(-1)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(input())
	s = ''
	flag = 0
	flag2 = 1
	done = 0
	done_flag = 0
	for i in range(n):
		done_flag = 0
		done = 0
		flag = 0
		s = l[i]
		j = 0
		while j < n:
			cnt = 0
			for k in range(m):
				if s[k] != l[j][k]:
					cnt += 1
				if cnt == 2 and done == 0:
					s = s[:k] + l[j][k] + s[k + 1:]
					done_flag = 1
					done = 1
					cnt = 1
					continue
				if cnt == 2:
					flag = 1
					break
			if flag == 1:
				break
			j = j + 1
			if done_flag == 1:
				done_flag = 0
				j = 0
		if flag == 0:
			print(s)
			flag2 = 0
			break
	if flag2 == 1:
		print(-1)


import io, os, math

def ri():
	return int(input().strip())

def rl():
	return list(map(int, input().strip().split()))

def Check(ans, strs):
	for i in range(len(strs)):
		cnt = 0
		for j in range(len(ans)):
			if ans[j] != strs[i][j]:
				cnt += 1
		if cnt > 1:
			return False
	return True

def Solve():
	(n, m) = rl()
	strs = [input().strip() for i in range(n)]
	for i in range(n):
		if Check(strs[i], strs):
			print(strs[i])
			return
	for i in range(m):
		for j in range(0, 26):
			tmp = strs[0][:i] + chr(j + ord('a')) + strs[0][i + 1:]
			if Check(tmp, strs):
				print(tmp)
				return
	print(-1)
T = ri()
while T:
	T -= 1
	Solve()


def ok(str1, str2):
	cnt = 0
	for i in range(len(str1)):
		if str1[i] != str2[i]:
			cnt += 1
		if cnt > 1:
			return False
	return True

def solve_one(s, n, m):
	alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
	for i in range(n):
		cur = s[i].copy()
		for j in range(m):
			for k in range(len(alphabet)):
				org = cur[j]
				cur[j] = alphabet[k]
				found = True
				for u in range(n):
					if not ok(cur, s[u]):
						found = False
						break
				if found:
					result = ''.join(cur)
					return result
				cur[j] = org
	return -1

def solve():
	import sys
	alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
	t = int(input())
	while t > 0:
		nm = sys.stdin.readline().split()
		n = int(nm[0])
		m = int(nm[1])
		s = [0 for _ in range(n)]
		for i in range(n):
			inp = sys.stdin.readline().strip()
			s[i] = list(inp)
		ans = solve_one(s, n, m)
		print(ans)
		t -= 1
solve()


T = int(input())

def diff(s1, s2):
	s = 0
	for (c1, c2) in zip(s1, s2):
		if c1 != c2:
			s += 1
	return s
for t in range(T):
	(N, M) = [int(_) for _ in input().split()]
	Ss = []
	for i in range(N):
		Ss.append(input())
	impossible = False
	for i in range(N):
		for j in range(N):
			if diff(Ss[i], Ss[j]) > 2:
				impossible = True
				break
		if impossible:
			break
	if impossible:
		print(-1)
		continue
	a = []
	for i in range(M):
		candidates = list(set((Ss[k][i] for k in range(N))))
		if len(candidates) == 1:
			a.append(candidates[0])
			continue
		found = False
		for n in range(N):
			c = Ss[n][i]
			for nn in range(N):
				if Ss[nn][i] != c:
					try_a = a + [c] + [cc for cc in Ss[nn][i + 1:]]
					for nnn in range(N):
						if diff(Ss[nnn], try_a) > 1:
							break
					else:
						print(''.join(try_a))
						found = True
						break
			if found:
				break
		else:
			print(-1)
			break
		if found:
			break
	if len(a) == M:
		print(''.join(a))


import sys
from collections import defaultdict
import math
input = sys.stdin.readline

def print_result(l):
	return print(' '.join(map(str, l)))

def timer(function):
	import time

	def wrapper(*args, **kwargs):
		t1 = time.time()
		val = function()
		t2 = time.time()
		print('Executed \\{}\\ in {:.2f} seconds.'.format(function.__name__, t2 - t1))
		return val
	return wrapper

def string_to_arr(s):
	res = [x for x in s]
	return res

def is_valid(a, b):
	cnt = 0
	for i in range(len(a)):
		if a[i] != b[i]:
			cnt += 1
	return cnt <= 1

def solve():
	(n, m) = map(int, input().split(' '))
	arr = [string_to_arr(input().split('\n')[0]) for i in range(n)]
	possible = False
	(oldchr, res) = ('', '')
	for i in range(m):
		s = arr[0].copy()
		oldchr = s[i]
		for c in range(26):
			flag = False
			s[i] = chr(ord('a') + c)
			for j in range(n):
				string = arr[j]
				if not is_valid(string, s):
					flag = True
					break
			if not flag:
				possible = True
				res = s
				break
		if not possible:
			s[i] = oldchr
		else:
			break
	if not possible:
		print(-1)
	else:
		print(''.join(res))
t = int(input())
for _ in range(t):
	solve()


import sys
input = sys.stdin.readline
Q = int(input())
Query = []
for _ in range(Q):
	(n, m) = map(int, input().split())
	Ss = [list(input().rstrip()) for _ in range(n)]
	Query.append((n, m, Ss))
for (N, M, Ss) in Query:
	S1 = Ss.pop()
	ans = []
	for m in range(M):
		ok = True
		must = None
		for n in range(N - 1):
			dif = 0
			for i in range(M):
				if i != m and Ss[n][i] != S1[i]:
					dif += 1
			if dif > 1:
				ok = False
				break
			elif dif == 1:
				if not must is None and must != Ss[n][m]:
					ok = False
					break
				must = Ss[n][m]
		if ok:
			ans = S1
			if not must is None:
				ans[m] = must
			break
	if not ans:
		print(-1)
	else:
		print(''.join(ans))


t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	s = []
	for _ in range(n):
		s.append(input())
	base = s[0]

	def solve():
		for i in range(ord('a'), ord('z') + 1):
			for j in range(m):
				c = base[:j] + chr(i) + base[j + 1:]
				flag = True
				for k in range(1, n):
					if not flag:
						break
					r = 0
					for l in range(m):
						if c[l] != s[k][l]:
							r += 1
						if r > 1:
							flag = False
							break
				if flag:
					print(c)
					return
		print('-1')
	solve()


production = True
import sys, math, collections

def input(input_format=0, multi=0):
	if multi > 0:
		return [input(input_format) for i in range(multi)]
	else:
		next_line = sys.stdin.readline()[:-1]
		if input_format >= 10:
			use_list = False
			input_format = int(str(input_format)[-1])
		else:
			use_list = True
		if input_format == 0:
			formatted_input = [next_line]
		elif input_format == 1:
			formatted_input = list(map(int, next_line.split()))
		elif input_format == 2:
			formatted_input = list(map(float, next_line.split()))
		elif input_format == 3:
			formatted_input = list(next_line)
		elif input_format == 4:
			formatted_input = list(map(int, list(next_line)))
		elif input_format == 5:
			formatted_input = next_line.split()
		else:
			formatted_input = [next_line]
		return formatted_input if use_list else formatted_input[0]

def out(output_line, output_format=0, newline=True):
	formatted_output = ''
	if output_format == 0:
		formatted_output = str(output_line)
	elif output_format == 1:
		formatted_output = ' '.join(map(str, output_line))
	elif output_format == 2:
		formatted_output = '\n'.join(map(str, output_line))
	print(formatted_output, end='\n' if newline else '')

def log(*args):
	if not production:
		print('$$$', end='')
		print(*args)
enu = enumerate
ter = lambda a, b, c: b if a else c

def mapl(iterable, format=0):
	if format == 0:
		return list(map(int, iterable))
	elif format == 1:
		return list(map(str, iterable))
	elif format == 2:
		return list(map(list, iterable))

def solve():
	(n, m) = input(1)
	a = input(10, n)
	p = [chr(i) for i in range(97, 97 + 26)]
	log(a)
	for i in range(m):
		r = 0
		for c in p:
			u = a[0][:i] + c + a[0][i + 1:]
			r = 1
			for s in a[1:]:
				f = 0
				for (x, y) in zip(s, u):
					if x != y:
						f += 1
						if f > 1:
							r = 0
							break
			if r:
				out(u)
				break
		if r:
			break
	else:
		out(-1)
	return
for i in range(input(11)):
	solve()


def solve():
	(n, m) = map(int, input().split())
	s = []
	for i in range(n):
		s.append(list(input()))
	ans = s[0]
	fans = ''
	for i in range(m):
		cur = ans[i]
		for j in range(97, 123):
			ans[i] = chr(j)
			flag = 0
			for k in range(n):
				error = 0
				for l in range(m):
					if ans[l] != s[k][l]:
						error += 1
					if error > 1:
						flag = 1
						break
				if flag == 1:
					break
			if flag == 0:
				print(''.join(ans))
				return
		ans[i] = cur
	print(-1)
for _ in range(int(input())):
	solve()


from math import sqrt
alph = [chr(i) for i in range(ord('a'), ord('z') + 1)]

def dif(st1, st2):
	d = 0
	for i in range(len(st1)):
		d += st1[i] != st2[i]
	return d

def main():
	(n, m) = map(int, input().split())
	st = [list(input()) for i in range(n)]
	for i in range(m):
		src = [i for i in st[0]]
		for let in alph:
			src[i] = let
			tr = True
			for w in st:
				if dif(w, src) > 1:
					tr = False
					break
			if tr:
				print(''.join(src))
				return
	print(-1)
for t in range(int(input())):
	main()


def f(s1, s2, m):
	j = 0
	p = 0
	while j < m:
		if s1[j] != s2[j]:
			p += 1
		if p > 1:
			break
		j += 1
	if p <= 1:
		return 1
	else:
		return 0
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = []
	for j in range(n):
		s = input()
		a.append(s)
	k = a.pop()
	c = []
	for p in k:
		c.append(p)
	j = 0
	v = 0
	while j < m:
		for p in range(26):
			c[j] = chr(97 + p)
			y = 0
			for g in range(n - 1):
				if f(a[g], c, m) == 0:
					y = 1
					break
			if y == 0:
				v = 1
				break
		if v == 1:
			break
		c[j] = k[j]
		j += 1
	if v == 0:
		print(str(-1))
	else:
		print(''.join(c))


from sys import stdin, stdout
from collections import Counter, deque
from bisect import bisect_left
from itertools import product
T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	ls = [input() for _ in range(n)]
	ok = 1
	for i in range(n):
		for j in range(i + 1, n):
			cc = sum([1 if ls[i][k] != ls[j][k] else 0 for k in range(m)])
			if cc > 2:
				ok = 0
				break
		if not ok:
			break
	if not ok:
		print(-1)
		continue
	p = [set([]) for _ in range(m)]
	for s in ls:
		for i in range(m):
			p[i].add(s[i])

	def rec(r, tg, can):
		if r == m:
			can.append(''.join(tg))
			return
		for ch in p[r]:
			tg.append(ch)
			rec(r + 1, tg, can)
			tg.pop()
	(tg, can) = ([], [])
	rec(0, tg, can)
	res = ''
	for ts in can:
		for s in ls:
			cc = sum([1 if s[k] != ts[k] else 0 for k in range(m)])
			if cc > 1:
				break
		else:
			res = ts
			break
	print(res if res else -1)


def good(ans):
	for i in range(n):
		count = 0
		for j in range(m):
			if ans[j] != s[i][j]:
				count += 1
		if count > 1:
			return 0
	return 1
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	s = [0] * n
	for i in range(n):
		s[i] = input()
	ans = '-1'
	fg = 0
	for i in range(n):
		for j in range(m):
			for k in range(ord('a'), ord('z') + 1):
				temp = s[i][:j] + chr(k) + s[i][j + 1:]
				if good(temp):
					ans = temp
					fg = 1
					break
			if fg == 1:
				break
		if fg == 1:
			break
	print(ans)


from sys import stdin
inp = lambda : stdin.readline().strip()
t = int(inp())
for _ in range(t):
	(n, m) = [int(x) for x in inp().split()]
	s = []
	for i in range(n):
		s.append(inp())
	ans = list(s[0])
	sad = [0] * n
	for letter in range(m):
		for alp in range(26):
			ans[letter] = chr(97 + alp)
			sad = [0] * n
			for i in range(n):
				for j in range(m):
					if ans[j] != s[i][j]:
						sad[i] += 1
					if max(sad) > 1:
						break
				if max(sad) > 1:
					break
			if max(sad) <= 1:
				break
		if max(sad) <= 1:
			break
		ans = list(s[0])
	if max(sad) <= 1:
		print(''.join(ans))
	else:
		print(-1)


def isgood(s1, s2):
	diff = 0
	for i in range(m):
		if s1[i] != s2[i]:
			diff += 1
	return diff <= 1
for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	if n == 1:
		print(input())
		continue
	s = []
	for _ in range(n):
		s.append(list(input()))
	ans = -1
	for pos in range(m):
		for c in 'abcdefghijlkmnopqrstuvwxyz':
			ss = [e for e in s[0]]
			ss[pos] = c
			good = True
			for e in s:
				if not isgood(ss, e):
					good = False
			if good:
				ans = ''.join(ss)
	print(ans)


import math
T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	arr = []
	for i in range(n):
		arr.append(input())
	S = arr[0]
	flag = 0
	ans = ''
	for i in range(m):
		for j in range(97, 97 + 26):
			flag = 0
			Str = S[:i] + chr(j) + S[i + 1:]
			for K in arr:
				count = 0
				for z in range(m):
					if Str[z] != K[z]:
						count += 1
					if count > 1:
						flag = 1
						break
				if flag == 1:
					break
			if flag == 0:
				ans = Str
				break
		if flag == 0:
			break
	if flag == 0:
		print(ans)
	else:
		print(-1)


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect, fractions, statistics
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify, _heapify_max, _heappop_max, nsmallest, nlargest

def main():
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	tc = ri()
	for _ in range(tc):
		(n, m) = ria()
		z = []
		for i in range(n):
			z.append(rs())
		s = 'abcdefghijklmnopqrstuvwxyz'
		leh = list(z[0])
		flag = 0
		for i in range(m):
			ans = leh.copy()
			for j in range(26):
				ans[i] = s[j]
				t = 0
				for k in z:
					count = 0
					for l in range(m):
						if k[l] != ans[l]:
							count += 1
					if count <= 1:
						t += 1
				if t == n:
					flag = 1
					break
			if flag == 1:
				break
		if flag == 0:
			print(-1)
		else:
			print(''.join(ans))
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


def ok(s1, s2):
	counter = 0
	for i in range(len(s1)):
		if s1[i] != s2[i]:
			counter += 1
	if counter > 1:
		return False
	return True
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = []
	ans = -1
	for j in range(n):
		a.append(input())
	for x in range(m):
		for y in range(97, 123):
			s = a[0][:x] + chr(y) + a[0][x + 1:]
			c = 0
			for j in range(n):
				if ok(s, a[j]):
					c += 1
			if c == n:
				ans = s
	print(ans)


import math
T = int(input())

def num_diffs(m, a, b):
	ans = 0
	for i in range(m):
		if a[i] != b[i]:
			ans += 1
	return ans

def meld(m, a, b):
	idx = []
	for i in range(m):
		if a[i] != b[i]:
			idx += [i]
	[i, j] = idx
	first = list(a)
	second = list(a)
	first[i] = b[i]
	second[j] = b[j]
	return [''.join(first), ''.join(second)]

def ok(m, c, arr):
	for target in arr:
		if num_diffs(m, c, target) > 1:
			return False
	return True

def ans(n, m, arr):
	arr = list(set(arr))
	if len(arr) == 1:
		return arr[0]
	candidate = arr[0]
	for target in arr[1:]:
		if num_diffs(m, candidate, target) > 2:
			return -1
		if num_diffs(m, candidate, target) == 2:
			for c in meld(m, candidate, target):
				if ok(m, c, arr):
					return c
			return -1
	return candidate
	return '?'
for t in range(T):
	(n, m) = input().split(' ')
	(n, m) = (int(n), int(m))
	arr = []
	for i in range(n):
		arr += [input()]
	print(ans(n, m, arr))


def count(a, b, diff):
	ans = 0
	for i in diff:
		if a[i[0]] != b[i[0]]:
			ans += 1
	return ans

def solve(m, n, arr):
	diff = []
	for i in range(m):
		l = arr[0][i]
		d = []
		for j in range(1, n):
			if l != arr[j][i]:
				d.append(arr[j][i])
		if len(d) > 0:
			diff.append([i] + list(set(d)))
	if len(diff) > n:
		print(-1)
		return
	flag = True
	for j in range(1, n):
		if count(arr[0], arr[j], diff) > 1:
			flag = False
			break
	if flag:
		return arr[0]
	for i in diff:
		w = arr[0].copy()
		for x in i[1:]:
			w[i[0]] = x
			flag = True
			for j in range(1, n):
				if count(w, arr[j], diff) > 1:
					flag = False
					break
			if flag:
				return w
	print(-1)
for i in range(int(input())):
	(n, m) = map(int, input().split())
	arr = [[ord(x) - 97 for x in input()] for _ in range(n)]
	ans = solve(m, n, arr)
	if ans:
		print(''.join([chr(x + 97) for x in ans]))


def calc(s):
	alpha = 'abcdefghijklmnopqrstuvwxyz'
	r = set()
	s = list(s)
	for i in range(len(s)):
		c = s[i]
		for j in alpha:
			s[i] = j
			r.add(''.join(s))
		s[i] = c
	return r
t = int(input())
for T in range(t):
	(n, m) = [int(x) for x in input().split()]
	a = set()
	for i in range(n):
		if i == 0:
			a = calc(input())
		else:
			a = a & calc(input())
	if len(a) == 0:
		print(-1)
	else:
		print(list(a)[0])


def count_diffs(follow, word):
	assert len(follow) == len(word)
	return sum((fc != wc for (fc, wc) in zip(follow, word)))

def at_most_one_diff(follow, words_one_diff):
	diffs = [count_diffs(follow, word) for word in words_one_diff]
	return all((d <= 1 for d in diffs))

def solve(n, m, words):
	if len(set(words)) == 1:
		return words[0]
	letters = []
	for j in range(m):
		continuations = {}
		for word in words:
			continuations.setdefault(word[j], []).append(word)
		if len(continuations) == 1:
			letters.append(words[0][j])
			continue
		for (cont_char, words_one_diff) in continuations.items():
			other_conts = {w[j + 1:] for w in words if w[j] != cont_char}
			if len(other_conts) != 1:
				continue
			follow = list(other_conts)[0]
			if at_most_one_diff(follow=follow, words_one_diff=[w[j + 1:] for w in words_one_diff]):
				return ''.join([*letters, cont_char, *follow])
		return None
	assert False

def main():
	T = int(input())
	for _ in range(T):
		(n, m) = map(int, input().split())
		words = [input().strip() for _ in range(n)]
		res = solve(n, m, words)
		if res is not None:
			print(res)
		else:
			print('-1')
main()


from copy import copy
from collections import defaultdict
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ar = []
	for i in range(n):
		ar.append(input())
	s = list(ar[0])
	d = {}
	gr = False
	for i in ar:
		count = 0
		for j in range(m):
			if i[j] != s[j]:
				count += 1
		if count == 2:
			for j in range(m):
				if i[j] != s[j]:
					t = (j, i[j])
					d[t] = 1
		if count > 2:
			gr = True
			break
	if gr:
		print(-1)
		continue
	bl = False
	if len(d) == 0:
		print(''.join(s))
		continue
	temp = []
	for i in d.keys():
		v = i
		temp = copy(s)
		temp[v[0]] = v[1]
		mx = 0
		for j in ar:
			count = 0
			for k in range(m):
				if j[k] != temp[k]:
					count += 1
					mx = max(count, mx)
		if mx <= 1:
			bl = True
			break
	if bl == True:
		print(''.join(temp))
	else:
		print(-1)


def checkdiff(m, s, t):
	cnt = 0
	for i in range(m):
		if t[i] != s[i]:
			cnt += 1
	if cnt <= 1:
		return 1
	else:
		return 0

def solve():
	(n, m) = map(int, input().split())
	s = []
	for i in range(n):
		s.append(input())
	t = ['a'] * 10
	for i in range(m):
		for j in range(m):
			t[j] = s[0][j]
		for j in range(26):
			t[i] = chr(97 + j)
			cnt = 0
			for k in range(n):
				if checkdiff(m, s[k], t) == 1:
					cnt += 1
			if cnt == n:
				for k in range(m):
					print(t[k], end='')
				print()
				return
	print(-1)
for _ in range(int(input())):
	solve()


def main():
	(n, m) = list(map(int, input().split()))
	v = []
	for i in range(n):
		b = input()
		v.append(b)
	t = list(v[0])
	my_str = []
	for i in range(m):
		t[i] = '?'
		my_str.append(t)
		t = list(v[0])
	for i in range(m):
		T = True
		for j in range(1, n):
			NUL = False
			for k in range(m):
				if my_str[i][k] != v[j][k]:
					if my_str[i][k] != '?' and (not NUL):
						NUL = True
					elif my_str[i][k] != '?' and NUL:
						T = False
			if NUL and my_str[i][i] == '?':
				my_str[i][i] = v[j][i]
		if my_str[i][i] == '?':
			my_str[i][i] = 'z'
		if T:
			s = ''
			for j in my_str[i]:
				s += j
			print(s)
			return 0
	print(-1)
a = int(input())
for i in range(a):
	main()


T = int(input())
alps = [chr(i) for i in range(97, 97 + 26)]
for _ in range(T):
	(N, M) = list(map(int, input().split()))
	ss = [input() for _ in range(N)]
	dp = [[-1] * (1 << N) for _ in range(M + 1)]
	dp[0] = [''] * (1 << N)
	for i in range(M):
		for bit in range(1 << N):
			if dp[i][bit] == -1:
				continue
			for a in alps:
				change = 0
				for (j, s) in enumerate(ss):
					if s[i] == a:
						change += 1 << j
				if bit | change != (1 << N) - 1:
					continue
				else:
					dp[i + 1][bit & change] = dp[i][bit] + a
	for d in dp[-1]:
		if d != -1:
			print(d)
			break
	else:
		print(-1)


import sys
import string
strInp = lambda : input().strip().split()
intInp = lambda : list(map(int, strInp()))
atoz = list(string.ascii_lowercase)
for t in range(int(input())):
	(n, m) = intInp()
	all = []
	for i in range(n):
		all.append(list(input()))
	changeStr = all.pop()
	for i in range(len(changeStr)):
		for char in atoz:
			testStr = [] + changeStr
			testStr[i] = char
			ans = False
			for arrStr in all:
				matchDiff = 0
				for j in range(len(arrStr)):
					if arrStr[j] != testStr[j]:
						matchDiff += 1
				if matchDiff > 1:
					break
			else:
				ans = True
			if ans == True:
				break
		if ans == True:
			break
	if ans == True:
		for i in testStr:
			print(i, end='')
		print()
	else:
		print(-1)


import io
import os
from collections import Counter, defaultdict, deque
from itertools import product, chain

def solve(N, M, A):
	letters = [set() for i in range(M)]
	for (i, w1) in enumerate(A):
		for j in range(i + 1, N):
			w2 = A[j]
			numDiff = 0
			for k in range(M):
				if w1[k] != w2[k]:
					numDiff += 1
					letters[k].add(w1[k])
					letters[k].add(w2[k])
			if numDiff > 2:
				return -1
			if numDiff == 0:
				letters[k].add(w1[k])
	for i in range(M):
		if not letters[i]:
			letters[i].add(A[0][i])
	for w1 in product(*letters):
		bad = False
		for w2 in A:
			numDiff = sum((1 for (x, y) in zip(w1, w2) if x != y))
			if numDiff > 1:
				bad = True
				break
		if not bad:
			return ''.join(w1)
	return -1
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
	(N, M) = [int(x) for x in input().split()]
	A = [input().decode().rstrip() for i in range(N)]
	ans = solve(N, M, A)
	print(ans)


from collections import defaultdict

def check(ans):
	for i in range(n):
		diff = 0
		for j in range(m):
			if arr_str[i][j] != ans[j]:
				diff += 1
		if diff >= 2:
			return False
	return True

def solve():
	for i in range(n):
		for j in range(m):
			(ans, a) = (arr_str[i].copy(), ord('a'))
			for char in range(a, a + 26):
				ans[j] = chr(char)
				if check(ans):
					return ''.join(ans)
	return -1
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	arr_str = defaultdict(list)
	for i in range(n):
		arr_str[i] = list(input())
	print(solve())


from collections import defaultdict
from sys import stdin, stdout

def check(ans):
	for i in range(n):
		diff = 0
		for j in range(m):
			if arr_str[i][j] != ans[j]:
				diff += 1
		if diff >= 2:
			return False
	return True

def solve():
	for i in range(n):
		for j in range(m):
			(ans, a) = (arr_str[i].copy(), ord('a'))
			for char in range(a, a + 26):
				ans[j] = chr(char)
				if check(ans):
					return ''.join(ans)
	return None
t = int(stdin.readline())
for _ in range(t):
	(n, m) = map(int, stdin.readline().split())
	arr_str = defaultdict(list)
	for i in range(n):
		arr_str[i] = list(stdin.readline())
	ans = solve()
	if ans == None:
		stdout.write('-1' + '\n')
	else:
		stdout.write(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [input() for _ in range(n)]
	cns = [([0] * n, '')]
	for j in range(m):
		d = {}
		for i in range(n):
			d[a[i][j]] = d.get(a[i][j], []) + [i]
		ncns = []
		for c in d:
			for (cn, cur) in cns:
				nc = cn.copy()
				for i in range(n):
					nc[i] += 1
				for x in d[c]:
					nc[x] -= 1
				if 2 in nc:
					continue
				ncns.append((nc, cur + c))
		cns = ncns
	if not cns:
		print(-1)
	else:
		print(cns[0][1])


import math
import sys
import bisect
from collections import defaultdict, Counter, deque
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda : map(int, input().split())
alele = lambda : list(map(int, input().split()))

def Y(c):
	print(['NO', 'YES'][c])

def y(c):
	print(['no', 'yes'][c])

def check(A, s):
	for i in A:
		c = 0
		for (j, k) in zip(i, s):
			if j != k:
				c += 1
		if c >= 2:
			return False
	return True
for _ in range(int(input())):
	(n, m) = ilele()
	A = []
	for i in range(n):
		S = input()
		A.append([*S])
	B = list(zip(*A))
	j = -1
	k = None
	for i in B:
		j += 1
		C = list(i)
		if len(set(C)) != 1:
			D = list(set(C))
			k = j
			break
	if k == None:
		print(''.join(A[0]))
	else:
		flag = 0
		for i in D:
			for j in range(len(A)):
				s = ''.join(A[j][:k]) + i + ''.join(A[j][k + 1:])
				if check(A, s):
					flag = 1
					break
			if flag == 1:
				break
		if flag == 1:
			print(s)
		else:
			print(-1)


import sys
input = sys.stdin.readline

def print(val):
	sys.stdout.write(str(val) + '\n')
from string import ascii_lowercase as L

def prog():
	for _ in range(int(input().strip())):
		(n, m) = map(int, input().split())
		strings = [input().strip() for i in range(n)]
		if n == 1:
			print(strings[0])
		else:
			worked = False
			a = strings.pop()
			for i in range(1, m + 1):
				if worked:
					break
				for char in L:
					fail = False
					if i < m:
						new = a[:i - 1] + char + a[i:]
					else:
						new = a[:i - 1] + char
					for string in strings:
						diff = 0
						for j in range(m):
							if string[j] != new[j]:
								diff += 1
						if diff > 1:
							fail = True
							break
					if not fail:
						worked = True
						output = new
						break
			if worked:
				print(output)
			else:
				print(-1)
prog()


def sol(s1, s2):
	n = len(s1)
	c = 0
	p1 = -1
	p2 = -1
	for i in range(n):
		if s1[i] != s2[i]:
			c += 1
			if c == 1:
				p1 = i
			if c == 2:
				p2 = i
		if c > 2:
			return (-1, p1, p2)
	return (c, p1, p2)
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	lis = []
	for i in range(n):
		lis.append(input())
	for i in range(n):
		f = 0
		s = lis[i]
		d = 0
		j = 0
		while j < n:
			if i != j:
				(val, p1, p2) = sol(s, lis[j])
				if val == -1:
					f = 1
					break
				elif val == 2:
					if d == 0:
						s1 = lis[i][:p1] + lis[j][p1] + lis[i][p1 + 1:]
						if p2 != m - 1:
							s2 = lis[i][:p2] + lis[j][p2] + lis[i][p2 + 1:]
						else:
							s2 = lis[i][:p2] + lis[j][p2]
						s = s1
						j = -1
					elif d == 1:
						s = s2
						j = -1
					else:
						f = 1
						break
					d += 1
			j += 1
		if f == 0:
			print(s)
			break
	if f:
		print(-1)


import sys

def input():
	return sys.stdin.readline().rstrip()
dxy = ((-1, 0), (0, -1), (1, 0), (0, 1))

def almost_same(str_s, str_t):
	assert len(str_s) == len(str_t)
	cnt = 0
	for i in range(len(str_s)):
		cnt += str_s[i] != str_t[i]
	return cnt <= 1

def slv():
	(n, m) = map(int, input().split())
	Ss = [input() for i in range(n)]
	str_s = Ss[0]
	for i in range(m):
		for str_i in range(26):
			char = chr(ord('a') + str_i)
			comp_s = str_s[:i] + char + str_s[i + 1:]
			if all((almost_same(comp_s, comp_r) for comp_r in Ss)):
				print(comp_s)
				return
	print(-1)
	return

def main():
	t = int(input())
	for _ in range(t):
		slv()
	return
main()


import sys

def check(str1, str2):
	k = 0
	for (i, sim) in enumerate(str1):
		if sim != str2[i]:
			k += 1
	return k

def main():
	res = ''
	input = sys.stdin.readline
	print = sys.stdout.write
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, input().split())
		strings = []
		for _ in range(n):
			s = input()
			if len(s) != m:
				s = s[:m]
			strings.append(s)
		kk = []
		sub_res = strings[0]
		k2 = ''
		for i in range(1, n):
			kk.append(check(strings[0], strings[i]))
			if kk[-1] > 2:
				sub_res = '-1'
				break
			elif kk[-1] == 2:
				k2 = i
		if sub_res != '-1' and k2 != '':
			for i in range(m):
				if strings[0][i] != strings[k2][i]:
					break
			str1 = strings[0][:i + 1] + strings[k2][i + 1:]
			str2 = strings[k2][:i + 1] + strings[0][i + 1:]
			ss = True
			for i in range(n):
				if check(str1, strings[i]) > 1:
					ss = False
					break
			if ss:
				sub_res = str1
			else:
				ss = True
				for i in range(n):
					if check(str2, strings[i]) > 1:
						ss = False
						break
				if ss:
					sub_res = str2
				else:
					sub_res = '-1'
		res += sub_res + '\n'
	print(res)
main()


def diff(a, b, m):
	d = 0
	for i in range(0, m):
		if a[i] != b[i]:
			d += 1
	return d
t = input()
for t in range(int(t)):
	nm = input().split()
	n = int(nm[0])
	m = int(nm[1])
	a = []
	check = 1
	for i in range(n):
		inp = input()
		a.append(inp)
	for ch in range(m):
		for i in range(26):
			if check:
				tt = list(a[0])
				tt[ch] = chr(97 + i)
				temp = ''.join(tt)
				f = 1
				for ll in range(1, n):
					if diff(temp, a[ll], m) > 1:
						f = 0
						break
				if f:
					check = 0
					print(temp)
	if check:
		print(-1)


from functools import lru_cache

def solve():

	@lru_cache(maxsize=None)
	def recurse(j, diff):
		if j >= m:
			return ''
		cand = set()
		for i in range(n):
			if diff[i]:
				cand.add(arr[i][j])
		if len(cand) > 1:
			return None
		if len(cand) == 0:
			for i in range(n):
				cand.add(arr[i][j])
		for c in cand:
			newdiff = list(diff)
			for i in range(n):
				if c != arr[i][j]:
					newdiff[i] = True
			ret = recurse(j + 1, tuple(newdiff))
			if ret is not None:
				return c + ret
		return None
	(n, m) = [int(x) for x in input().split()]
	arr = []
	for i in range(n):
		arr.append(input())
	diff = tuple([False for i in range(n)])
	ret = recurse(0, diff)
	if ret is None:
		print(-1)
	else:
		print(ret)
	return
t = int(input())
while t > 0:
	t = t - 1
	solve()


for case in range(int(input())):
	(n, m) = [int(x) for x in input().split()]
	series = []
	tests = []
	for i in range(n):
		series.append([x for x in input()])
	tests.append([x for x in series[0]])
	for i in range(m):
		temp = [x for x in series[0]]
		temp[i] = '*'
		tests.append(temp)
	ans_found = False
	ans = ''
	for parent in tests:
		possible = []
		if '*' in parent:
			i = parent.index('*')
			for l in 'qwertyuioplkjhgfdsazxcvbnm':
				temp = [x for x in parent]
				temp[i] = l
				possible.append(temp)
		else:
			possible.append(parent)
		for p in possible:
			score = 0
			for s in series:
				k = 0
				for i in range(m):
					if p[i] == s[i]:
						k += 1
				if k >= m - 1:
					score += 1
			if score == n:
				ans_found = True
				ans = p
				break
	if ans_found:
		print(''.join(ans))
	else:
		print(-1)


from sys import stdin, stdout
for case in range(int(stdin.readline())):
	(n, m) = [int(x) for x in stdin.readline().split()]
	words = []
	for a in range(n):
		words.append(stdin.readline().strip())
	realGood = -1
	for q in range(n):
		char = [x for x in words[q]]
		free1 = True
		constant = (-1, -1)
		valid = True
		change = set()
		for word in words:
			free2 = True
			for c in range(len(word)):
				if word[c] != char[c]:
					if free2:
						free2 = False
						change.add(c)
					elif free1:
						free1 = False
						if len(change) <= 1:
							for a in change:
								x = a
							char[x] = word[x]
						else:
							valid = False
					else:
						valid = False
		if valid:
			if constant != (-1, -1):
				char[constant[0]] = constant[1]
			out = ''
			for a in char:
				out += a
			realGood = out
	print(realGood)


import copy
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	strings = []
	for _ in range(n):
		strings.append(input())
	candidate = strings[0]
	successful = False
	for i in range(m):
		for j in range(26):
			candidate = candidate[:i] + chr(ord('a') + j) + candidate[i + 1:]
			doesItWork = True
			for k in range(1, n):
				distanceCount = 0
				for l in range(m):
					if candidate[l] != strings[k][l]:
						distanceCount += 1
				if distanceCount >= 2:
					doesItWork = False
					break
			if doesItWork:
				successful = True
				break
			candidate = candidate[:i] + strings[0][i] + candidate[i + 1:]
		if successful:
			break
	if successful:
		print(candidate)
	else:
		print(-1)


T = int(input())
for _ in range(T):
	(n, m) = list(map(int, input().split()))
	a = []
	for _ in range(n):
		s = input()
		a.append(s)
	valid = True
	b = [s for s in a]
	for i in range(n):
		for j in range(n):
			if j == i:
				continue
			pos = []
			for k in range(m):
				if a[i][k] != a[j][k]:
					pos.append(k)
			if len(pos) > 2:
				valid = False
				break
			else:
				for p in pos:
					t = a[i][:p] + a[j][p] + a[i][p + 1:]
					b.append(t)
		if not valid:
			break
	ans = '-1'
	for s in b:
		valid = True
		for i in range(n):
			cnt = 0
			for k in range(m):
				if s[k] != a[i][k]:
					cnt += 1
					if cnt >= 2:
						valid = False
						break
			if not valid:
				break
		if valid:
			ans = s
			break
	print(ans)


alph = 'abcdefghijklmnopqrstuvwxyz'
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	s = [input() for i in range(n)]
	for i in range(m):
		for char in alph:
			cand = s[0][0:i] + char + s[0][i + 1:]
			flag = False
			for j in range(n):
				cnt = 0
				for k in range(m):
					if cand[k] != s[j][k]:
						cnt += 1
				if cnt > 1:
					flag = True
			if not flag:
				print(cand)
				break
		else:
			continue
		break
	else:
		print(-1)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(input())
	for i in range(m):
		ans = [''] * m
		for j in range(m):
			if j != i:
				ans[j] = a[0][j]
		flag = True
		for j in range(1, n):
			check = 0
			for k in range(m):
				if ans[i] == '':
					if ans[k] != a[j][k] and k != i:
						check += 1
				elif ans[k] != a[j][k]:
					check += 1
			if ans[i] == '':
				if check > 1:
					flag = False
				elif check == 1:
					ans[i] = a[j][i]
			elif check > 1:
				flag = False
		if flag:
			if ans[i] == '':
				ans[i] = 'a'
				print(''.join(ans))
			else:
				print(''.join(ans))
			break
	else:
		print(-1)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	first = input()
	words = dict()
	for i in range(m):
		for j in range(26):
			key = first[:i] + chr(97 + j) + first[i + 1:]
			words[key] = 0
	for i in range(1, n):
		word = input()
		for x in words:
			t = 0
			for j in range(m):
				if word[j] != x[j]:
					t += 1
			if t <= 1:
				words[x] += 1
	for x in words:
		if words[x] == n - 1:
			print(x)
			break
	else:
		print(-1)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	arr = []
	for i in range(n):
		arr.append(list(input().strip()))
	ans = arr[0]
	found = False
	c = list('qwertyuiopasdfghjklzxcvbnm')
	for i in c:
		if found:
			break
		for j in range(m):
			if found:
				break
			prev_val = ans[j]
			ans[j] = i
			cur_ans = True
			for k in range(n):
				cnt = 0
				for l in range(m):
					if arr[k][l] != ans[l]:
						cnt += 1
						if cnt > 1:
							break
				if cnt > 1:
					cur_ans = False
					break
			if cur_ans:
				print(''.join(ans))
				found = True
				break
			else:
				ans[j] = prev_val
	if not found:
		print(-1)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time
inf = 10 ** 20
mod = 10 ** 9 + 7

def LI():
	return list(map(int, input().split()))

def II():
	return int(input())

def LS():
	return list(input().split())

def S():
	return input()

def solve():
	(n, m) = LI()
	ss = [S() for _ in range(n)]
	s = list(ss[0])
	for i in range(m):
		for c in string.ascii_lowercase:
			ans = s.copy()
			ans[i] = c
			for j in range(1, n):
				flag = False
				for k in range(m):
					if ans[k] == ss[j][k]:
						continue
					if flag:
						ans = '-1'
						break
					flag = True
				if ans == '-1':
					break
			if ans != '-1':
				return ans
	return ans

def main():
	t = II()
	res = list()
	for _ in range(t):
		ans = solve()
		res.append(ans)
	for ans in res:
		print(''.join(ans))
	return 0
main()


def diff(s1, s2):
	count = 0
	for i in range(m):
		if s1[i] != s2[i]:
			count += 1
	return count
for nt in range(int(input())):
	(n, m) = map(int, input().split())
	s = []
	for i in range(n):
		s.append(input())
	flag = 0
	ans = -1
	for i in range(m):
		for j in range(26):
			a = s[0][0:i] + chr(j + 97) + s[0][i + 1:]
			f = 0
			for k in s:
				if diff(a, k) >= 2:
					f = 1
					break
			if not f:
				flag = 1
				break
		if flag:
			break
	if flag:
		print(a)
	else:
		ans = s[0]
		for k in s:
			if diff(k, s[0]) >= 2:
				ans = -1
				break
		print(ans)


import sys
import heapq
import random
import collections
from functools import lru_cache

def solve(grid):

	@lru_cache(maxsize=None)
	def test_string(test):
		for strn in grid:
			if sum([1 for (a, b) in zip(test, strn) if a != b]) > 1:
				return False
		return True
	for strn in grid:
		for (i, s) in enumerate(strn):
			for other in grid:
				test = strn[:i] + other[i] + strn[i + 1:]
				if test_string(test):
					return test
	return -1

def console(*args):
	print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)
	return
for case_num in range(int(input())):
	(nrows, _) = list(map(int, input().split()))
	grid = []
	for _ in range(nrows):
		grid.append(input())
	res = solve(grid)
	print(res)


from sys import stdin
T = int(input())
while T:
	(n, m) = map(int, input().split())
	arr = []
	for i in range(n):
		arr.append(stdin.readline())
	output = '-1'
	flag = True
	for i in range(m):
		temp = list(arr[0])
		for j in range(26):
			ch = chr(ord('a') + j)
			temp[i] = ch
			flag = True
			for val in arr:
				count = 0
				for pos in range(m):
					if temp[pos] != val[pos]:
						count += 1
				if count > 1:
					flag = False
					break
			if flag:
				output = ''.join(temp)
				break
		if flag:
			break
	print(output.rstrip())
	T -= 1


from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect
import math
import heapq
import sys
import io, os
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for ii in range(int(input())):
	f = 0
	(n, m) = map(int, input().split())
	arr = [list(input()) for i in range(n)]
	for i in range(m):
		temp = arr[0][:]
		for c in alphabet:
			temp[i] = c
			ok = 1
			for j in range(n):
				temp2 = arr[j]
				diff = 0
				for itr in range(m):
					if temp[itr] != temp2[itr]:
						diff += 1
					if diff > 1:
						ok = 0
						break
				if not ok:
					break
			if ok:
				print(''.join(temp))
				f = 1
				break
		if f:
			break
	if not f:
		print(-1)


import sys
import os
import heapq
import math
try:
	path = './file/input.txt'
	if os.path.exists(path):
		sys.stdin = open(path, 'r')
except:
	pass
t = int(input())

def printd(value):
	pass
for _ in range(t):
	arr = list(map(int, input().split(' ')))
	(n, m) = (arr[0], arr[1])
	a = []
	for _ in range(n):
		a.append(input())
	result = -1
	for i in range(m):
		success = True
		chars = []
		for row in range(1, n):
			count = 0
			for pos in range(m):
				if pos != i:
					if a[0][pos] != a[row][pos]:
						count += 1
			if count > 1:
				success = False
				break
			elif count == 1:
				if a[row][i] not in chars:
					chars.append(a[row][i])
		if not success:
			continue
		if len(chars) == 1:
			result = a[0]
			result = result[0:i] + chars[0] + result[i + 1:]
			break
		elif len(chars) == 0:
			result = a[0]
			break
	print(result)


def inp():
	return int(input())

def inlt():
	l = input().split()
	for i in range(len(l)):
		l[i] = int(l[i])
	return l

def insr():
	s = input()
	return list(s[:len(s)])

def s_to_int(a):
	for i in range(len(a)):
		a[i] = int(a[i])

def factors(n):
	res = []
	t = 1
	while t * t <= n:
		if t * t == n:
			res.append(t)
		if n % t == 0:
			res.append(t)
			res.append(n // t)
		t += 1
	res.sort()
	return res

def compact_factors(n):
	res = []
	t = 2
	while n != 1 and t * t <= n:
		cnt = 0
		while n % t == 0:
			cnt += 1
			n //= t
		if cnt != 0:
			res.append([t, cnt])
		t += 1
	if n > 1:
		res.append([n, 1])
	return res

def binary_search(l, target, lp, rp):
	mid = (lp + rp) // 2
	if l[mid] == target:
		return mid
	elif l[mid] > target:
		binary_search(l, target, lp, mid - 1)
	elif l[mid] < target:
		binary_search(l, target, mid + 1, rp)
	elif lp >= rp:
		return -1
n = inp()
for i in range(n):
	l = inlt()
	m = l[0]
	length = l[1]
	words = []
	dp = []
	dif = [1] * m
	dp.append(['', dif])
	for j in range(m):
		words.append(insr())
	for j in range(length):
		d = {}
		for k in range(m):
			if words[k][j] not in d:
				d[words[k][j]] = [k]
			else:
				d[words[k][j]].append(k)
		dp2 = []
		for k in range(len(dp)):
			for x in d:
				flag = 1
				new_diff = list(dp[k][1])
				for z in range(m):
					if z not in d[x] and dp[k][1][z] == 0:
						flag = 0
						break
					elif z not in d[x] and dp[k][1][z] == 1:
						new_diff[z] = 0
				if flag:
					dp2.append([dp[k][0] + x, new_diff])
		dp = list(dp2)
	if len(dp) == 0:
		print(-1)
	else:
		print(dp[0][0])


import sys

def input():
	return sys.stdin.readline()[:-1]

def diff(s, t):
	ret = 0
	for k in range(len(s)):
		if s[k] != t[k]:
			ret += 1
	return ret

def main():
	T = 'abcdefghijklmnopqrstuvwxyz'
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		s = [input() for i in range(n)]
		ans = '_'
		for k in range(m):
			for e in T:
				temp = s[0][:k] + e + s[0][k + 1:]
				f = 1
				for t in s:
					if diff(temp, t) > 1:
						f = 0
						break
				if f == 1:
					ans = temp
		print(-1 if ans == '_' else ans)
main()


s = []

def okay():
	for i in range(n):
		cnt = 0
		for j in range(m):
			if ans[j] != s[i][j]:
				cnt += 1
		if cnt > 1:
			return False
	return True
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	s = [input() for i in range(n)]
	ans = list(s[0])
	Found = False
	for i in range(n):
		if not Found:
			for j in range(m):
				temp = ans[j]
				ans[j] = s[i][j]
				if okay():
					print(''.join(ans))
					Found = True
					break
				ans[j] = temp
	if not Found:
		print(-1)


for T in range(int(input())):
	(n, m) = [int(x) for x in input().split()]
	arr = []
	for i in range(n):
		arr.append(list(input()))
	if n == 1:
		print(*arr[0], sep='')
		continue
	first = arr[0]
	done = 0
	for i in range(m):
		prev = first[i]
		for j in range(97, 97 + 26):
			ch = chr(j)
			first[i] = ch
			bad = 0
			for k in range(1, n):
				bad = 0
				for pos in range(m):
					if first[pos] != arr[k][pos]:
						bad += 1
						if bad > 1:
							break
				if bad > 1:
					break
			if bad > 1:
				continue
			else:
				print(*first, sep='')
				done = 1
				break
		if done:
			break
		else:
			first[i] = prev
	if not done:
		print(-1)


def check(s, tmp):
	k = 0
	for i in range(len(s)):
		if s[i] != tmp[i]:
			k += 1
	return k < 2
for mda in range(int(input())):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(input())
	ans = ''
	for i in range(m):
		for num in range(26):
			ok = True
			s = a[0][:i] + chr(ord('a') + num) + a[0][i + 1:]
			for j in range(1, n):
				if check(a[j], s) == False:
					ok = False
					break
			if ok == True:
				ans = s
				break
		if len(ans) > 0:
			break
	if len(ans) > 0:
		print(ans)
	else:
		print(-1)


def f(a):
	for i in range(m):
		for j in range(26):
			b = a[0:i] + chr(ord('a') + j) + a[i + 1:m]
			ans = 1
			for k in range(N):
				if check(b, n[k]) > 1:
					ans = 0
					break
			if ans:
				print(b)
				return
	print(-1)
	return

def check(a, b):
	k = 0
	for i in range(len(a)):
		if a[i] != b[i]:
			k += 1
	return k
t = int(input())
for i in range(t):
	(N, m) = list(map(int, input().split()))
	n = []
	for i in range(N):
		n.append(input())
	f(n[0])


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	chararr = []
	for i in range(n):
		s = input()
		chararr.append(s)
	flagmain = 1
	finstring = list(chararr[0])
	for i in range(m):
		charsaved = finstring[i]
		for j in range(26):
			finstring[i] = chr(97 + j)
			flag = True
			for k in range(n):
				counts = 0
				for l in range(m):
					if chararr[k][l] != finstring[l]:
						counts += 1
				if counts > 1:
					flag = False
					break
			if flag == True:
				print(''.join(finstring))
				flagmain = 0
				break
		if flagmain == 0:
			break
		finstring[i] = charsaved
	if flagmain:
		print(-1)


t = int(input())
while t:
	t -= 1
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(input())
	f = 0
	for i in range(m):
		x = []
		for j in range(m):
			x.append(l[0][j])
		for j in range(26):
			x[i] = chr(97 + j)
			c = 0
			for k in range(n):
				c1 = 0
				for y in range(m):
					if x[y] != l[k][y]:
						c1 += 1
				if c1 <= 1:
					c += 1
			if c == n:
				for k in range(m):
					f = 1
					print(x[k], end='')
				print()
				break
		if f == 1:
			break
	if f == 0:
		print(-1)


def diff(a, b):
	d = 0
	for i in range(len(a)):
		if a[i] != b[i]:
			d += 1
	return d
for i in range(int(input())):
	(n, m) = map(int, input().split())
	strings = [input() for _ in range(n)]
	ans = list(strings[0])
	find = True
	for j in range(m):
		ans = list(strings[0])
		for k in range(26):
			ans[j] = chr(ord('a') + k)
			count = 0
			for s in strings:
				if diff(ans, s) <= 1:
					count += 1
			if count == n:
				find = False
				break
		if not find:
			break
	if not find:
		print(''.join(ans))
	else:
		print(-1)


alph = list('abcdefghijklmnopqrstuvwxyz')
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	ss = []
	for _ in range(n):
		s = list(input())
		ss.append(s)
	ansExist = False
	origin = False
	for i in range(n):
		flg = True
		for j in range(n):
			if j != i:
				cnt = 0
				for k in range(m):
					if ss[i][k] != ss[j][k]:
						cnt += 1
						if cnt > 1:
							flg = False
							break
				if not flg:
					break
		if flg:
			origin = True
			ansExist = True
			print(''.join(ss[i]))
			break
	if not origin:
		for i in range(m):
			ans = ['' for _ in range(m)]
			for j in range(m):
				ans[j] = ss[0][j]
			thisPos = False
			for a in alph:
				if a != ss[0][i]:
					ans[i] = a
				flg = True
				for j in range(1, n):
					cnt = 0
					for k in range(m):
						if ans[k] != ss[j][k]:
							cnt += 1
							if cnt > 1:
								flg = False
								break
					if not flg:
						break
				if flg:
					thisPos = True
					ansExist = True
					print(''.join(ans))
					break
			if thisPos:
				break
	if not ansExist:
		print(-1)


import sys
input = lambda : sys.stdin.readline().strip('\r\n')
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [input() for _ in range(n)]
	is_ans = False
	for i in range(m):
		for c in range(26):
			ans = list(a[0])
			ans[i] = chr(c + ord('a'))
			is_ans = True
			for j in range(n):
				diff = 0
				for k in range(m):
					if ans[k] != a[j][k]:
						diff += 1
					if diff > 1:
						is_ans = False
						break
			if is_ans:
				break
		if is_ans:
			break
	if is_ans:
		print(''.join(ans))
	else:
		print(-1)


import sys
from collections import Counter
from typing import List

def solve(n: int, m: int, a: List[str]):

	def find(s: str, idx: int, diffs: List[int]):
		if idx == m:
			return s
		c = Counter()
		for i in range(n):
			c[a[i][idx]] += 1
		sorted_by_occurrences = c.most_common()
		(most_common_chr, most_common_cnt) = sorted_by_occurrences[0]
		for (chr, cnt) in sorted_by_occurrences:
			for i in range(n):
				if a[i][idx] != chr:
					diffs[i] += 1
			if all((diffs[i] <= 1 for i in range(n))):
				r = find(s + chr, idx + 1, diffs)
				if r != -1:
					return r
			for i in range(n):
				if a[i][idx] != chr:
					diffs[i] -= 1
		return -1
	return find('', 0, [0 for _ in range(n)])
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [input() for _ in range(n)]
	r = solve(n, m, a)
	print(r)


import string
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	s = [input() for _ in range(n)]
	totry = string.ascii_lowercase
	for i in range(m):
		t1 = 0
		for l in totry:
			ans = s[0][:i] + l + s[0][i + 1:]
			t = 0
			for st in s:
				r = 0
				for tr in range(m):
					if st[tr] != ans[tr]:
						if r:
							t = 1
							break
						else:
							r += 1
				if t:
					break
			else:
				print(ans)
				t1 = 1
				break
		if t1:
			break
	else:
		print(-1)


def ok(a, b):
	ans = 0
	for i in range(len(a)):
		if a[i] != b[i]:
			ans += 1
	if ans <= 1:
		return True
	return False
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	S = []
	for i in range(n):
		s = input()
		S.append(s)
	d = list(S[0])
	A = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
	o = 0
	for i in S:
		if ok(d, i):
			o += 1
	if o == n:
		for i in d:
			print(i, end='')
		print()
		continue
	flag = False
	for i in range(m):
		for j in A:
			ans = 0
			p = d[i]
			if d[i] != j:
				d[i] = j
				for g in range(1, n):
					if ok(d, S[g]):
						ans += 1
			if ans == n - 1:
				flag = True
				break
			else:
				d[i] = p
		if flag == True:
			break
	if flag:
		for i in d:
			print(i, end='')
		print()
	else:
		print('-1')


from string import ascii_lowercase
t = int(input())

def solve(n, m, words):

	def neighbors(word):
		ans = {word}
		for i in range(m):
			for c in ascii_lowercase:
				ans.add(word[:i] + c + word[i + 1:])
		return ans
	intersection = neighbors(words[0])
	for i in range(1, n):
		intersection &= neighbors(words[i])
	if not intersection:
		return '-1'
	return intersection.pop()
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	arr = []
	for _ in range(n):
		arr.append(input())
	print(solve(n, m, arr))


t = int(input())
al = [chr(ord('a') + i) for i in range(26)]
for _ in range(t):
	(n, m) = map(int, input().split())
	if n == 1:
		print(input())
		continue
	s = list({input() for i in range(n)})
	n = len(s)
	if n == 1:
		print(s[0])
		continue
	a = set()
	x = [''] * m
	cnt = 0
	for i in range(m):
		if s[0][i] == s[1][i]:
			x[i] = s[0][i]
			cnt += 1
	if cnt == m - 1:
		p = ''
		q = ''
		f = 1
		for i in range(m):
			if x[i] == '':
				f = 0
			elif f:
				p += x[i]
			else:
				q += x[i]
		for i in al:
			a.add(p + i + q)
	elif cnt == m - 2:
		q = []
		for i in range(m):
			if x[i] == '':
				q.append(i)
		a.add(s[0][:q[0]] + s[0][q[0]] + s[0][q[0] + 1:q[1]] + s[1][q[1]] + s[0][q[1] + 1:])
		a.add(s[0][:q[0]] + s[1][q[0]] + s[0][q[0] + 1:q[1]] + s[0][q[1]] + s[0][q[1] + 1:])
	for i in range(2, n):
		q = []
		for v in a:
			cnt = 0
			for j in range(m):
				if s[i][j] == v[j]:
					cnt += 1
			if cnt < m - 1:
				q.append(v)
		for v in q:
			a.remove(v)
	if a:
		print(list(a)[0])
	else:
		print(-1)


t = int(input())
for i in range(t):
	arr = []
	(n, m) = map(int, input().split())
	for i in range(n):
		arr.append(input())
	str1 = []
	for i in arr[0]:
		str1.append(i)
	ans = ''
	flag = 0
	for i in range(m):
		for j in range(26):
			ini = str1[i]
			str1[i] = chr(j + 97)
			str2 = ''
			for ch in str1:
				str2 += ch
			cnt = 0
			for k in range(n):
				str3 = arr[k]
				count = 0
				for k1 in range(m):
					if str2[k1] != str3[k1]:
						count += 1
				if count <= 1:
					cnt += 1
			if cnt == n:
				ans += str2
				flag = 1
				break
			str1[i] = ini
		if flag:
			break
	if not flag:
		print(-1)
	else:
		print(ans)


import math
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def check(s, l):
	for i in range(len(l)):
		e = l[i]
		c = 0
		for j in range(len(e)):
			if e[j] != s[j]:
				c += 1
		if c > 1:
			return False
	return True
for ik in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(list(input()))
	s = l[0]
	f = 0
	for i in range(m):
		s = [] + l[0]
		for j in range(26):
			s[i] = chr(j + 97)
			if check(s, l) == True:
				f = 1
				print(*s, sep='')
				break
		if f == 1:
			break
	if f == 0:
		print(-1)


g = int(input())
while g > 0:
	g -= 1
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(input())
	s = a[0]
	f3 = 0
	for i in range(m):
		f2 = 0
		for j in range(26):
			temp = s[0:i] + chr(j + 97) + s[i + 1:len(s)]
			f = 0
			for k in range(n):
				c = 0
				for l in range(m):
					if a[k][l] != temp[l] and c == 1:
						f = 1
						break
					if a[k][l] != temp[l]:
						c = 1
			if f == 0:
				print(temp)
				f2 = 1
				break
		if f2 == 1:
			f3 = 1
			break
	if f3 == 0:
		print(-1)


import os
import sys
from io import BytesIO, IOBase
from string import ascii_lowercase

def is_valid(strings, res):
	for s in strings:
		cnt = 0
		for (c1, c2) in zip(s, res):
			if c1 != c2:
				cnt += 1
				if cnt > 1:
					return False
	return True

def solution(strings, n, m):
	res = list(strings[0])
	for i in range(m):
		cur_c = res[i]
		for c in ascii_lowercase:
			res[i] = c
			if is_valid(strings, res):
				write(''.join(res))
				return
		res[i] = cur_c
	write(-1)

def main():
	for _ in range(r_int()):
		(n, m) = r_array()
		strings = []
		for _ in range(n):
			strings.append(input())
		solution(strings, n, m)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')

def write(*args, end='\n'):
	for x in args[:-1]:
		sys.stdout.write(str(x) + ' ')
	sys.stdout.write(str(args[-1]))
	sys.stdout.write(end)

def r_array():
	return [int(x) for x in input().split()]

def r_int():
	return int(input())
main()


def diff_pos(s1, s2, m):
	ans = 0
	for i in range(m):
		if s1[i] != s2[i]:
			ans += 1
		if ans > 1:
			return False
	return True

def f(m, n, arr):
	sample = arr.pop()
	for i in range(m):
		for j in range(26):
			ans = sample[:i] + chr(97 + j) + sample[i + 1:]
			b = True
			for st in arr:
				if not diff_pos(st, ans, m):
					b = False
					break
			if b:
				print(ans)
				return
	print('-1')
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = []
	for i in range(n):
		arr.append(input())
	f(m, n, arr)


import os
import sys
from io import BytesIO, IOBase
from math import log2, ceil, sqrt, gcd, log
from collections import *
from bisect import *
from heapq import *
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
g = lambda : input().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
rr = lambda x: reversed(range(x))
mod = int(1000000000.0) + 7
inf = float('inf')
(t,) = gil()

def comp(s, ss, m):
	for os in ss:
		delta = 0
		for i in range(m):
			if s[i] != os[i]:
				delta += 1
		if delta > 1:
			return False
	return True

def solve(s, ss, n, m):
	for j in range(m):
		prev = s[j]
		for ch in 'abcdefghijklmnopqrstuvwxyz':
			s[j] = ch
			if comp(s, ss, m):
				return ''.join(s)
		s[j] = prev
	return -1
for _ in range(t):
	(n, m) = gil()
	base = gcl()
	mat = [g() for _ in range(n - 1)]
	print(solve(base, mat, n - 1, m))


from sys import stdin
from collections import defaultdict
input = stdin.readline

def dp(ip, ch, costs, n, m, current):
	if ch == m:
		return current
	uniqueChars = []
	uniqueCharsSet = set()
	for i in range(n):
		if ip[i][ch] not in uniqueCharsSet:
			uniqueChars.append(ip[i][ch])
			uniqueCharsSet.add(ip[i][ch])
	for ele in uniqueChars:
		newCosts = costs.copy()
		for i in range(n):
			if ip[i][ch] != ele:
				newCosts[i] += 1
		if max(newCosts) <= 1:
			current.append(ele)
			z = dp(ip, ch + 1, newCosts, n, m, current)
			if z:
				return z
			current.pop()
t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().rstrip().split(' ')))
	ip = []
	for _ in range(n):
		ip.append(input().rstrip())
	costs = [0] * n
	current = []
	z = dp(ip, 0, costs, n, m, current)
	if z:
		print(''.join(z))
	else:
		print(-1)


import string

def isvalid(word):
	for i in range(n):
		differences = 0
		for j in range(m):
			if word[j] != strings[i][j]:
				differences += 1
		if differences > 1:
			return False
	return True

def solve():
	alphabet = string.ascii_lowercase
	if isvalid(strings[0]):
		return strings[0]
	for i in range(m):
		s = strings[0].copy()
		for j in range(len(alphabet)):
			s[i] = alphabet[j]
			if isvalid(s):
				return s
	return '-1'
testcases = int(input())
for i in range(testcases):
	(n, m) = map(int, input().split())
	strings = []
	for j in range(n):
		strings.append(list(input()))
	print(''.join(solve()))


import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__

def go():
	(n, m) = map(int, input().split())

	def sumdif(x, y):
		return sum((xx != yy for (xx, yy) in zip(x, y)))
	s = [input() for _ in range(n)]
	for j in range(1, n):
		(a, b) = (s[0], s[j])
		d = [i for i in range(m) if a[i] != b[i]]
		if len(d) > 2:
			return '-1'
		if len(d) == 2:
			c1 = a[:d[1]] + b[d[1]:]
			c2 = b[:d[1]] + a[d[1]:]
			if all((sumdif(c1, ss) < 2 for ss in s)):
				return c1
			if all((sumdif(c2, ss) < 2 for ss in s)):
				return c2
			return '-1'
	return s[0]
t = int(input())
ans = []
for _ in range(t):
	ans.append(str(go()))
print('\n'.join(ans))


def f(s, a):
	for i in range(len(a)):
		ct = 0
		for j in range(len(a[i])):
			if a[i][j] != s[j]:
				ct += 1
		if ct > 1:
			return False
	return True
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [input() for _ in range(n)]
	s = a[0]
	ans = ''
	for i in range(m):
		(t1, t2) = (s[:i], s[i + 1:])
		for j in range(26):
			ch = chr(ord('a') + j)
			ns = t1 + ch + t2
			if f(ns, a):
				ans = ns
				break
	if ans == '':
		print(-1)
	else:
		print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	dict = {}
	for i in range(n):
		s = input()
		dict[s] = 1
	ans = [0 for x in range(m)]
	arr = list(dict.keys())
	n = len(arr)
	if len(arr) == 1:
		print(arr[0])
		continue
	if len(arr) == 2:
		s1 = arr[0]
		s2 = arr[1]
		save = []
		for i in range(m):
			if s1[i] != s2[i]:
				save.append(i)
			if len(save) > 2:
				ans = -1
				break
			if s1[i] == s2[i]:
				ans[i] = s1[i]
		if ans == -1:
			print(ans)
			continue
		if len(save) == 2:
			index1 = save[0]
			index2 = save[1]
			ans[index1] = s1[index1]
			ans[index2] = s2[index2]
			for i in range(m):
				print(ans[i], end='')
			print()
			continue
		else:
			print(s1)
			continue
	s1 = arr[0]
	s2 = arr[1]
	save = []
	for i in range(m):
		if s1[i] != s2[i]:
			save.append(i)
		if len(save) > 2:
			ans = -1
			break
		if s1[i] == s2[i]:
			ans[i] = s1[i]
	if ans == -1:
		print(ans)
		continue
	if len(save) == 2:
		index1 = save[0]
		index2 = save[1]
		ans1 = [0 for x in range(m)]
		ans2 = [0 for x in range(m)]
		for i in range(m):
			if i == index1:
				ans1[i] = s1[i]
				ans2[i] = s2[i]
			elif i == index2:
				ans1[i] = s2[i]
				ans2[i] = s1[i]
			else:
				ans1[i] = ans2[i] = ans[i]
		s3 = arr[2]
		p = q = 0
		for i in range(m):
			if i not in save:
				if s3[i] != ans[i]:
					p += 1
					q += 1
			else:
				if s3[i] != ans1[i]:
					p += 1
				if s3[i] != ans2[i]:
					q += 1
		if p >= 2 and q >= 2:
			ans = -1
		elif p < 2:
			ans = ans1
		elif q < 2:
			ans = ans2
		if ans == -1:
			print(ans)
			continue
		assert len(arr) == n
		for i in range(n - 3):
			var = 0
			st = arr[i + 3]
			for j in range(m):
				if st[j] != ans[j]:
					var += 1
			if var > 1:
				ans = -1
				break
		if ans == -1:
			print(ans)
			continue
		for i in range(m):
			print(ans[i], end='')
		print()
	else:
		bool = 0
		index1 = save[0]
		for i in range(n - 2):
			st = arr[i + 2]
			if bool == 0:
				var = 0
				for j in range(m):
					if j != index1:
						if st[j] != ans[j]:
							var += 1
				if var > 1:
					ans = -1
					break
				elif var == 1:
					bool = 1
					ans[index1] = st[index1]
			else:
				var = 0
				for j in range(m):
					if st[j] != ans[j]:
						var += 1
				if var > 1:
					ans = -1
					break
		if ans == -1:
			print(ans)
		else:
			if bool == 0:
				ans[index1] = 'a'
			for i in range(m):
				print(ans[i], end='')
			print()


import copy
t = int(input())
al = list('abcdefghijklmnopqrstuvwxyz')
for _ in range(t):
	(n, m) = map(int, input().split())
	l = [list(input()) for i in range(n)]
	d = l[0]
	do = 0
	for i in range(m):
		c = copy.deepcopy(d)
		for j in range(26):
			c[i] = al[j]
			check = True
			for k in l:
				count = 0
				for r in range(m):
					if c[r] != k[r]:
						count += 1
				if count > 1:
					check = False
					break
			if check:
				do = 1
				ans = copy.deepcopy(c)
	if do:
		print(*ans, sep='')
	else:
		print(-1)


import math
import string

def change(s, j, c):
	return s[:j] + c + s[j + 1:]

def check(b, a, n, m):
	for i in range(n):
		count = 0
		for j in range(m):
			if b[i][j] != a[j]:
				count += 1
			if count > 1:
				return 0
	return 1

def solve():
	(n, m) = map(int, input().split())
	b = []
	for i in range(n):
		b.append(input())
	s = b[0]
	flag = 0
	for k in range(m):
		if flag == 1:
			break
		for c in string.ascii_lowercase:
			new = change(s, k, c)
			if check(b, new, n, m):
				flag = 1
				print(new)
				break
	if flag == 0:
		print(-1)
for t in range(int(input())):
	solve()


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	S = [str(input()) for _ in range(n)]
	ans = -1
	for i in range(m):
		for j in range(26):
			t = list(S[0])
			c = chr(j + ord('a'))
			t[i] = c
			t = ''.join(t)
			temp = []
			for k in range(n):
				cnt = 0
				for l in range(m):
					if S[k][l] != t[l]:
						cnt += 1
				temp.append(cnt)
			if max(temp) <= 1:
				ans = t
	print(ans)


class Solution:

	def __init__(self):
		test = int(input())
		for i in range(0, test):
			(n, m) = list(map(int, input().split()))
			a = [input() for i in range(0, n)]
			print(self.solve(n, m, a))

	def solve(self, n, m, a):
		p = []
		alphabet = [chr(c) for c in range(ord('a'), ord('z') + 1)]
		for s in a:
			for i in range(0, m):
				for c in alphabet:
					if c != s[i]:
						t = list(s)
						t[i] = c
						p.append(''.join(t))
		for t in p:
			if self.okay(t, a):
				return t
		return -1

	def okay(self, t, a):

		def diff(a, b):
			found = False
			for (x, y) in zip(a, b):
				if x != y:
					if found:
						return False
					found = True
			return True
		for s in a:
			if not diff(t, s):
				return False
		return True
Solution()


for i in range(int(input())):
	(n, k) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(input())
	r = 0
	for i in range(k):
		for j in range(97, 97 + 26):
			s = list(l[0])
			s[i] = chr(j)
			f = True
			for ko in range(n):
				c = 0
				for e in range(k):
					if s[e] != l[ko][e]:
						c += 1
				if c > 1:
					f = False
					break
			if f:
				break
		if f:
			r = 1
			break
	if r:
		print(''.join(s))
	else:
		print(-1)


from collections import defaultdict as dd
import math
import string
import copy

def nn():
	return int(input())

def li():
	return list(input())

def mi():
	return map(int, input().split())

def lm():
	return list(map(int, input().split()))
q = nn()

def split(word):
	return [char for char in word]

def one_aways(s):
	s_list = split(s)
	one_aways = set()
	for i in range(len(s)):
		for j in string.ascii_lowercase:
			new_slist = copy.deepcopy(s_list)
			new_slist[i] = j
			one_aways.add(''.join(new_slist))
	return one_aways
for _ in range(q):
	(n, lens) = mi()
	strs = []
	for _ in range(n):
		strs.append(input())
	ints = one_aways(strs[0])
	for i in range(1, n):
		ints = ints.intersection(one_aways(strs[i]))
	if len(ints) == 0:
		print(-1)
	else:
		print(list(ints)[0])


import math as mt
from collections import defaultdict as dd
import sys
input = sys.stdin.readline
import string
lc = string.ascii_lowercase

def compare(string1, string2):
	count_diffs = 0
	for (a, b) in zip(string1, string2):
		if a != b:
			if count_diffs:
				return 0
			count_diffs += 1
	return 1
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l += [input().strip()]
	s1 = list(l[0])
	s = s1[:]
	mw = s[:]
	f1 = 0
	f = 0
	for i in lc:
		for j in range(m):
			if s[j] != i or s[j] == i:
				s[j] = i
				for k in l[1:]:
					x = compare(''.join([i for i in s]), k)
					if not x:
						s = list(l[0])
						f = 1
						break
					else:
						f = 0
				if f == 0:
					f1 = 1
					break
		if f1:
			break
	if f1:
		print(''.join([i for i in s]))
	else:
		print(-1)


t = int(input())

def diff(a, b):
	ct = 0
	for i in range(len(a)):
		if a[i] != b[i]:
			ct += 1
			if ct > 1:
				return False
	return ct < 2
for temp in range(t):
	ans = ''
	(n, m) = map(int, input().split())
	ct = [{} for i in range(m)]
	strings = []
	for i in range(n):
		s = input()
		strings.append(s)
		for j in range(len(s)):
			try:
				ct[j][s[j]] += 1
			except:
				ct[j].update({s[j]: 1})
	for i in range(m - 1, -1, -1):
		mk = list(ct[i].keys())[0]
		mv = ct[i][mk]
		for key in ct[i]:
			if mv < ct[i][key]:
				mv = ct[i][key]
				mk = key
		ans = mk + ans
		for st in strings:
			if st[i:] != ans:
				ans = st[:i] + ans
				break
		if len(ans) == m:
			break
	for st in strings:
		if not diff(ans, st):
			ans = -1
			break
	if ans == -1:
		ans = ''
		for i in range(m):
			mk = list(ct[i].keys())[0]
			mv = ct[i][mk]
			for key in ct[i]:
				if mv < ct[i][key]:
					mv = ct[i][key]
					mk = key
			ans += mk
			for st in strings:
				if st[:i + 1] != ans:
					ans += st[i + 1:]
					break
			if len(ans) == m:
				break
		for st in strings:
			if not diff(ans, st):
				ans = -1
				break
	print(ans)


def check(a, b):
	dif = 0
	for i in range(len(a)):
		if a[i] != b[i]:
			dif += 1
			if dif == 2:
				return False
	return True
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	data = []
	for i in range(n):
		data.append(input())
	result = False
	for i in range(m):
		for j in range(0, 26):
			now = data[0][:i] + chr(ord('a') + j) + data[0][i + 1:]
			temp = True
			for k in data[1:]:
				if not check(now, k):
					temp = False
			if temp:
				print(now)
				result = True
				break
		if result:
			break
	if not result:
		print('-1')


def get_string(a, i, st, ans, m, n):
	if i == m:
		return (True, ans)
	s = set([el[i] for el in st])
	for el in s:
		c = a.copy()
		for j in range(n):
			if st[j][i] != el and c[j] == True:
				c[j] = False
			elif st[j][i] != el and c[j] == False:
				break
		else:
			(got, ans_up) = get_string(c, i + 1, st, ans + el, m, n)
			if got:
				return (got, ans_up)
	return (False, ans)
for i in range(int(input())):
	(n, m) = map(int, input().split())
	st = []
	for _ in range(n):
		st.append(input())
	a = [True for _ in range(n)]
	(got, ans) = get_string(a.copy(), 0, st, '', m, n)
	if got:
		print(ans)
	else:
		print(-1)


from math import sqrt
from collections import defaultdict as dd, deque
import sys
input = sys.stdin.readline
t = int(input())
while t:
	d = dd(list)
	ll = []
	(n, m) = map(int, input().split())
	for i in range(n):
		s = input().split()[0]
		ll.append(s)
	ind = -1
	ans = ''
	for j in range(m):
		op = set(ll[0][j])
		for i in range(1, n):
			op.add(ll[i][j])
			if ll[i][j] != ll[0][j]:
				ind = j
		if ind != -1:
			break
		ans += ll[0][j]
	if ind == -1:
		print(ll[0])
	else:
		op = list(op)
		for i in range(n):
			d[ll[i][ind]].append(i)
		lol = 0
		for i in op:
			dummy = str(ans) + i
			for j in d:
				if j != i:
					dummy += ll[d[j][0]][ind + 1:]
					break
			lo = 0
			for i in range(n):
				cou = 0
				for j in range(m):
					if dummy[j] != ll[i][j]:
						cou += 1
					if cou > 1:
						lo = 1
						break
				if lo:
					break
			if lo == 0:
				lol = 1
				break
		if lol:
			print(dummy)
		else:
			print(-1)
	t -= 1


from sys import stdin
input = iter(stdin.readlines()).__next__
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [input().strip() for _ in range(n)]
	ans = a[0]
	for i in range(0, m):
		for letter in map(chr, range(ord('a'), ord('z') + 1)):
			test = ans[:i] + letter + ans[i + 1:]
			correct = True
			for string in a[1:]:
				diffs = len([1 for (char_t, char_s) in zip(test, string) if char_t != char_s])
				if diffs > 1:
					correct = False
					break
			if correct:
				print(test)
				break
		if correct:
			break
	else:
		print(-1)


sc = iter(open(0).read().split())
ni = lambda : int(next(sc))
ns = lambda : next(sc)

def solve():
	T = A[0]
	for S in A[1:]:
		cnt = 0
		for (t, s) in zip(T, S):
			if t != s:
				cnt += 1
		if cnt >= 2:
			break
	else:
		print(''.join(T))
		return
	for c in 'abcdefghijklmnopqrstuvwxyz':
		for i in range(M):
			T = A[0][:]
			T[i] = c
			for S in A[1:]:
				cnt = 0
				for (t, s) in zip(T, S):
					if t != s:
						cnt += 1
				if cnt >= 2:
					break
			else:
				print(''.join(T))
				return
	print(-1)
T = ni()
for _ in range(T):
	(N, M) = (ni(), ni())
	A = [list(ns()) for _ in range(N)]
	solve()


t = int(input())

def aux(s):
	r = set()
	s = list(s)
	for i in range(len(s)):
		c = s[i]
		for j in 'abcdefghijklmnopqrstuvwxyz':
			s[i] = j
			r.add(''.join(s))
		s[i] = c
	return r
while t != 0:
	t -= 1
	(n, m) = map(int, input().split())
	s = input()
	a = aux(s)
	for _ in range(n - 1):
		s = input()
		a = a & aux(s)
	if len(a) == 0:
		print(-1)
	else:
		print(list(a)[-1])


import sys, math, cmath, time
start_time = time.time()
global tt

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	return input().strip()

def invr():
	return map(int, input().split())

def solve():
	(n, m) = invr()
	a = []
	for i in range(n):
		s = insr()
		a.append(s)
	b = [['0'] * len(a) for i in range(m)]
	for i in range(m):
		for j in range(n):
			b[i][j] = a[j][i]
	q = a[0]
	qw = 0
	for i in range(m):
		qq = string_counter(b[i])
		for j in range(26):
			w = q[:i] + chr(97 + j) + q[i + 1:]
			for k in range(n):
				ww = 0
				for l in range(m):
					if w[l] != a[k][l]:
						ww = ww + 1
				if ww < 2:
					True
				else:
					break
			else:
				print(w)
				qw = 1
				break
		if qw == 1:
			break
	if qw == 0:
		print(-1)

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	t = inp()
	for tt in range(t):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
	sys.stdout.close()

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
	return q
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


def diff(string, ans):
	count = 0
	for i in range(len(string)):
		if string[i] != ans[i]:
			count += 1
	return count

def checkans(ans, strings):
	for string in strings:
		if diff(string, ans) > 1:
			return False
	return True
t = int(input())
for _ in range(t):
	(n, m) = [int(c) for c in input().split()]
	strings = []
	for i in range(n):
		string = input()
		strings.append(string)
	indices = []
	if n == 1:
		print(strings[0])
		continue
	for s in range(n - 1):
		indices = []
		string = strings[s]
		anotherstring = strings[s + 1]
		for i in range(0, m):
			if string[i] != anotherstring[i]:
				indices.append(i)
		if len(indices) > 0:
			break
	if len(indices) > 2:
		print(-1)
	else:
		letters = 'abcdefghijklmnopqrtsuvwxyz'
		indices.append(0)
		for index in indices:
			for letter in letters:
				ansstring = list(strings[0])
				ansstring[index] = letter
				if checkans(ansstring, strings):
					print(''.join(ansstring))
					break
			else:
				continue
			break
		else:
			print(-1)


import sys
import math
from collections import defaultdict as dd
mod = 1000000007
T = 1
T = int(sys.stdin.readline())
for _ in range(T):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(input())
	flg = 0
	ans = ''
	for i in range(m):
		s = l[0]
		for j in range(26):
			t = s[:i]
			t += chr(j + 97)
			t += s[i + 1:]
			ff = 0
			for k in l:
				c = 0
				for p in range(m):
					if k[p] != t[p]:
						c += 1
					if c == 2:
						break
				if c > 1:
					ff = 1
					break
			if ff == 0:
				ans = t
				flg = 1
				break
		if flg:
			break
	if flg:
		print(ans)
	else:
		print(-1)


def chk(s1, s2):
	c = 0
	for i in range(len(s1)):
		if s1[i] != s2[i]:
			c += 1
	return c

def ok(s, str):
	for i in str:
		if chk(s, i) > 1:
			return False
	return True
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	str = [input() for i in range(n)]
	ans = -1
	for i in str:
		for j in range(m):
			for k in range(26):
				tmp = list(i)
				tmp[j] = chr(97 + k)
				if ok(tmp, str):
					ans = ''.join(tmp)
	print(ans)


import sys
input = sys.stdin.readline
for f in range(int(input())):
	(n, m) = map(int, input().split())
	s = [0] * n
	for i in range(n):
		s[i] = input()
	poss = False
	maxdiff = 0
	prob = 0
	for i in range(n):
		diff = 0
		for j in range(m):
			if s[0][j] != s[i][j]:
				diff += 1
		maxdiff = max(maxdiff, diff)
		if diff > 1:
			prob = i
	sol = [0, 0]
	if maxdiff <= 1:
		poss = True
	else:
		for foo in range(m):
			maxdiff = 0
			for i in range(n):
				diff = 0
				for j in range(m):
					if j == foo:
						if s[prob][j] != s[i][j]:
							diff += 1
					elif s[0][j] != s[i][j]:
						diff += 1
				maxdiff = max(diff, maxdiff)
			if maxdiff <= 1:
				poss = True
				sol = [prob, foo]
	if poss:
		prob = sol[0]
		foo = sol[1]
		top = s[0][0]
		if foo == 0:
			top = s[prob][0]
		for i in range(1, m):
			if i == foo:
				top += s[prob][i]
			else:
				top += s[0][i]
		print(top)
	else:
		print(-1)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import collections

def check(ans, arr, m):
	for strs in arr:
		count = 0
		for i in range(m):
			if ans[i] != strs[i]:
				count += 1
				if count > 1:
					return False
	return True

def solve(n, m, arr):
	if n == 1 or m == 1:
		return (True, arr[0])
	ans = arr[0]
	for i in range(1, n):
		ans_1 = None
		ans_2 = None
		total = sum((c != s for (c, s) in zip(ans, arr[i])))
		if total > 2:
			return (False, None)
		if total == 2:
			seen = 0
			(ans_1, ans_2) = ([], [])
			for (a, b) in zip(ans, arr[i]):
				if a == b:
					ans_1.append(a)
					ans_2.append(b)
				elif seen == 0:
					ans_1.append(a)
					ans_2.append(b)
					seen += 1
				else:
					ans_1.append(b)
					ans_2.append(a)
			(ans_1, ans_2) = (''.join(ans_1), ''.join(ans_2))
			break
	if not ans_1 and (not ans_2):
		return (True, ans)
	if check(ans_1, arr, m):
		return (True, ans_1)
	if check(ans_2, arr, m):
		return (True, ans_2)
	return (False, None)
t = int(input())
for i in range(t):
	(n, m) = list(map(int, input().split()))
	arr = []
	for i in range(n):
		arr.append(input())
	(can, ans) = solve(n, m, arr)
	if can:
		print(ans)
	else:
		print('-1')


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	list1 = []
	s = 'abcdefghijklmnopqrstuvwxyz'
	for _ in range(n):
		ll = input()
		list1.append(ll)
	f = 0
	set1 = set([])
	for i in range(m):
		for j in range(26):
			ll = list1[0][:i] + s[j] + list1[0][i + 1:]
			set1.add(ll)
	set2 = set([])
	for i in range(1, n):
		for j in range(m):
			for k in range(26):
				ll = list1[i][:j] + s[k] + list1[i][j + 1:]
				set2.add(ll)
		set1 = set1.intersection(set2)
		set2 = set([])
	if set1:
		for i in set1:
			print(i)
			break
	else:
		print(-1)


def constring(a, b):
	string1 = ''
	string2 = ''
	count = 0
	for i in range(len(a)):
		if a[i] == b[i]:
			string1 += a[i]
			string2 += a[i]
		if a[i] != b[i] and count == 0:
			string1 += b[i]
			string2 += a[i]
			count += 1
		elif a[i] != b[i] and count == 1:
			string1 += a[i]
			string2 += b[i]
	return (string1, string2)

def diff(a, b):
	count = 0
	for i in range(len(a)):
		if a[i] != b[i]:
			count += 1
	return count
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	li = [str(input()) for i in range(n)]
	zi = []
	ni = list(set(li))
	if len(ni) == 1:
		print(li[0])
	else:
		for ii in range(len(ni) - 1):
			if diff(ni[ii], ni[ii + 1]) > 2:
				print(-1)
				break
			else:
				(a, b) = constring(ni[ii], ni[ii + 1])
				zi.append(a)
				zi.append(b)
		else:
			for i in zi:
				u = []
				for ii in ni:
					u.append(diff(i, ii))
				if max(u) <= 1:
					print(i)
					break
			else:
				print(-1)


def diff(a, b):
	ct = 0
	for x in range(len(a)):
		if a[x] != b[x]:
			ct += 1
	return ct

def ind(a, b):
	for x in range(len(a)):
		if a[x] != b[x]:
			return x

def indr(a, b):
	for x in range(len(a) - 1, -1, -1):
		if a[x] != b[x]:
			return x
t = int(input())
while t > 0:
	(n, m) = map(int, input().split())
	a = []
	for x in range(n):
		a.append(input())
	st = ''
	flag = 1
	mi = 10
	for x in range(n):
		ma = 0
		for y in range(n):
			di = diff(a[x], a[y])
			ma = max(di, ma)
		if ma >= 3:
			flag = 0
			break
		if ma < mi:
			st = a[x]
			mi = ma
	if flag == 0 or len(st) == 0:
		print(-1)
	else:
		ans = []
		for z in a:
			p = diff(z, st)
			if p == 2:
				i = ind(z, st)
				kk = st[0:i] + z[i] + st[i + 1:]
				ans.append(kk)
				i = indr(z, st)
				kk = st[0:i] + z[i] + st[i + 1:]
				ans.append(kk)
				break
			if p >= 3:
				flag = 0
		if flag == 0:
			print(-1)
		if len(ans) == 0:
			print(st)
		else:
			ma = 0
			for x in a:
				p = diff(x, ans[0])
				ma = max(ma, p)
			if ma <= 1:
				print(ans[0])
				t -= 1
				continue
			ma = 0
			for x in a:
				p = diff(x, ans[1])
				ma = max(ma, p)
			if ma <= 1:
				print(ans[1])
				t -= 1
				continue
			print(-1)
	t -= 1


def inp():
	return int(input())
import math

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
import bisect
from collections import defaultdict
start = 'a'
num = 1
alphabet = defaultdict(lambda : False)
for i in range(1, 27):
	alphabet[num] = start
	start = chr(ord(start) + 1)
	num += 1

def compare(s1, s2, threshold=1):
	differences = 0
	for i in range(len(s1)):
		if s1[i] != s2[i]:
			differences += 1
	if differences <= threshold:
		return True
	else:
		return False
	pass

def solve(li, N, M):
	different = False
	string1 = None
	string2 = None
	final_string = None
	for i in range(N):
		for j in range(i + 1, N):
			if li[i] != li[j]:
				string1 = li[i]
				string2 = li[j]
				different = True
				break
		else:
			continue
		break
	if not different:
		return li[0]
	if not compare(string1, string2, 2):
		return -1
	indexes = defaultdict(lambda : False)
	diff = 0
	for i in range(len(string1)):
		if string1[i] != string2[i]:
			indexes[i] = True
			diff += 1
	if diff == 1:
		for i in range(1, 27):
			s = ''
			for j in range(len(string1)):
				if indexes[j]:
					s += alphabet[i]
				else:
					s += string1[j]
			passed = True
			for j in range(N):
				if not compare(s, li[j]):
					passed = False
					break
			if passed:
				return s
	elif diff == 2:
		yee = [(1, 2), (2, 1)]
		for tup in yee:
			s = ''
			count = 1
			for i in range(len(string1)):
				if indexes[i]:
					if count == 1:
						if tup[0] == 1:
							s += string1[i]
						elif tup[0] == 2:
							s += string2[i]
						count += 1
					elif count == 2:
						if tup[0] == 1:
							s += string2[i]
						elif tup[0] == 2:
							s += string1[i]
						count += 1
				else:
					s += string1[i]
			passed = True
			for i in range(N):
				if not compare(s, li[i]):
					passed = False
					break
			if passed:
				return s
	return -1
T = inp()
for i in range(T):
	(N, M) = inlt()
	li = []
	for i in range(N):
		li.append(input())
	print(solve(li, N, M))


import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import time
start_time = time.time()
import collections as col
import math
from functools import reduce

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())

def diff(s1, s2):
	count = 0
	for i in range(len(s1)):
		if s1[i] != s2[i]:
			count += 1
	return count

def works(s1, list_s):
	for S in list_s:
		if diff(S, s1) > 1:
			return False
	return True

def solve():
	(N, M) = getInts()
	SS = []
	for n in range(N):
		SS.append(listStr())
	if N == 1:
		return ''.join(SS[0])
	if M == 1:
		return 'a'
	for i in range(M):
		for j in range(26):
			tmp = list(SS[0])
			tmp[i] = chr(ord('a') + j)
			if works(tmp, SS[1:]):
				return ''.join(tmp)
	return -1
for _ in range(getInt()):
	print(solve())


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	s = []
	for i in range(n):
		s.append(list(input()))
	flag1 = 0
	ans = s[0].copy()
	for i in range(m):
		save = ans[i]
		for a in range(26):
			temp = chr(a + 97)
			ans[i] = temp
			flag = 1
			for k in range(n):
				count = 0
				for j in range(m):
					if s[k][j] != ans[j]:
						count += 1
				if count > 1:
					flag = 0
					break
			if flag:
				print(''.join(ans))
				flag1 = 1
				break
		if flag1:
			break
		ans[i] = save
	if flag1 == 0:
		print(-1)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	s = []
	for _ in range(n):
		s.append(input())
	p = set()
	for j in range(m):
		for k in 'abcdefghijklmnopqrstuvwxyz':
			p.add(s[0][:j] + k + s[0][j + 1:])
	for i in range(1, n):
		w = s[i]
		p2 = set()
		for j in range(m):
			for k in 'abcdefghijklmnopqrstuvwxyz':
				p2.add(w[:j] + k + w[j + 1:])
		p.intersection_update(p2)
	if len(p) == 0:
		print(-1)
	else:
		print(list(p)[0])


from collections import Counter
import sys
sys.setrecursionlimit(10 ** 6)
mod = 1000000007
inf = int(1e+18)
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]

def inverse(a):
	return pow(a, mod - 2, mod)

def usearch(x, a):
	lft = 0
	rgt = len(a) + 1
	while rgt - lft > 1:
		mid = (rgt + lft) // 2
		if a[mid] <= x:
			lft = mid
		else:
			rgt = mid
	return lft

def solve():
	(n, m) = map(int, input().split())
	s = [input() for i in range(n)]
	a = []
	b = [0] * n

	def dfs(i):
		if i == m:
			return a[:]
		ans = None
		for c in range(ord('a'), ord('z') + 1):
			c = chr(c)
			for j in range(n):
				if s[j][i] == c:
					continue
				b[j] += 1
			a.append(c)
			if not [i for i in b if i > 1]:
				ans = dfs(i + 1)
			if ans:
				return ans
			for j in range(n):
				if s[j][i] == c:
					continue
				b[j] -= 1
			del a[-1]
		return ans
	ans = dfs(0)
	if ans:
		print(''.join(ans))
	else:
		print(-1)

def main():
	n = int(input())
	for i in range(n):
		solve()
main()


Q = ['a', 'b', 'a', 'b']
N = int(input())
for i in range(0, N):
	p = input().rstrip().split(' ')
	L = []
	n = int(p[0])
	m = int(p[1])
	for j in range(0, n):
		s1 = input().rstrip()
		x = list(s1)
		L.append(x)
	tot = -1
	L = list(L)
	A = list(L[0])
	B = list(L[0])
	for j in range(0, 1):
		for k in range(0, len(A)):
			B = list(L[0])
			for O in range(0, 26):
				AA = chr(O + 97)
				B[k] = AA
				GQ = 0
				for U in range(0, len(L)):
					G = L[U]
					ans = 0
					for H in range(0, len(G)):
						if G[H] != B[H]:
							ans += 1
					if ans > 1:
						GQ = 1
						break
				if GQ == 0:
					tot = ''.join(B)
					break
			if tot != -1:
				break
		if tot != -1:
			break
	print(tot)


def check(l, s, m):
	for i in l:
		count = 0
		for j in range(m):
			if s[j] != i[j]:
				count += 1
		if count > 1:
			return 0
	return 1
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		s = input()
		l.append(s)
	s1 = l[0]
	if check(l, s, m) == 1:
		print(s)
	else:
		bo = 0
		for i in range(m):
			u = s1[i]
			for j in range(97, 123):
				k = s[:i] + chr(j) + s[i + 1:]
				if check(l, k, m) == 1:
					bo = 1
					break
			if bo == 1:
				break
		if bo == 1:
			print(k)
		else:
			print(-1)


def check(a, final):
	count = 0
	for i in range(len(a)):
		for j in range(len(final)):
			if final[j] != a[i][j]:
				count += 1
		if count > 1:
			return False
		else:
			count = 0
	return True
test = int(input())
while test != 0:
	(n, m) = [int(x) for x in input().split()]
	a = []
	for i in range(n):
		a.append(input())
	final = a[0]
	flag = 0
	for i in range(m):
		for j in range(97, 123):
			x = chr(j)
			final = final[:i] + x + final[i + 1:]
			if check(a, final) == True:
				print(final)
				flag = 1
				break
		final = final[:i] + a[0][i] + final[i + 1:]
		if flag == 1:
			break
	if flag == 0:
		print(-1)
	test -= 1


from sys import stdin, stdout
input = lambda : stdin.readline().strip()
fast_print = stdout.write
from math import sqrt, floor
T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	strings = []
	for i in range(n):
		strings.append(input())
	if n == 1:
		fast_print(strings[0] + '\n')
		continue
	candidates = []
	for i1 in range(len(strings)):
		for i2 in range(i1 + 1, len(strings)):
			a = strings[i1]
			b = strings[i2]
			cnt = 0
			for i in range(m):
				if a[i] != b[i]:
					cnt += 1
			if cnt > 2:
				fast_print('-1\n')
				break
			elif cnt == 2:
				s1 = ''
				s2 = ''
				flag = 0
				for i in range(m):
					if a[i] != b[i] and flag == 1:
						s1 += b[i]
						s2 += a[i]
					else:
						s1 += a[i]
						s2 += b[i]
						if a[i] != b[i]:
							flag = 1
				candidates.append(s1)
				candidates.append(s2)
			else:
				for n in range(26):
					candidates.append('')
				for i in range(m):
					if a[i] != b[i]:
						for k in range(1, 26 + 1):
							candidates[-k] += chr(ord('a') + k - 1)
					else:
						for k in range(1, 26 + 1):
							candidates[-k] += a[i]
		else:
			continue
		break
	else:
		candidates = list(set(candidates))
		for candidate in candidates:
			for string in strings:
				cnt = 0
				for i in range(m):
					if candidate[i] != string[i]:
						cnt += 1
				if cnt > 1:
					break
			else:
				fast_print(candidate + '\n')
				break
		else:
			fast_print('-1\n')


import sys
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right
from collections import deque
from collections import Counter
from itertools import accumulate, combinations, permutations
from heapq import heapify, heappop, heappush
from functools import lru_cache

def input():
	return sys.stdin.readline()[:-1]

def printl(li):
	_ = print(*li, sep='\n') if li else None

def argsort(s, return_sorted=False):
	inds = sorted(range(len(s)), key=lambda k: s[k])
	if return_sorted:
		return (inds, [s[i] for i in inds])
	return inds

def alp2num(c, cap=False):
	return ord(c) - 97 if not cap else ord(c) - 65

def num2alp(i, cap=False):
	return chr(i + 97) if not cap else chr(i + 65)

def matmat(A, B):
	(K, N, M) = (len(B), len(A), len(B[0]))
	return [[sum([A[i][k] * B[k][j] for k in range(K)]) for j in range(M)] for i in range(N)]

def matvec(M, v):
	(N, size) = (len(v), len(M))
	return [sum([M[i][j] * v[j] for j in range(N)]) for i in range(size)]

def T(M):
	(n, m) = (len(M), len(M[0]))
	return [[M[j][i] for j in range(n)] for i in range(m)]

def main():
	mod = 1000000007
	(N, M) = map(int, input().split())
	A = tuple((input() for _ in range(N)))
	inf = 'x' * (M + 1)
	dp = [[inf for _ in range(2 ** N)] for _ in range(M + 1)]
	dp[0][0] = ''
	for m in range(1, M + 1):
		alis = [alp2num(A[i][m - 1]) for i in range(N)]
		for i in range(2 ** N):
			for let in range(26):
				flag = 1
				ni = i
				for (j, a) in enumerate(alis):
					if let != a and i >> j & 1 == 0:
						ni += 1 << j
					elif let != a:
						flag = 0
						break
				if flag and dp[m - 1][i] != inf:
					dp[m][ni] = dp[m - 1][i] + num2alp(let)
	for x in dp[M]:
		if len(x) == M:
			print(x)
			return
	print(-1)
q = int(input())
for _ in range(q):
	main()


from collections import Counter
from queue import Queue
from typing import List

def read_int():
	return int(input())

def read_string_array():
	return input().split()

def read_int_array():
	return [int(_) for _ in read_string_array()]

def read_line():
	return input()

def diff(s1, s2):
	return sum((1 for (_, __) in zip(s1, s2) if _ != __))

def solve(a, sol='', diff_so_far=None):
	if not a[0]:
		return sol
	a_suffix = [_[1:] for _ in a]
	n = len(a)
	diff_so_far = list(diff_so_far or [0 for _ in range(n)])
	must_use = None
	for i in range(n):
		if diff_so_far[i]:
			if must_use is not None and a[i][0] != must_use:
				return -1
			must_use = a[i][0]
	candidates = set((_[0] for _ in a)) if must_use is None else [must_use]
	rets = [solve(a_suffix, sol + l, [__ + (1 if l != a[_][0] else 0) for (_, __) in enumerate(diff_so_far)]) for l in candidates]
	for r in rets:
		if r != -1:
			return r
	return -1
T = read_int()
for _ in range(T):
	(N, M) = read_int_array()
	A = [read_line() for _ in range(N)]
	print(solve(A))


ipnl = lambda n: [int(input()) for _ in range(n)]
inp = lambda : int(input())
ip = lambda : [int(w) for w in input().split()]
for _ in range(inp()):
	(n, m) = ip()
	x = [list(input()) for i in range(n)]
	for l in range(m):
		t = [x[w][l] for w in range(n)]
		t = list(set(t))
		for k in range(len(t)):
			s = list(x[0])
			s[l] = t[k]
			flag = 1
			for i in range(n):
				ctr = 0
				for j in range(m):
					if s[j] != x[i][j]:
						ctr += 1
				if ctr > 1:
					flag = 0
					break
			if flag:
				break
		if flag:
			break
	if flag:
		print(''.join(s))
	else:
		print(-1)


def ok(a, b):
	diffs = 0
	for i in range(len(a)):
		if a[i] != b[i]:
			diffs += 1
		if diffs > 1:
			return False
	return True

def findInStrings(ind, ch, strs):
	for s in strs:
		if s[ind] == ch:
			return s
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	strings = []
	for _ in range(n):
		strings.append(input())
	chars = {}
	for i in range(m):
		cs = set((s[i] for s in strings))
		chars[i] = cs
	ans = ''
	done = False
	for i in range(m):
		ss = chars[i]
		if len(ss) == 1:
			ans += list(ss)[0]
		else:
			possible = False
			r = ''
			o = list(ss)
			for (q, c) in enumerate(o):
				cand = findInStrings(i, o[int(not q)], strings)
				candd = list(cand)
				candd[i] = c
				cand = ''.join(candd)
				oks = [ok(cand, k) for k in strings]
				if False not in oks:
					r = cand
					possible = True
					break
			if possible:
				print(r)
				done = True
				break
			else:
				print(-1)
				done = True
				break
	if not done and len(ans) == m:
		print(ans)
	elif not done and len(ans) != m:
		print(-1)


import os, sys, math
from io import BytesIO, IOBase
from collections import defaultdict, deque, OrderedDict
import bisect as bi

def yes():
	print('YES')

def no():
	print('NO')

def I():
	return int(input())

def In():
	return map(int, input().split())

def ln():
	return list(map(int, input().split()))

def Sn():
	return input().strip()
BUFSIZE = 8192

def find_gt(a, x):
	i = bi.bisect_left(a, x)
	if i != len(a):
		return i
	else:
		return len(a)

def check(a, l):
	n1 = len(l)
	for j in range(n1):
		cnt = 0
		for i in range(m):
			if a[i] != l[j][i]:
				cnt += 1
		if cnt > 1:
			return False
	return True

def solve():
	global n, m
	(n, m) = In()
	l = set()
	for i in range(n):
		l.add(Sn())
	l = list(l)
	n1 = len(l)
	pos = [set() for i in range(m)]
	for i in range(m):
		for j in range(n1):
			pos[i].add(l[j][i])
	ans = [[]]
	for i in range(m):
		temp = []
		for y in pos[i]:
			for x in ans:
				t = x.copy()
				t.append(y)
				temp.append(t.copy())
		ans.clear()
		ans = temp.copy()
		if len(ans) > 10000:
			print(-1)
			return
	ok = False
	for x in ans:
		if check(x, l):
			print(''.join(x))
			return
	print(-1)
	pass

def main():
	T = I()
	for i in range(T):
		solve()
M = 998244353
P = 1000000007

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
from collections import defaultdict as dd

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
from math import *
import copy
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

def li():
	return [int(x) for x in input().split()]

def fi():
	return int(input())

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def bo(i):
	return ord(i) - ord('a')
import copy
t = fi()
while t > 0:
	t -= 1
	(n, m) = mi()
	a = []
	for i in range(n):
		s = si()
		a.append(s)
	flag = 0
	for i in range(m):
		f = 0
		for k in range(26):
			p = copy.deepcopy(a[0])
			p[i] = chr(k + ord('a'))
			f = 0
			for j in range(1, n):
				f = 0
				for l in range(m):
					if a[j][l] != p[l]:
						f += 1
					if f == 2:
						break
				if f == 2:
					break
			if f < 2:
				print(''.join(p))
				break
		if f < 2:
			break
	if f == 2:
		print(-1)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ans = ''
	s = []
	z = 0
	for i in range(n):
		s.append(input())
	for i in range(n):
		for j in range(m):
			now = ''
			for l in range(j):
				now += s[0][l]
			now += s[i][j]
			for l in range(j + 1, m):
				now += s[0][l]
			maxx = 0
			for h in range(n):
				am1 = 0
				st = s[h]
				for k in range(m):
					if st[k] != now[k]:
						am1 += 1
				if am1 > maxx:
					maxx = am1
			if maxx <= 1 and z == 0:
				print(now)
				z += 1
				break
	if z == 0:
		print(-1)


from collections import deque
from sys import stdin, stdout
from string import ascii_letters
input = stdin.readline
ascii_letters = ascii_letters[:26]
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = [list(input().strip()) for i in range(n)]
	res = arr[0][:]
	can = False
	for i in range(m):
		was = res[i]
		for g in ascii_letters:
			res[i] = g
			aviable = True
			for k in arr:
				count = 0
				for c in range(m):
					if res[c] != k[c]:
						count += 1
				if count > 1:
					aviable = False
					break
			if aviable:
				can = True
				break
		if can:
			print(''.join(res))
			break
		res[i] = was
	if not can:
		print(-1)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
import bisect
import heapq
from math import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def graph(vertex):
	return [[] for i in range(0, vertex + 1)]

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(a, b):
	ans = 1
	while b > 0:
		if b % 2 == 1:
			ans *= a
		a *= a
		b //= 2
	return ans

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def solve():
	(n, m) = sep()
	s = []
	for i in range(n):
		s.append(inp())
	if m == 1:
		print('a')
		return
	ans = ''
	for i in range(m):
		new = []
		for j in range(n):
			new.append(s[j][i])
		if len(set(new)) > 2:
			f = False
			for he in range(len(new)):
				for k in range(n):
					if s[k][i] != new[he]:
						chck1 = s[k][:i] + new[he] + s[k][i + 1:]
						break
				flag = True
				for k in range(n):
					diff = 0
					for l in range(m):
						if s[k][l] != chck1[l]:
							diff += 1
					if diff > 1:
						flag = False
						break
				if flag:
					f = True
					break
			if f:
				print(chck1)
			else:
				print(-1)
			return
		elif len(set(new)) == 1:
			ans += new[0]
		else:
			f1 = True
			f2 = True
			new = list(set(new))
			ans1 = ans
			for k in range(n):
				if s[k][i] != new[0]:
					ans1 += new[0] + s[k][i + 1:]
					break
			for k in range(0, n):
				if ans1 == s[k]:
					continue
				else:
					diff = 0
					for l in range(m):
						if ans1[l] != s[k][l]:
							diff += 1
					if diff > 1:
						f1 = False
						break
			if f1:
				print(ans1)
				return
			for k in range(n):
				if s[k][i] != new[1]:
					ans += new[1] + s[k][i + 1:]
					break
			for k in range(n):
				if ans == s[k]:
					continue
				else:
					diff = 0
					for l in range(m):
						if ans[l] != s[k][l]:
							diff += 1
					if diff > 1:
						f2 = False
						break
			if f2:
				print(ans)
			else:
				print(-1)
			return
	print(ans)
	return
testcase(int(inp()))


cases = int(input())
for i in range(cases):
	l1 = input().split(' ')
	n = int(l1[0])
	m = int(l1[1])
	s = []
	impossible = False
	for j in range(n):
		string = input()
		s.append(string)
	test = list(s[0])
	possible = True
	alphabets = 'abcdefghijklmnopqrstuvwxyz'
	if m == 1:
		for rand in alphabets:
			if rand not in s:
				print(rand)
				break
		continue
	for k in range(len(test)):
		for alpha in alphabets:
			test[k] = alpha
			trial = ''.join(test)
			for p in range(1, n):
				rem = s[p]
				diff = 0
				for (a, b) in zip(rem, trial):
					if a != b:
						diff += 1
					if diff > 1:
						possible = False
						test = list(s[0])
						break
				if diff <= 1:
					possible = True
					continue
				if not possible:
					test = list(s[0])
					break
			if possible:
				print(trial)
				break
		if possible:
			break
	if not possible:
		print(-1)


ans = []
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	u = []
	for i in range(n):
		u.append(input())
	d = []
	for i in range(n):
		d.append([0] * n)
	for i in range(n):
		ok = True
		start = False
		two = set()
		for j in range(n):
			d[i][j] = []
			for k in range(m):
				if u[i][k] != u[j][k]:
					d[i][j].append(k)
					if len(d[i][j]) > 2:
						ok = False
						break
			if not ok:
				break
			if len(d[i][j]) == 2 and (not start):
				(ind1, ind2) = (d[i][j][0], d[i][j][1])
				(v1, v2) = (u[j][ind1], u[j][ind2])
				start = True
			elif len(d[i][j]) == 2:
				if ind1 not in d[i][j] or u[j][ind1] != v1:
					ind1 = -1
				if ind2 not in d[i][j] or u[j][ind2] != v2:
					ind2 = -1
				if ind1 == ind2 == -1:
					ok = False
					break
		if not ok:
			continue
		if start:
			for j in range(n):
				if i == j:
					continue
				if ind1 == -1 or (u[j][ind1] != v1 and ind1 not in d[i][j]):
					ind1 = -1
				if ind2 == -1 or (u[j][ind2] != v2 and ind2 not in d[i][j]):
					ind2 = -1
			if ind1 == ind2 == -1:
				continue
			s = list(u[i][:])
			if ind1 != -1:
				s[ind1] = v1
			else:
				s[ind2] = v2
			s = ''.join(s)
		else:
			s = u[i]
		ans.append(s)
		break
	else:
		ans.append('-1')
print('\n'.join(ans))


alpha = 'abcdefghijklmnopqrstuvwxyz'
t = int(input())
for _ in range(0, t):
	(n, m) = map(int, input().split())
	aa = []
	for _ in range(0, n):
		s = input()
		aa.append(s)
	ok = False
	for i in range(0, m):
		for j in alpha:
			ans = list(aa[0])
			ans[i] = j
			ok = True
			for ii in range(0, n):
				diff = 0
				for jj in range(0, m):
					if ans[jj] != aa[ii][jj]:
						diff += 1
				if diff > 1:
					ok = False
					break
			if ok:
				break
		if ok:
			break
	if ok:
		print(''.join(ans))
	else:
		print(-1)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	strings = []
	for _ in range(n):
		strings.append(input())
	stop = 0
	for pos in range(m):
		for char in range(26):
			s = list(strings[0])
			s[pos] = chr(ord('a') + char)
			s = ''.join(s)
			maxdiff = 0
			for string in strings:
				diff = 0
				for ind in range(m):
					if s[ind] != string[ind]:
						diff += 1
				maxdiff = max(maxdiff, diff)
			if maxdiff == 1:
				stop = 1
				print(s)
				break
		if stop:
			break
	if not stop:
		print(-1)


import math
import string

def change(s, i, symbol):
	ans = s[0:i] + symbol + s[i + 1:]
	return ans

def check(a, n, m, s):
	ans = 0
	for i in range(n):
		cnt = 0
		for j in range(m):
			if a[i][j] != s[j]:
				cnt += 1
		if cnt > 1:
			return 0
	return 1
t = int(input())
for ttt in range(t):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(str(input()))
	s = a[0]
	ans = 0
	for j in range(m):
		if ans == 1:
			break
		for c in string.ascii_lowercase:
			now = change(s, j, c)
			if check(a, n, m, now):
				ans = 1
				print(now)
				break
	if ans == 0:
		print(-1)


import os, sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import Counter
from math import gcd

def dtb(n):
	return bin(n).replace('0b', '')
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [input() for __ in range(n)]
	ans = 0
	for i in range(m):
		s = set()
		for j in range(n):
			s.add(a[j][i])
		ck = [j for j in a[0]]
		for j in s:
			ck[i] = j
			ct = 1
			for k in range(n):
				c = 0
				for t in range(m):
					if a[k][t] != ck[t]:
						c += 1
				if c >= 2:
					ct = 0
					break
			if ct:
				ans = ck
				break
		if ans:
			break
	if ans:
		print(''.join(ans))
	else:
		print(-1)


def cmp(s, t):
	k = 0
	for i in range(len(s)):
		if s[i] != t[i]:
			k += 1
	return k
t = int(input())
for i in range(t):
	a = []
	(n, m) = map(int, input().split())
	for j in range(n):
		a.append(input())
	temp = ''
	found = True
	for j in range(m):
		for l in range(26):
			found = True
			temp = a[0][:j] + chr(97 + l) + a[0][j + 1:]
			for k in range(n):
				if cmp(temp, a[k]) > 1:
					found = False
			if found:
				break
		if found:
			break
	if found:
		print(temp)
	else:
		print(-1)


from sys import stdin, stdout
import sys
from math import *

def d(s, r):
	dif = 0
	for i in range(len(s)):
		if s[i] != r[i]:
			dif += 1
	if dif < 2:
		return True
	return False
for __ in range(int(input())):
	(n, m) = map(int, input().split())
	s = []
	for i in range(n):
		s.append(input())
	if m == 1:
		print('a')
	else:
		rslt = '-1'
		for i in range(n):
			for j in range(m):
				for k in range(26):
					temp = 0
					s1 = chr(k + 97)
					if j > 0:
						s1 = s[i][:j] + s1
					if j < m - 1:
						s1 = s1 + s[i][j + 1:]
					for x in range(n):
						ans = d(s1, s[x])
						if ans == False:
							temp = 1
							break
					if temp == 0:
						rslt = s1
						break
				if temp == 0:
					break
			if temp == 0:
				break
		print(rslt)


for i in range(int(input())):
	(n, m) = map(int, input().split())
	matrix = list(('' for j in range(n)))
	for j in range(n):
		matrix[j] = input()
	flag = False
	ans = '-1'
	for j in range(m):
		for a in 'qwertyuioplkjhgfdsazxcvbnm':
			t = matrix[0]
			t = t[:j] + a + t[j + 1:]
			for h in matrix:
				ct = 0
				for re in range(m):
					if t[re] != h[re]:
						ct += 1
				if ct > 1:
					flag = True
			if not flag:
				ans = t
			flag = False
	print(ans)


import io
import os
from itertools import product

def solve(N, M, A):
	candidates = set(A)
	for i in range(N):
		for j in range(i + 1, N):
			w1 = A[i]
			w2 = A[j]
			indices = []
			for k in range(M):
				if w1[k] != w2[k]:
					indices.append(k)
			if len(indices) > 2:
				return -1
			for k in indices:
				candidates.add(w1[:k] + w2[k] + w1[k + 1:])
				candidates.add(w2[:k] + w1[k] + w2[k + 1:])
	for w1 in candidates:
		bad = False
		for w2 in A:
			numDiff = sum((1 for (x, y) in zip(w1, w2) if x != y))
			if numDiff > 1:
				bad = True
				break
		if not bad:
			return ''.join(w1)
	return -1
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
	(N, M) = [int(x) for x in input().split()]
	A = [input().decode().rstrip() for i in range(N)]
	ans = solve(N, M, A)
	print(ans)


def main():
	import sys
	input = sys.stdin.readline
	sys.setrecursionlimit(10 ** 9)

	def dist(s, t):
		ret = 0
		for (cs, ct) in zip(s, t):
			if cs != ct:
				ret += 1
		return ret
	for __ in [0] * int(input()):
		(N, M) = map(int, input().split())
		S = [list(input()[:-1]) for _ in [0] * N]
		dup = [set() for _ in [0] * M]
		for s in S:
			for (i, c) in enumerate(s):
				dup[i].add(c)
		f = 0
		for (i, d) in enumerate(dup):
			f += len(d) - 1
		if f > N:
			print(-1)
			continue

		def dfs(i, t):
			if i == M:
				for s in S:
					if dist(s, t) > 1:
						return False
				return t
			if len(dup[i]) == 1:
				return dfs(i + 1, t + list(dup[i])[0])
			for c in dup[i]:
				ret = dfs(i + 1, t + c)
				if ret:
					return ret
			return False
		ans = dfs(0, '')
		if ans:
			print(ans)
		else:
			print(-1)
main()


def count(a, b):
	c = 0
	for i in range(m):
		if a[i] == b[i]:
			c += 1
	return c

def valid(a, b):
	return m - count(a, b) <= 1
t = int(input())
for w in range(t):
	got = False
	nm = list(map(int, input().strip().split()))
	n = nm[0]
	m = nm[1]
	arr = []
	for u in range(n):
		arr.append(str(input()))
	if n == 1:
		got = True
		print(arr[0])
	i = 0
	j = 1
	while i < n - 1 and j < n:
		c = count(arr[i], arr[j])
		if m - c > 2:
			got = True
			print(-1)
			break
		elif m - c == 2:
			str1 = arr[i]
			for k in range(m):
				flag = True
				if str1[k] != arr[j][k]:
					str1 = str1[:k] + arr[j][k] + (k + 1 != m) * str1[k + 1:]
					for x in range(0, n):
						if not valid(str1, arr[x]):
							flag = False
							break
					if flag:
						got = True
						print(str1)
						break
					else:
						str1 = str1[:k] + arr[i][k] + (k + 1 != m) * str1[k + 1:]
			if not flag:
				i += 1
				j += 1
			else:
				break
		else:
			l = 0
			while l < n:
				this = True
				for k in range(n):
					if valid(arr[l], arr[k]):
						continue
					else:
						this = False
						break
				if this:
					got = True
					print(arr[l])
					break
				else:
					l += 1
			if not this:
				i += 1
				j += 1
			else:
				break
	if not got:
		print(-1)


for k in range(int(input())):
	(n, m) = map(int, input().split())
	strings = []
	for i in range(n):
		string = [j for j in input()]
		strings += [string]
	i = 1
	flag = 0
	for word in strings:
		for ind_of_row in range(i, n):
			difference = 0
			for ind in range(m):
				if word[ind] != strings[ind_of_row][ind]:
					difference += 1
			if difference > 2:
				flag = 1
				print('-1')
				break
			if flag == 1:
				break
		if flag == 1:
			break
		i += 1
	if flag == 1:
		continue
	symbols = []
	for ind in range(m):
		column = set()
		for word in strings:
			column.add(word[ind])
		symbols += [list(column)]
	candidates = []
	for position in symbols:
		nexus = []
		for el in position:
			if len(candidates) == 0:
				nexus += [el]
			else:
				for candidate in candidates:
					nexus += [candidate + el]
		candidates = list(nexus)
	for candidate in candidates:
		flag = 0
		for string in strings:
			difference = 0
			for ind in range(m):
				if candidate[ind] != string[ind]:
					difference += 1
				if difference > 1:
					flag = 1
					break
			if flag == 1:
				break
		if flag == 0:
			print(candidate)
			break
	if flag != 0:
		print('-1')


import sys
max_int = 1000000001
min_int = -max_int
t = int(input())
letters = 'abcdefghijklmnopqrstuvwxyz'
for _t in range(t):
	(n, m) = map(int, sys.stdin.readline().split())
	strings = []
	first_string = False
	for _n in range(n):
		s = input()
		if not first_string:
			first_string = s
		else:
			strings.append(s)
	variations = set()
	for i in range(m):
		for letter in letters:
			if i == 0:
				to_add = letter + first_string[1:]
			elif i == m:
				to_add = first_string[0:-1] + letter
			else:
				to_add = first_string[0:i] + letter + first_string[i + 1:]
			variations.add(to_add)
	for variation in variations:
		for string in strings:
			diff = 2
			for i in range(m):
				if string[i] != variation[i]:
					diff -= 1
					if diff == 0:
						break
			if diff == 0:
				break
		else:
			print(variation)
			break
	else:
		print(-1)


t = int(input())
for case in range(t):
	(n, m) = map(int, input().split())
	a = [input() for _ in range(n)]
	if n == 1:
		print(a[0])
		continue
	pos = []
	idx = 0
	while True:
		for i in range(m):
			if a[idx][i] != a[idx + 1][i]:
				pos.append(i)
		if len(pos) > 0:
			break
		idx += 1
		if idx == n - 1:
			break
	if idx == n - 1:
		print(a[0])
	elif len(pos) >= 3:
		print('-1')
	else:
		if len(pos) == 1:
			candi = []
			for i in range(26):
				candi.append(a[idx][:pos[0]] + chr(97 + i) + a[idx][pos[0] + 1:])
		else:
			candi = [a[idx][:pos[0]] + a[idx + 1][pos[0]] + a[idx][pos[0] + 1:], a[idx][:pos[1]] + a[idx + 1][pos[1]] + a[idx][pos[1] + 1:]]
		ans = '-1'
		for s in candi:
			ok = 1
			for i in range(n):
				dif = 0
				for j in range(m):
					if s[j] != a[i][j]:
						dif += 1
					if dif >= 2:
						ok = 0
						break
			if ok:
				ans = s
		print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	li = []
	for i in range(n):
		li.append(list(input()))
	ansli = []
	for i in range(n):
		ans = li[i].copy()
		for j in range(m):
			for zz in range(n):
				tem = ans.copy()
				tem[j] = li[zz][j]
				ansli.append(tem)
	f1 = False
	for i in ansli:
		flag = True
		for j in li:
			count = 0
			for zz in range(m):
				if i[zz] != j[zz]:
					count += 1
			if count > 1:
				flag = False
				break
		if flag:
			f1 = True
			print(''.join(i))
			break
	if not f1:
		print(-1)


from sys import stdin
input = lambda : stdin.readline().strip()
from math import ceil, sqrt, factorial, gcd

def aise(a, r, nh):
	if r == m or len(a) == m:
		x = 0
		for i in l:
			if a == i:
				x += 1
		if x == n:
			print(a)
			return True
		else:
			for i in l:
				t = 0
				f = 0
				for j in range(m):
					if a[j] != i[j]:
						t += 1
				if t == 1 or t == 0:
					if t == 0:
						f += 1
				else:
					return False
			if f == 0 or f == 1:
				print(a)
				return True
			else:
				return False
	else:
		for i in list(z[r]):
			flag = 1
			q = list(nh)
			for j in range(n):
				if l[j][r] != i:
					q[j] += 1
					if q[j] > 1:
						flag = 0
			if flag == 1:
				if aise(a + i, r + 1, q):
					return True
		return False
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	zl = [0 for i in range(n)]
	l = []
	ass = []
	for i in range(97, 123):
		ass.append(chr(i))
	z = [set() for i in range(m)]
	ans = ''
	for i in range(n):
		l.append(input())
		for j in range(m):
			z[j].add(l[i][j])
	for i in range(m):
		for j in ass:
			if j not in z[i]:
				z[i].add(j)
				break
	for i in range(m):
		z[i] = list(z[i])
	if aise('', 0, zl):
		pass
	else:
		print('-1')


t = int(input())
answer = []
for kek in range(t):
	(n, m) = map(int, input().split())
	a = []
	may = []
	for i in range(n):
		may.append(set())
		a.append(input())
		may[-1].add(a[-1])
	for i in range(m):
		book = set()
		for word in a:
			book.add(word[i])
		for j in range(n):
			for let in book:
				may[j].add(a[j][:i] + let + a[j][i + 1:])
	ans = may[0]
	for i in may:
		ans &= i
	if len(ans) == 0:
		answer.append(-1)
	else:
		for i in ans:
			answer.append(i)
			break
print(*answer, sep='\n')


abc = 'abcdefghijklmnopqrstuvwxyz'
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [input() for _ in range(n)]
	s = a[0]
	ans = -1
	nr = 0
	for i in range(m):
		for j in abc:
			s = a[0][:i] + j + a[0][i + 1:]
			nr = 0
			for k in range(n):
				c = 0
				for l in range(m):
					c += a[k][l] != s[l]
				nr += not c > 1
			if nr == n:
				ans = s
				break
		if nr == n:
			break
	print(ans)


import sys
input = sys.stdin.readline
(T,) = map(int, input().split())
for _ in range(T):
	(N, M) = map(int, input().split())
	x = list(input().strip())
	ys = []
	for _ in range(N - 1):
		ys.append(input().strip())
	ff = 0
	for i in range(M):
		xi = x[i]
		for c in 'abcdefghijklmnopqrstuvwxyz':
			x[i] = c
			f = 0
			for y in ys:
				cc = 0
				for j in range(M):
					if x[j] != y[j]:
						cc += 1
				if cc > 1:
					f = 1
					break
			if not f:
				print(''.join(x))
				ff = 1
				break
		x[i] = xi
		if ff:
			break
	else:
		print(-1)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ss = set()
	for _ in range(n):
		ss.add(input())
	sarr = list(map(list, ss))
	n = len(sarr)
	gs = [True for _ in range(m)]
	for i in range(m):
		c = sarr[0][i]
		for j in range(n):
			if sarr[j][i] != c:
				gs[i] = False
	if m - sum(map(int, gs)) < 2:
		print(''.join(sarr[0]))
		continue
	poss = True
	candidates = None
	for i in range(n):
		s1 = sarr[i]
		for j in range(i + 1, n):
			s2 = sarr[j]
			dc = 0
			for k in range(m):
				if s1[k] != s2[k]:
					dc += 1
					if dc > 2:
						poss = False
						break
			if not poss:
				break
			if dc == 2:
				candidates = (s1, s2)
		if not poss:
			break
	if not poss:
		print(-1)
		continue
	dp1 = None
	dp2 = None
	s1 = candidates[0]
	s2 = candidates[1]
	for i in range(m):
		if s1[i] != s2[i]:
			if dp1 is None:
				dp1 = i
			else:
				dp2 = i
				break
	cs1 = s1[:dp1] + [s1[dp1]] + s1[dp1 + 1:dp2] + [s2[dp2]] + s1[dp2 + 1:]
	cs2 = s1[:dp1] + [s2[dp1]] + s1[dp1 + 1:dp2] + [s1[dp2]] + s1[dp2 + 1:]
	match = True
	for s in sarr:
		dc = 0
		for i in range(m):
			if s[i] != cs1[i]:
				dc += 1
		if dc > 1:
			match = False
			break
	if match:
		print(''.join(cs1))
		continue
	match = True
	for s in sarr:
		dc = 0
		for i in range(m):
			if s[i] != cs2[i]:
				dc += 1
		if dc > 1:
			match = False
			break
	if match:
		print(''.join(cs2))
		continue
	print(-1)


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	s = []
	ans = str()
	for o in range(n):
		a = input()
		s.append(a)
	if len(s) == 1:
		print(s[0])
		continue
	flag = False
	stone = 'abcdefghijklmnopqrstuvwxyz'
	sttwo = s[0]
	for p in range(m):
		for w in range(len(stone)):
			tmp = sttwo[0:p] + stone[w] + sttwo[p + 1:]
			mx = 0
			for x in range(1, n):
				u = 0
				for y in range(m):
					if tmp[y] != s[x][y]:
						u += 1
				mx = max(mx, u)
			if mx <= 1:
				flag = True
				ans = tmp
	if flag:
		print(ans)
	else:
		print(-1)


from sys import stdin, stdout
int_in = lambda : int(stdin.readline())
arr_in = lambda : [int(x) for x in stdin.readline().split()]
mat_in = lambda rows: [arr_in() for y in range(rows)]
str_in = lambda : stdin.readline().strip()
out = lambda o: stdout.write('{}\n'.format(o))
arr_out = lambda o: out(' '.join(map(str, o)))
bool_out = lambda o: out('YES' if o else 'NO')
tests = lambda : range(1, int_in() + 1)
case_out = lambda i, o: out('Case #{}: {}'.format(i, o))

def solve(n, m, strings):
	possibilities = set()
	possibilities.add(strings[0])
	for i in range(m):
		to_add = list(strings[0])
		to_add[i] = '?'
		possibilities.add(''.join(to_add))
	for (i, string) in enumerate(strings[1:]):
		works = set()
		for poss in possibilities:
			diff = 0
			diff_i = -1
			q_i = -1
			for j in range(m):
				if poss[j] == '?':
					q_i = j
				elif string[j] != poss[j]:
					diff += 1
					diff_i = j
			if diff < 2:
				if diff_i == -1:
					new = poss
				elif q_i == -1:
					new = poss
				elif q_i >= 0 and diff_i >= 0:
					new = list(poss)
					new[q_i] = string[q_i]
					new = ''.join(new)
				else:
					continue
			else:
				continue
			works.add(new)
		possibilities = works
		if len(possibilities) == 0:
			return -1
	result = list(possibilities)[0]
	result = map(lambda x: 'z' if x == '?' else x, result)
	return ''.join(result)
for i in tests():
	(n, m) = arr_in()
	strings = [str_in() for x in range(n)]
	out(solve(n, m, strings))


def eq(s1, s2):
	diffs = 0
	for (x, y) in zip(s1, s2):
		if x != y:
			diffs += 1
		if diffs > 1:
			return False
	return True

def solve():
	(n, m) = (int(x) for x in input().split())
	strings = [input().strip() for _ in range(n)]
	ans = []
	for i in range(m):
		letters = set((s[i] for s in strings))
		if len(letters) == 1:
			ans.append(letters.pop())
		else:
			break
	if len(ans) == m:
		return ''.join(ans)
	ans += ['', '']
	for l in letters:
		ans[-2] = l
		for s in strings:
			if s[i] != l:
				ans[-1] = s[i + 1:]
				break
		curr_ans = ''.join(ans)
		is_ans = True
		for s in strings:
			is_ans &= eq(curr_ans, s)
		if is_ans:
			return curr_ans
	return -1
for _ in range(int(input())):
	print(solve())


import sys
import math
import operator as op
from functools import reduce

def read_line():
	return sys.stdin.readline()[:-1]

def read_int():
	return int(sys.stdin.readline())

def read_int_line():
	return [int(v) for v in sys.stdin.readline().split()]

def read_float_line():
	return [float(v) for v in sys.stdin.readline().split()]

def ncr(n, r):
	r = min(r, n - r)
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer / denom

def isSameforOne(a, b):
	cnt = 0
	for i in range(len(a)):
		if a[i] != b[i]:
			cnt += 1
		if cnt > 1:
			return False
	return True
t = read_int()
for i in range(t):
	(n, m) = read_int_line()
	st = []
	for i in range(n):
		a = read_line()
		st.append(a)
	s = []
	a = st[0]
	l = [chr(i) for i in range(97, 123)]
	for i in range(m):
		for j in l:
			temp = a[:i] + j + a[i + 1:]
			s.append(temp)
	ans = '-1'
	for i in s:
		f = False
		for j in range(n):
			f = isSameforOne(i, st[j])
			if not f:
				break
		if f:
			ans = i
			break
	print(ans)


from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush, heappop
import math
from collections import *
from functools import reduce, cmp_to_key, lru_cache
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
M = mod = 10 ** 9 + 7

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip().split()]

def st():
	return str(input().rstrip())[2:-1]

def val():
	return int(input().rstrip())

def li2():
	return [str(i)[2:-1] for i in input().rstrip().split()]

def li3():
	return [int(i) for i in st()]

def satisfy(s, l, n, m):
	for i in range(n):
		tot = 0
		for j in range(m):
			if s[j] != l[i][j]:
				tot += 1
		if tot > 1:
			return 0
	return 1
for _ in range(val()):
	(n, m) = li()
	l = []
	for i in range(n):
		l.append(st())
	ans = ''
	for j in range(m):
		cnt = Counter()
		for i in range(n):
			cnt[l[i][j]] += 1
		if len(cnt) == 1:
			ans += l[-1][j]
		else:
			ans = ''
			for k in cnt:
				for i in range(n):
					if l[i][j] != k:
						a1 = l[i][:j] + k + l[i][j + 1:]
				if satisfy(a1, l, n, m):
					ans = a1
					break
			if len(ans) == 0:
				ans = -1
			break
	print(ans)


def rs():
	return input().strip()

def ri():
	return int(input())

def ria():
	return list(map(int, input().split()))

def ia_to_s(a):
	return ' '.join([str(s) for s in a])

def dist(s1, s2):
	m = len(s1)
	return sum((1 for i in range(m) if s1[i] != s2[i]))

def solve(n, m, s):
	for j in range(m):
		x = [si for si in s[0]]
		for c in range(26):
			x[j] = chr(ord('a') + c)
			ok = True
			for i in range(1, n):
				if dist(x, s[i]) > 1:
					ok = False
					break
			if ok:
				return ''.join(x)
	return '-1'

def main():
	for _ in range(ri()):
		(n, m) = ria()
		s = []
		for __ in range(n):
			s.append(rs())
		print(solve(n, m, s))
main()


import math
t = int(input(''))
while t > 0:
	(n, m) = map(int, input().split())
	l = []
	for i in range(n):
		l.append(input())
	flag = 0
	for k in range(m):
		var = 97
		for v in range(26):
			var = 97 + v
			s = l[0]
			s_new = s[:k] + chr(var) + s[k + 1:]
			for z in l:
				count = 0
				for check in range(m):
					if z[check] != s_new[check]:
						count += 1
				if count > 1:
					break
			else:
				ans = s_new
				flag = 1
	if flag == 1:
		print(ans)
	else:
		print(-1)
	t -= 1


def check(grid, n, m, s):
	for s1 in grid:
		diff = 0
		for i in range(m):
			if s[i] != s1[i]:
				diff += 1
		if diff > 1:
			return False
	return True

def solve(grid, n, m, ans):
	s = list(grid[0])
	for col in range(m):
		for row in range(n):
			prev = s[col]
			s[col] = grid[row][col]
			if check(grid, n, m, s):
				s1 = ''
				for i in s:
					s1 += i
				ans.append(s1)
				return
			s[col] = prev
	ans.append(-1)

def main():
	t = int(input())
	ans = []
	for i in range(t):
		(n, m) = map(int, input().split())
		grid = []
		for j in range(n):
			grid.append(input())
		solve(grid, n, m, ans)
	for i in ans:
		print(i)
main()


import sys

def I():
	return list(map(int, input().split()))

def sieve(n):
	a = [1] * n
	for i in range(2, n):
		if a[i]:
			for j in range(i * i, n, i):
				a[j] = 0
	return a

def solve():

	def checker(s):
		for i in range(n):
			s2 = strs[i]
			c = 0
			for j in range(m):
				if s2[j] != s[j]:
					c += 1
				if c > 1:
					return False
		return True
	(n, m) = I()
	strs = []
	for i in range(n):
		strs.append(input())
	f = 0
	for i in range(n):
		s = strs[i]
		if checker(s):
			return s
		for j in range(m):
			curr = ord(s[j]) - 97
			for k in range(26):
				if k == curr:
					continue
				else:
					t = checker(s[:j] + chr(k + 97) + s[j + 1:])
					if t:
						return s[:j] + chr(k + 97) + s[j + 1:]
	return -1
for __ in range(int(input())):
	print(solve())


def strgntr(s, m):
	st = set()
	for i in range(m):
		for j in range(26):
			st.add(s[:i] + chr(97 + j) + s[i + 1:])
	return st
for t in range(int(input())):
	(n, m) = [int(x) for x in input().split(' ')]
	l = []
	s = input()
	st = strgntr(s, m)
	for i in range(n - 1):
		st = strgntr(input(), m) & st
	if not st:
		print(-1)
	else:
		l = list(st)
		print(l[0])


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(input())
	done = False
	for letter in range(m):
		done = False
		for i in range(97, 123):
			now = a[0][:letter] + chr(i) + a[0][letter + 1:]
			fuc = False
			for u in range(1, n):
				counter = 0
				for ch in range(m):
					if a[u][ch] != now[ch]:
						counter += 1
						if counter > 1:
							fuc = True
							break
				if fuc:
					break
			if not fuc:
				done = True
				break
		if done:
			break
	if done:
		print(now)
	else:
		print(-1)


import os
os_input = os.read(0, int(10000000.0)).split()
os_input_pos = -1

def cin():
	global os_input_pos
	os_input_pos += 1
	return os_input[os_input_pos]
T = int(cin())
res = []
while T:
	T -= 1
	(n, m) = (int(cin()), int(cin()))
	s = [cin().decode() for i in range(n)]
	dp = [[None for j in range(2 ** n)] for i in range(m + 1)]
	dp[0][0] = ''
	for x in range(m):
		for j in range(2 ** n):
			if dp[x][j] is None:
				continue
			for k in 'qwertyuiopasdfghjklzxcvbnm':
				nj = j
				for i in range(n):
					if s[i][x] != k:
						nj ^= 1 << i
				if nj & j == j and dp[x + 1][nj] is None:
					dp[x + 1][nj] = dp[x][j] + k
	for j in range(2 ** n):
		if dp[m][j] is not None:
			res.append(dp[m][j])
			break
	else:
		res.append('-1')
os.write(1, '\n'.join(res).encode())


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')

def main():
	for _ in range(N()):
		(n, m) = RL()
		arr = [list(input()) for _ in range(n)]
		c = [chr(i) for i in range(97, 97 + 26)]

		def check(carr):
			for i in range(n):
				num = 0
				for j in range(m):
					if carr[j] != arr[i][j]:
						num += 1
						if num > 1:
							return False
			return True
		tag = True
		res = []
		for i in range(n):
			for j in range(m):
				for k in range(26):
					now = arr[i].copy()
					now[j] = c[k]
					if check(now):
						res = now
						tag = False
						print(''.join(res))
						break
				if tag == False:
					break
			if tag == False:
				break
		else:
			print(-1)
main()


import sys
input = sys.stdin.readline

def solve(n, m, A):
	L = 'abcdefghijklmnopqrstuvwxyz'
	S = [set() for _ in range(n)]
	for (i, (a, s)) in enumerate(zip(A, S)):
		s.add(a)
		for j in range(m):
			Tmp = list(a)
			for l in L:
				Tmp[j] = l
				tmp = ''.join(Tmp)
				s.add(tmp)
	ans_set = S[0]
	for i in range(1, n):
		ans_set &= S[i]
	if ans_set:
		return tuple(ans_set)[0]
	return '-1'

def main():
	t = int(input())
	for _ in range(t):
		(n, m) = map(int, input().split())
		A = [input().strip() for _ in range(n)]
		ans = solve(n, m, A)
		sys.stdout.write(ans + '\n')
main()


import sys
input = lambda : sys.stdin.readline().strip()
indices = set()

def calc(a, b):
	val = 0
	for i in range(len(a)):
		if a[i] != b[i]:
			val += 1
			indices.add(i)
	return val

def solve():
	(n, m) = map(int, input().split())
	s = []
	for i in range(n):
		s.append(input())
	ans = list(s[0])
	for j in range(m):
		save = ans[j]
		for d in range(26):
			ans[j] = chr(ord('a') + d)
			flag = True
			for z in range(n):
				cnt = 0
				for c in range(m):
					if s[z][c] != ans[c]:
						cnt += 1
				if cnt > 1:
					flag = False
					break
			if flag:
				print(''.join(ans))
				return
		ans[j] = save
	print(-1)
t = int(input())
while t:
	t -= 1
	solve()


M = 17
s = ['' for x in range(M)]
candidate = ''
double_break = 0
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	for i in range(1, n + 1):
		s[i] = input()
	for i in range(m):
		for j in range(26):
			j = chr(97 + j)
			candidate = ''
			for k in range(i):
				candidate += s[1][k]
			candidate += j
			for k in range(i + 1, m):
				candidate += s[1][k]
			for k in range(2, n + 1):
				differences = 0
				for w in range(m):
					differences += candidate[w] != s[k][w]
				if differences > 1:
					break
			else:
				print(candidate)
				double_break = 1
				break
		if double_break:
			double_break = 0
			break
	else:
		print(-1)


def likely_line(line1, line2):
	mismatch = 0
	position = []
	for x in range(len(line1)):
		if line1[x] != line2[x] and line1[x] != '*':
			mismatch += 1
			position.append(x)
	return [mismatch, position]

def new_line(line1, line2, pos):
	res_line = ''
	for x in range(len(line1)):
		if x == pos:
			res_line += line2[x]
		else:
			res_line += line1[x]
	return res_line

def check_line(line, lines):
	for x in range(len(lines)):
		test = likely_line(line, lines[x])
		if test[0] > 1:
			return False
	return True
tests = int(input())
for i in range(tests):
	numbers = input().split()
	n = int(numbers[0])
	m = int(numbers[1])
	line = []
	for x in range(n):
		line.append(input())
	find_line = line[0]
	fixed_flag = 0
	for x in range(n):
		test = likely_line(find_line, line[x])
		if test[0] > 2:
			find_line = -1
			break
		elif test[0] == 2:
			if fixed_flag == 0:
				first_line = new_line(find_line, line[x], test[1][0])
				second_line = new_line(find_line, line[x], test[1][1])
				if check_line(first_line, line):
					find_line = first_line
					break
				elif check_line(second_line, line):
					find_line = second_line
					break
				else:
					find_line = -1
					break
			else:
				find_line = -1
				break
		elif test[0] == 1:
			if fixed_flag == 0:
				find_line = new_line(find_line, '**********', test[1][0])
				fixed_flag = 1
			elif find_line[test[1][0]] != '*':
				first_line = ''
				for y in range(m):
					if find_line[y] != '*':
						first_line += find_line[y]
					else:
						first_line += line[x][y]
				if check_line(first_line, line):
					find_line = first_line
					break
				else:
					find_line = -1
					break
	if find_line == -1:
		result_line = -1
	else:
		result_line = ''
		for y in range(len(find_line)):
			if find_line[y] != '*':
				result_line += find_line[y]
			else:
				result_line += line[0][y]
	print(result_line)


from sys import stdin, stdout

def find(arr, N, M):
	for i in range(M):
		k = arr[0][i]
		for j in range(N):
			if arr[j][i] != k:
				break
		else:
			continue
		break
	s = set()
	for j in range(N):
		s.add(arr[j][i])
	P = []
	for j in s:
		for k in arr:
			P.append(k[:i] + j + k[i + 1:])
	for i in P:
		for j in arr:
			c = 0
			for k in range(M):
				if j[k] != i[k]:
					c += 1
				if c > 1:
					break
			else:
				continue
			break
		else:
			return i
	return -1

def main():
	for _ in range(int(stdin.readline())):
		(N, M) = list(map(int, stdin.readline().split()))
		arr = []
		for _ in range(N):
			arr.append(stdin.readline().strip())
		print(find(arr, N, M))
main()


def check(s, n, m, res):
	for k in range(n):
		st = s[k]
		c = 0
		for l in range(m):
			if st[l] != res[l]:
				c += 1
		if c > 1:
			return False
	return True
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	s = []
	for i in range(n):
		s.append(input())
	res = list(s[0])
	f = 0
	for i in range(m):
		res = list(s[0])
		for j in range(26):
			res[i] = chr(ord('a') + j)
			if check(s, n, m, res):
				print(''.join(res))
				f = 1
				break
		if f == 1:
			break
	if f == 0:
		print(-1)


from collections import Counter
import itertools
import itertools
for i in range(int(input())):
	(n, m) = map(int, input().split())
	matrix = []
	for ii in range(n):
		l1 = list(input())
		matrix.append(l1)
	k = matrix.copy()
	k.sort()
	matrix = list((k for (k, _) in itertools.groupby(k)))
	n = len(matrix)
	m = len(matrix[0])
	common = []
	result = []
	for jj in range(m):
		for ii in range(n):
			common.append(matrix[ii][jj])
		occurence_count = Counter(common)
		common_set = list(set(common))
		val = occurence_count.most_common(1)[0][1]
		multi = []
		for ii in common_set:
			if common.count(ii) == val:
				multi.append(ii)
		result.append(multi)
		common = []
		multi = []
	final = list(itertools.product(*result))
	final_val = []
	for ii in final:
		flag = 0
		for jj in matrix:
			cnt = 0
			for ll in range(m):
				if jj[ll] != ii[ll]:
					cnt += 1
			if cnt > 1:
				flag = 1
		final_val.append(flag)
	if 0 not in final_val:
		print(-1)
	else:
		print(''.join(final[final_val.index(0)]))


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
testcases = int(input())
for j in range(testcases):
	(n, m) = map(int, input().split())
	strings = []
	for s in range(n):
		strings.append(input())
	string1 = strings[0]
	broke = False
	try1 = [k for k in string1]
	try2 = [k for k in string1]
	for s in range(1, n):
		diff = 0
		inds = []
		for b in range(m):
			if strings[s][b] == string1[b]:
				continue
			else:
				diff += 1
				inds.append((b, strings[s][b]))
		if diff >= 3:
			broke = True
			break
		if diff == 2:
			try1[inds[0][0]] = inds[0][1]
			try2[inds[1][0]] = inds[1][1]
			break
	broke = False
	for s in range(n):
		diffs = 0
		for b in range(m):
			if strings[s][b] == try1[b]:
				continue
			else:
				diffs += 1
		if diffs >= 2:
			broke = True
			break
	if broke == False:
		print(''.join(try1))
	else:
		broke = False
		for s in range(n):
			diffs = 0
			for b in range(m):
				if strings[s][b] == try2[b]:
					continue
				else:
					diffs += 1
			if diffs >= 2:
				broke = True
				break
		if broke == False:
			print(''.join(try2))
		else:
			print(-1)


import sys
from sys import flags
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())

def dist(s1, s2):
	m = len(s1)
	cnt = 0
	for i in range(m):
		if s1[i] != s2[i]:
			cnt += 1
	return cnt

def find_anchor(s1, s2):
	m = len(s1)
	cs = []
	for i in range(m):
		if s1[i] != s2[i]:
			cs.append((i, s1[i], s2[i]))
	anchor1 = list(s1)
	anchor1[cs[0][0]] = cs[0][2]
	anchor1 = ''.join(anchor1)
	anchor2 = list(s1)
	anchor2[cs[1][0]] = cs[1][2]
	anchor2 = ''.join(anchor2)
	return (anchor1, anchor2)

def satisfy(anchor, a, n):
	for i in range(n):
		if dist(anchor, a[i]) > 1:
			return False
	return True

def solve(a, n, m):
	mapping = {}
	for i in range(n - 1):
		for j in range(1, n):
			d = dist(a[i], a[j])
			mapping[i, j] = d
			if d >= 3:
				return '-1'
	flag = False
	anchors = None
	for ((i, j), d) in mapping.items():
		if d == 2:
			anchors = find_anchor(a[i], a[j])
			flag = True
			break
	if flag:
		for anchor in anchors:
			if satisfy(anchor, a, n):
				return anchor
		return '-1'
	else:
		return a[0]

def main():
	t = inp()
	for _ in range(t):
		(n, m) = inlt()
		a = [input().strip() for i in range(n)]
		ans = solve(a, n, m)
		print(ans)
main()


import itertools
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [''] * n
	for i in range(n):
		a[i] = list(input())
	if n == 1:
		for i in a[0]:
			print(i, end='')
		print()
		continue
	if m == 1:
		print('z')
		continue
	pat = []
	l = []
	for i in range(n - 1):
		p = [[] for _ in range(m)]
		for j in range(m):
			p[j].append(a[i][j])
			p[j].append(a[i + 1][j])
			p[j] = list(set(p[j]))
		if m == 1:
			l = list(itertools.product(p[0]))
		elif m == 2:
			l = list(itertools.product(p[0], p[1]))
		elif m == 3:
			l = list(itertools.product(p[0], p[1], p[2]))
		elif m == 4:
			l = list(itertools.product(p[0], p[1], p[2], p[3]))
		elif m == 5:
			l = list(itertools.product(p[0], p[1], p[2], p[3], p[4]))
		elif m == 6:
			l = list(itertools.product(p[0], p[1], p[2], p[3], p[4], p[5]))
		elif m == 7:
			l = list(itertools.product(p[0], p[1], p[2], p[3], p[4], p[5], p[6]))
		elif m == 8:
			l = list(itertools.product(p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]))
		elif m == 9:
			l = list(itertools.product(p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8]))
		elif m == 10:
			l = list(itertools.product(p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9]))
		pat = list(set(pat + list(l)))
	ans = []
	for p in pat:
		flg = True
		for i in range(n):
			cnt = 0
			for j in range(m):
				if a[i][j] == p[j]:
					pass
				else:
					cnt += 1
			if cnt > 1:
				flg = False
				break
		if flg:
			ans = p
			break
	if len(ans) > 0:
		for i in ans:
			print(i, end='')
		print()
	else:
		print(-1)


for _ in range(0, int(input())):
	(n, m) = map(int, input().split())
	strings = []
	for i in range(0, n):
		strings.append([*input()])
	if n == 1:
		print(''.join(strings[0]))
		continue
	if m == 1:
		print('a')
		continue
	possible = True
	maybe = False
	for i in range(1, n):
		counter = 0
		differ = []
		for j in range(0, m):
			if strings[0][j] != strings[i][j]:
				counter += 1
				if counter == 3:
					break
				differ.append(j)
		if counter > 2:
			possible = False
			break
		if counter == 2:
			model1 = strings[0].copy()
			model1[differ[0]] = strings[i][differ[0]]
			model2 = strings[0].copy()
			model2[differ[1]] = strings[i][differ[1]]
			maybe = True
	if maybe == True:
		flag1 = 0
		flag2 = 0
		for i in range(1, n):
			counter = 0
			for j in range(0, m):
				if model1[j] != strings[i][j]:
					counter += 1
					if counter == 2:
						flag1 = 1
						break
		for i in range(1, n):
			counter = 0
			for j in range(0, m):
				if model2[j] != strings[i][j]:
					counter += 1
					if counter == 2:
						flag2 = 1
						break
		if flag1 == 1 and flag2 == 1:
			print(-1)
			continue
		elif flag1 == 0:
			print(''.join(model1))
			continue
		else:
			print(''.join(model2))
			continue
	if possible == True:
		print(''.join(strings[0]))
	else:
		print(-1)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

def gift():
	for _ in range(t):
		(n, m) = list(map(int, input().split()))
		arrys = []
		for i in range(n):
			kap = list(input())
			arrys.append(kap)
		ans = []
		checkdiff = True
		for i in range(n):
			for j in range(i, n):
				if checkdiff:
					counter = 0
					for k in range(m):
						if arrys[i][k] != arrys[j][k]:
							counter += 1
						if counter > 2:
							checkdiff = False
							break
				else:
					break
		if checkdiff:
			for j in range(m):
				counterdic = {}
				for i in range(n):
					ele = arrys[i][j]
					freq = counterdic.get(ele, 0)
					counterdic[ele] = freq + 1
				if len(counterdic) == 1:
					ans.append(arrys[0][j])
				else:
					ans.append(list(counterdic.keys()))
			pans = ans[0]
			for j in range(1, m):
				tis = ans[j]
				tans = []
				if len(tis) == 1:
					for di in pans:
						di += tis
						tans.append(di)
				else:
					for di in pans:
						for ti in tis:
							diu = di + ti
							tans.append(diu)
				pans = tans
			gotans = False
			for ina in pans:
				ans = True
				for i in range(n):
					counter = 0
					for j in range(m):
						if ina[j] != arrys[i][j]:
							counter += 1
						if counter >= 2:
							ans = False
							break
				if ans:
					yield ina
					gotans = True
					break
			if not gotans:
				yield (-1)
		else:
			yield (-1)
t = int(input())
ans = gift()
print(*ans, sep='\n')


from copy import deepcopy
t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	s = []
	for i in range(n):
		s.append(list(input()))

	def diff(a, b):
		count = 0
		for i in range(0, len(a)):
			if a[i] != b[i]:
				count += 1
		return count
	flag1 = 0
	str = -1
	temp = deepcopy(s[0])
	for i in range(0, m):
		temp = deepcopy(s[0])
		for c in 'qwertyuiopasdfghjklzxcvbnm':
			temp[i] = c
			flag = 1
			for l in s[1:]:
				if diff(l, temp) > 1:
					flag = 0
					break
			if flag == 1:
				flag1 = 1
				break
		if flag1 == 1:
			break
	if flag1 == 1:
		print(''.join(temp))
	else:
		print(-1)


import math as mt
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [0] * n
	for i in range(n):
		a[i] = input()
	temp = a[0]
	sz = len(a[0])
	ans = []
	for i in range(sz):
		for j in range(26):
			use = temp
			use = list(temp)
			use[i] = chr(ord('a') + j)
			flag = 1
			for k in range(n):
				diff = 0
				for l in range(sz):
					if a[k][l] != use[l]:
						diff = diff + 1
				if diff > 1:
					flag = 0
			if flag == 1:
				ans = use
	if len(ans) == 0:
		print(-1)
	else:
		for i in range(len(ans)):
			print(ans[i], end='')
		print('')


alp = 'abcdefghijklmnopqrstuvwxyz'
for loop in range(int(input())):
	(n, m) = map(int, input().split())
	a = [tuple(input()) for _ in range(n)]
	found = False
	for i in range(n):
		for j in range(m):
			for k in range(26):
				ans = list(a[i][:])
				ans[j] = alp[k]
				dif = [0] * n
				for x in range(n):
					for y in range(m):
						if a[x][y] != ans[y]:
							dif[x] += 1
				if max(dif) <= 1:
					found = True
					break
			if found:
				break
		if found:
			break
	print(''.join(ans) if found else -1)


def main_function():
	from sys import stdin
	from sys import stdout
	input = stdin.readline
	print = stdout.write

	def check_strings(ix=0):
		if ix == len(diff_options):
			considered_str[-1] = True
			return
		elif len(diff_options[ix]) == 1:
			considered_str[ix] = diff_options[ix][0]
			check_strings(ix + 1)
		else:
			indexes = []
			for i in range(len(diff_options[ix])):
				considered_str[ix] = diff_options[ix][i]
				for j in range(len(indexes)):
					counter_other_char[indexes[j]] = 0
				indexes = []
				for j in range(len(memo)):
					if memo[j][ix] != considered_str[ix] and counter_other_char[j] != 0:
						break
					elif memo[j][ix] != considered_str[ix]:
						counter_other_char[j] = 1
						indexes.append(j)
				else:
					for j in range(1, len(indexes)):
						if memo[indexes[j]][ix + 1:] != memo[indexes[j - 1]][ix + 1:]:
							break
					else:
						check_strings(ix + 1)
						if considered_str[-1]:
							return
	t = int(input())
	for _ in range(t):
		(n, m) = list(map(int, input().split()))
		memo = [input()[:-1] for i in range(n)]
		diff_options = [[] for i in range(m)]
		counter_other_char = [0] * n
		for i in range(n):
			for j in range(m):
				diff_options[j].append(memo[i][j])
		for i in range(m):
			diff_options[i] = sorted(list(set(diff_options[i])))
		considered_str = ['' for i in range(m + 1)]
		considered_str[-1] = False
		check_strings()
		if considered_str[-1]:
			print(''.join(considered_str[:-1]) + '\n')
		else:
			print('-1\n')
main_function()


def checkValid(a, s):
	for i in range(len(a)):
		count = 0
		for j in range(len(a[0])):
			if a[i][j] != s[j]:
				count += 1
		if count > 1:
			return 0
	return 1
for x in range(int(input())):
	a = []
	(n, m) = map(int, input().split())
	for y in range(n):
		a.append(input())
	s = a[0]
	var = 0
	var1 = 0
	for i in range(len(s)):
		for j in range(97, 123):
			arr = list(s)
			arr[i] = chr(j)
			s = ''.join(arr)
			if checkValid(a, s) == 1:
				print(s)
				var = 1
				break
			else:
				s = a[0]
		if var == 1:
			var1 = 1
			break
	if var1 == 0:
		print('-1')


t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	l = []
	for i in range(n):
		s = input()
		l.append(s)
	ans = ''
	dict = {}
	for i in range(m):
		flag = 0
		for j in range(26):
			li = []
			flag2 = 0
			for k in range(n):
				if ord(l[k][i]) - 97 != j and dict.get(k) is not None:
					flag2 = 1
					break
				if ord(l[k][i]) - 97 != j:
					li.append(l[k][i + 1:])
			if flag2 == 1:
				continue
			if len(list(set(li))) <= 1:
				ans += chr(j + 97)
				flag = 1
				for k in range(n):
					if ord(l[k][i]) - 97 != j:
						dict[k] = 1
				break
		if flag == 0:
			ans = -1
			break
	print(ans)


def solve():
	(n, m) = map(int, input().split())
	grid = [input() for _ in range(n)]
	if m == 1 or n == 1:
		return grid[0]
	string = list(grid[0])
	for idx in range(m):
		curr = string[idx]
		for c in range(26):
			string[idx] = chr(c + 97)
			flag = True
			for i in range(n):
				cnt = 0
				for j in range(m):
					if grid[i][j] != string[j]:
						cnt += 1
				if cnt > 1:
					break
			else:
				return ''.join(string)
		string[idx] = curr
	return -1
for _ in range(int(input())):
	print(solve())


from sys import stdin, stdout, setrecursionlimit
from collections import deque, defaultdict
import math
rl = lambda : stdin.readline()
rll = lambda : stdin.readline().split()
rli = lambda : map(int, stdin.readline().split())
(INF, NINF) = (float('inf'), float('-inf'))

def main():
	T = int(rl())
	tochar = lambda n: chr(n + 97)

	def nbhrs(s):
		nbhrset = set()
		for i in range(len(s)):
			for nc in range(26):
				newstr = ''.join((s[j] if j != i else tochar(nc) for j in range(len(s))))
				nbhrset.add(newstr)
		return nbhrset
	for _ in range(T):
		(n, m) = rli()
		S = []
		choices = []
		for __ in range(n):
			S.append(rll()[0])
			choices.append(nbhrs(S[-1]))
		for i in range(1, len(choices)):
			choices[i] = choices[i].intersection(choices[i - 1])
		if len(choices[-1]) > 0:
			print(choices[-1].pop())
		else:
			print('-1')
	stdout.close()
main()


def check(cand, arr):
	for item in arr:
		ans = 0
		for x in range(len(item)):
			if item[x] != cand[x]:
				ans += 1
		if ans > 1:
			return 0
	return 1

def solve(arr, n, m):
	cand = [x for x in arr[0]]
	for x in range(m):
		temp = cand[x]
		for c in range(26):
			cand[x] = chr(c + 97)
			if check(cand, arr):
				return cand
		cand[x] = temp
	return -1
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	arr = []
	while n:
		arr.append(input())
		n -= 1
	ans = solve(arr, n, m)
	if ans != -1:
		print(''.join(ans))
	else:
		print(-1)


def solve():
	pairwise = [[dist(a[i], a[j]) for i in range(n)] for j in range(n)]
	if max([max(i) for i in pairwise]) > 2:
		return -1
	elif max([max(i) for i in pairwise]) < 2:
		return a[0]
	possible = None
	for i in range(n):
		for j in range(i):
			if pairwise[i][j] == 2:
				ss = get_possible(a[i], a[j])
				possible = update_pos(possible, ss)
	ps = []
	for p in possible:
		pos = True
		for s in a:
			if dist(p, s) > 1:
				pos = False
		if pos:
			ps.append(p)
	if ps:
		return ps[0]
	else:
		return -1

def dist(s1, s2):
	r = 0
	for k in range(m):
		if s1[k] != s2[k]:
			r += 1
	return r

def update_pos(possible, ss):
	r = []
	if possible == None:
		r = ss
	else:
		for s in ss:
			if s in possible:
				r.append(s)
	return r

def get_possible(s1, s2):
	r1 = []
	r2 = []
	first = True
	for k in range(m):
		if s1[k] == s2[k]:
			r1.append(s1[k])
			r2.append(s1[k])
		elif s1[k] != s2[k] and first:
			r1.append(s1[k])
			r2.append(s2[k])
			first = False
		else:
			r2.append(s1[k])
			r1.append(s2[k])
	return [''.join(r1), ''.join(r2)]
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [input() for _ in range(n)]
	print(solve())


import sys

def check():
	global n, m
	for i in range(n):
		count = 0
		for j in range(m):
			if not list_answer[j] == list_word[i][j]:
				count += 1
			if count > 1:
				return False
	return True
T = int(sys.stdin.readline())
for _ in range(T):
	(n, m) = map(int, sys.stdin.readline().split())
	list_word = [sys.stdin.readline().strip() for _ in range(n)]
	list_answer = list(list_word[0])
	list_a = [set() for _ in range(m)]
	for i in range(n):
		for j in range(m):
			list_a[j].add(list_word[i][j])
	end = 0
	for j in range(m):
		while list_a[j]:
			now_word = list_a[j].pop()
			list_answer[j] = now_word
			if check():
				end = 1
				break
		if end:
			break
	if end:
		print(''.join(list_answer))
	else:
		print(-1)


import os
import sys
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		a = [input() for _ in range(n)]

		def chk(ans):
			for s in a:
				cnt = 0
				for j in range(m):
					cnt += ans[j] != s[j]
				if cnt > 1:
					return False
			return True
		if chk(a[0]):
			print(a[0])
			continue
		fl = True
		for i in range(m):
			if not fl:
				break
			for k in range(n):
				if a[k][i] == a[0][i]:
					continue
				if chk(a[0][0:i] + a[k][i] + a[0][i + 1:]):
					print(a[0][0:i] + a[k][i] + a[0][i + 1:])
					fl = False
					break
		if fl:
			print(-1)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()