You are given n k-digit integers. You have to rearrange the digits in the integers so that the difference between the largest and the smallest number was minimum. Digits should be rearranged by the same rule in all integers.

Input

The first line contains integers n and k — the number and digit capacity of numbers correspondingly (1 ≤ n, k ≤ 8). Next n lines contain k-digit positive integers. Leading zeroes are allowed both in the initial integers and the integers resulting from the rearranging of digits.

Output

Print a single number: the minimally possible difference between the largest and the smallest number after the digits are rearranged in all integers by the same rule.

Examples

Input

6 4
5237
2753
7523
5723
5327
2537


Output

2700


Input

3 3
010
909
012


Output

3


Input

7 5
50808
36603
37198
44911
29994
42543
50156


Output

20522

Note

In the first sample, if we rearrange the digits in numbers as (3,1,4,2), then the 2-nd and the 4-th numbers will equal 5237 and 2537 correspondingly (they will be maximum and minimum for such order of digits).

In the second sample, if we swap the second digits and the first ones, we get integers 100, 99 and 102.

Difficulty: MEDIUM
Tags: Combinatorics

Implementation

Complete search
Skill types: Complete search

Starter code:

Solutions:
import sys
data = sys.stdin.read().split()
data_ptr = 0

def data_next():
	global data_ptr, data
	data_ptr += 1
	return data[data_ptr - 1]
N = int(data_next())
K = int(data_next())
arr = []
for i in range(N):
	arr.append(list(data_next()))
perm = []
for i in range(K):
	perm.append(str(i))

def next_perm():
	global perm, arr
	for i in reversed(range(len(perm) - 1)):
		if perm[i] < perm[i + 1]:
			break
	else:
		return False
	for j in reversed(range(i + 1, len(perm))):
		if perm[i] < perm[j]:
			break
	(perm[i], perm[j]) = (perm[j], perm[i])
	perm[i + 1:] = reversed(perm[i + 1:])
	for k in range(len(arr)):
		(arr[k][i], arr[k][j]) = (arr[k][j], arr[k][i])
		arr[k][i + 1:] = reversed(arr[k][i + 1:])
	return True
ans = 1000000000
while True:
	ans = min(ans, int(''.join(max(arr))) - int(''.join(min(arr))))
	if not next_perm():
		break
print(ans)


from itertools import permutations
(n, k) = map(int, input().split())
ar = [input() for i in range(n)]
ans = float('inf')
for p in permutations(range(k)):
	mx = 0
	mn = float('inf')
	for e in ar:
		cur = 0
		for i in p:
			cur = 10 * cur + int(e[i])
		mx = max(mx, cur)
		mn = min(mn, cur)
	ans = min(ans, mx - mn)
print(ans)


from itertools import permutations
(n, k) = map(int, input().split())
a = []
mn = float('inf')
for _ in range(n):
	line = input()
	a.append(list(permutations(line)))
for arr in zip(*a):
	ints = [int(''.join(num)) for num in arr]
	mn = min(mn, max(ints) - min(ints))
print(mn)


from itertools import permutations
(n, k) = map(int, input().split())
A = []
for i in range(n):
	A.append(input())
permutation = []
for i in range(n):
	permutation.append(list(permutations(A[i], k)))
result = float('inf')
for i in range(len(permutation[0])):
	nums = []
	for j in range(n):
		nums.append(int(''.join(map(str, permutation[j][i]))))
	result = min(max(nums) - min(nums), result)
print(result)


import itertools
(n, k) = [int(i) for i in input().split()]
comb = list(itertools.permutations(range(k), k))
orig = []
d = 9999999999
for j in range(n):
	orig.append(input())
for com in comb:
	maxx = 0
	minn = 100000000
	for l in orig:
		x = ''
		for z in range(k):
			x += l[com[z]]
		if int(x) > maxx:
			maxx = int(x)
		if int(x) < minn:
			minn = int(x)
	if d > maxx - minn:
		d = maxx - minn
print(d)


import sys
input = sys.stdin.readline
from itertools import permutations

def transform(num, p, k):
	new_num = [None] * k
	for (cur_i, num_i) in enumerate(p):
		new_num[cur_i] = num[num_i]
	return int(''.join(new_num))
(n, k) = map(int, input().split())
nums = []
if n == 1:
	print(0)
else:
	for _ in range(n):
		nums.append(input().rstrip())
	diff = float('inf')
	for p in permutations(range(k)):
		transformed = [transform(num, p, k) for num in nums]
		transformed.sort()
		diff = min(diff, transformed[-1] - transformed[0])
	print(diff)


from itertools import permutations

def ap(t, p):
	return [t[q] for q in p]
(n, k) = map(int, input().split())
s = [input() for i in range(n)]
ans = 10 ** 100
for p in permutations(range(k)):
	u = [int(''.join(ap(t, p))) for t in s]
	ans = min(ans, max(u) - min(u))
print(ans)


from itertools import permutations as p
from collections import Counter as count
(n, k) = list(map(int, input().split()))
z = [[] for i in range(k)]
for i in range(n):
	s = input()
	for j in range(k):
		z[j].append(s[j])
s = list(p(z))
z = []
for i in s:
	l = []
	for a in zip(*i):
		l.append(int(''.join(a)))
	z.append(max(l) - min(l))
print(min(z))


from itertools import permutations
(n, k) = list(map(int, input().split(' ')))
permutacoes = []
for i in range(n):
	x = list(input())
	permuts = [''.join(x) for x in list(permutations(x))]
	permuts = list(map(int, permuts))
	permutacoes.append(permuts)
menor_dif = 10000000000
for i in range(len(permutacoes[0])):
	p = []
	for j in range(len(permutacoes)):
		aux = permutacoes[j][i]
		p.append(aux)
	dif = max(p) - min(p)
	if dif < menor_dif:
		menor_dif = dif
print(menor_dif)


from itertools import permutations
(n, k) = map(int, input().split())
l = []
perm = permutations([x for x in range(k)])
for i in range(n):
	l.append(int(input()))
diff = 10 ** 9
for i in perm:
	(mi, ma) = (10 ** 9, 0)
	for j in l:
		num = 0
		for a in range(k):
			num = num + 10 ** a * (j // 10 ** i[a] % 10)
		mi = min(mi, num)
		ma = max(ma, num)
	diff = min(diff, ma - mi)
print(diff)


import itertools
(nums, digits) = [int(x) for x in input().split()]
possibilities = zip(*[[int(''.join(permut)) for permut in itertools.permutations(input())] for y in range(nums)])
xs = list(possibilities)
minimum = None
for x in xs:
	local_min = max(x) - min(x)
	if minimum is None or local_min < minimum:
		minimum = local_min
print(minimum)


(n, k) = map(int, input().split())

def solve(x='', i=0):
	if i == 0:
		global perm
		perm = []
	if i == k:
		perm.append(x)
		return
	for j in range(1, k + 1):
		if str(j) not in x:
			solve(x + str(j), i + 1)
solve()

def yes(a, p):
	b = ''
	for x in p:
		b += a[int(x) - 1]
	return int(b)

def wow(ar, p):
	(maxi, mini) = (0, 1000000000.0)
	for x in ar:
		maxi = max(yes(x, p), maxi)
		mini = min(yes(x, p), mini)
	return maxi - mini
ar = []
while n:
	n -= 1
	ar.append(input())
ans = wow(ar, '12345678'[:k])
for p in perm:
	ans = min(ans, wow(ar, p))
print(ans)


from itertools import *
(n, k) = map(int, input().split())
a = []
for i in range(n):
	a.append([i for i in input()])
l = []
for i in range(k):
	l.append(i)
perm = permutations(l)
ans = 10 ** 9
for now in perm:
	curr = list(now)
	mx = 0
	mn = 10 ** 9
	for i in a:
		d = ''
		for j in range(k):
			d += i[curr[j]]
		mx = max(mx, int(d))
		mn = min(mn, int(d))
	ans = min(ans, mx - mn)
print(ans)


import itertools, sys
(n, k) = [int(x) for x in input().split()]
perms = zip(*[[int(''.join(p)) for p in itertools.permutations(input())] for y in range(n)])
perms = list(perms)
minimum = float('inf')
for p in perms:
	temp = max(p) - min(p)
	if temp < minimum:
		minimum = temp
print(minimum)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
from collections import defaultdict
from itertools import permutations
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')
(n, d) = [int(x) for x in input().split()]
li = []
for i in range(n):
	s = input()
	li.append(s)
st = ''
for i in range(0, d):
	st += str(i)
from itertools import permutations
max_diff = 10 ** 9
for i in permutations(st):
	ans = []
	for j in i:
		ans.append(int(j))
	aa = []
	for j in li:
		k = ''
		for m in ans:
			k += j[m]
		aa.append(int(k))
	(mam, mim) = (max(aa), min(aa))
	max_diff = min(mam - mim, max_diff)
print(max_diff)


from itertools import permutations
(n, k) = map(int, input().split())
print(min((max(k) - min(k) for k in zip(*[[int(''.join(j)) for j in permutations(input())] for i in range(n)]))))


from itertools import permutations
(n, k) = map(int, input().split())
perm = permutations(range(k), k)
a = []
for _ in range(n):
	a += [input()]
maxDiff = 10 ** 9
for p in perm:
	minp = '9' * k
	maxp = '0' * k
	for i in range(n):
		t = ''.join(map(lambda x: a[i][p[x]], range(k)))
		minp = min(t, minp)
		maxp = max(t, maxp)
	diff = int(maxp) - int(minp)
	if diff < maxDiff:
		maxDiff = diff
print(maxDiff)


(n, d) = [int(x) for x in input().split()]
li = []
for i in range(n):
	s = input()
	li.append(s)
st = ''
for i in range(0, d):
	st += str(i)
from itertools import permutations
max_diff = 10 ** 9
for i in permutations(st):
	ans = []
	for j in i:
		ans.append(int(j))
	aa = []
	for j in li:
		k = ''
		for m in ans:
			k += j[m]
		aa.append(int(k))
	(mam, mim) = (max(aa), min(aa))
	max_diff = min(mam - mim, max_diff)
print(max_diff)


from itertools import permutations
(n, k) = map(int, input().split())
pl = [permutations(input()) for i in range(n)]
cnt = k
ans = 10 ** k
for i in range(2, k):
	cnt *= i
for i in range(cnt):
	(tmax, tmin) = (0, 10 ** k)
	for i in range(n):
		t = int(''.join(next(pl[i])))
		if t > tmax:
			tmax = t
		if t < tmin:
			tmin = t
	ans = min(ans, tmax - tmin)
print(ans)


from itertools import permutations
(n, a) = map(int, input().split())
lis = []
mx = 0
mi = 10000000000
ans = 1000000000
perm = permutations([i for i in range(1, a + 1)])
for i in range(n):
	b = list(input())
	lis.append(b)
for i in perm:
	mx = 0
	mi = 100000000000
	for k in lis:
		now = ''
		for j in i:
			now += k[j - 1]
		mx = max(mx, int(now))
		mi = min(mi, int(now))
	ans = min(ans, mx - mi)
print(ans)


from itertools import permutations

def main():
	(n, k) = [int(elem) for elem in input().split()]
	a = []
	ans = 1 << 31
	for _ in range(n):
		p = input()
		a.append(list(permutations(p)))
	for elem in zip(*a):
		ints = [int(''.join(num)) for num in elem]
		ans = min(ans, max(ints) - min(ints))
	print(ans)
main()


from itertools import permutations
(n, nDig) = map(int, input().split())
a = [list(input()) for _ in range(n)]
vals = [[] for _ in range(n)]
for (i, digs) in enumerate(a):
	for p in permutations(digs):
		vals[i].append(int(''.join(p)))
ret = float('inf')
for p in zip(*vals):
	ret = min(ret, max(p) - min(p))
print(ret)


import math
import itertools
(n, k) = map(int, input().split())
numbers = []
for i in range(n):
	numbers.append(input())
permutations = []
for number in numbers:
	curr = [int(''.join(perm)) for perm in itertools.permutations(number)]
	permutations.append(curr)
possibilities = [[] for i in range(math.factorial(k))]
for i in range(n):
	for j in range(math.factorial(k)):
		possibilities[j].append(permutations[i][j])
minimum = 99999999
for poss in possibilities:
	minimum = min(max(poss) - min(poss), minimum)
print(minimum)


from math import factorial as fact
from itertools import *
(n, k) = map(int, input().split())
a = []
for i in range(n):
	a.append(input())
b = []
for i in range(n):
	b.append(list(permutations(a[i])))
s = 1000000000000
for i in range(fact(k)):
	c = []
	for j in range(n):
		c.append(int(''.join(b[j][i])))
	mx = max(c)
	mn = min(c)
	if mx - mn < s:
		s = mx - mn
print(s)


from itertools import permutations
(n, k) = map(int, input().split())
min_diff = 10 ** 9
tab = []
for _ in range(n):
	tab += [list(input())]
for digit_map in permutations(list(range(k))):
	perm_nums = []
	for num in tab:
		perm_nums += [int(''.join([num[i] for i in digit_map]))]
	perm_nums.sort()
	min_diff = min([min_diff, perm_nums[-1] - perm_nums[0]])
print(min_diff)


from itertools import permutations
(n, k) = map(int, input().split())
N = []
for i in range(n):
	N.append(permutations(input().strip()))
ans = 1000000000
try:
	while True:
		X = []
		for i in range(n):
			X.append(int(''.join(next(N[i]))))
		diff = max(X) - min(X)
		if diff < ans:
			ans = diff
except StopIteration:
	print(ans)


import itertools

def s():
	[n, k] = list(map(int, input().split()))
	a = [list(input()) for _ in range(n)]
	r = 10 ** 9
	for i in itertools.permutations(range(k)):
		mi = 10 ** 9
		ma = 0
		for j in a:
			c = int(''.join([str(j[i[l]]) for l in range(k)]))
			mi = min(mi, c)
			ma = max(ma, c)
		r = min(ma - mi, r)
	print(r)
s()


import itertools as it
(n, k) = [int(i) for i in input().split()]
a = [list(map(int, input())) for i in range(n)]
p = [10 ** j for j in range(k)][::-1]
m = 99999999999999
(mmx, mmn) = (0, 9999999999)
for i in it.permutations(p):
	(mx, mn) = (0, 9999999999)
	for j in a:
		s = sum([k * t for (k, t) in zip(i, j)])
		mx = mx if mx > s else s
		mn = mn if mn < s else s
		if mx - mn > m:
			break
	d = mx - mn
	if d < m:
		m = d
print(m)


from itertools import permutations
(n, k) = map(int, input().split())
l = []
for i in range(n):
	l.append(input())
perm = []
for i in range(n):
	perm.append(list(permutations(l[i])))
f = 0
for i in range(len(perm[0])):
	temp = []
	for j in range(n):
		temp.append(int(''.join(perm[j][i])))
	diff = max(temp) - min(temp)
	if f == 0:
		ans = diff
		f = 1
	elif diff < ans:
		ans = diff
print(ans)


import itertools
(n, k) = map(int, input().split())
a = list(range(k))
b = []
for i in range(n):
	b.append(input())
ans = 10 ** 10
for z in itertools.permutations(a):
	(m1, m2) = (10 ** 10, 0)
	for p in b:
		s = ''
		for i in z:
			s += p[i]
		x = int(s)
		(m1, m2) = (min(m1, x), max(m2, x))
	ans = min(ans, m2 - m1)
print(ans)


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()
import sys
input = sys.stdin.readline
scanner = lambda : int(input())
string = lambda : input().rstrip()
get_list = lambda : list(read())
read = lambda : map(int, input().split())
get_float = lambda : map(float, input().split())

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def fact(x):
	val = 1
	while x > 0:
		val *= x
		x -= 1
	return val

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

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

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

def is_integer(n):
	return math.ceil(n) == math.floor(n)

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

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 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 and n > 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)]
	(prime[0], prime[1]) = (False, False)
	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

def phi(n):
	result = n
	p = 2
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			result = result * (1.0 - 1.0 / float(p))
		p = p + 1
	if n > 1:
		result = result * (1.0 - 1.0 / float(n))
	return int(result)

def is_prime(n):
	if n == 0:
		return False
	if n == 1:
		return True
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True

def next_prime(n, primes):
	while primes[n] != True:
		n += 1
	return n
MAXN = int(100000.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
spf = [0 for i in range(MAXN)]

def factoriazation(x):
	res = []
	for i in range(2, int(x ** 0.5) + 1):
		while x % i == 0:
			res.append(i)
			x //= i
	if x != 1:
		res.append(x)
	return res

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

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

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()

def binary_search(low, high, w, h, n):
	while low < high:
		mid = low + (high - low) // 2
		if check(mid, w, h, n):
			low = mid + 1
		else:
			high = mid
	return low

def check(beauty, s, n, count):
	pass
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
alphs = 'abcdefghijklmnopqrstuvwxyz'
from itertools import permutations
import math
import bisect as bis
import random
import sys
import collections as collect

def solve():
	(n, k) = read()
	val = []
	for i in range(n):
		s = string()
		val.append(list(permutations(s)))
	m = INF
	for arr in zip(*val):
		a = [int(''.join(num)) for num in arr]
		m = min(m, max(a) - min(a))
	print(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')

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')
for i in range(1):
	solve()


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

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

def S():
	return str(input())

def L():
	return list(R())
from collections import Counter
import math
import sys

def check(a):
	global num
	num2 = num.copy()
	for i in range(len(num)):
		xx = list(num2[i])
		xx = [xx[a[i]] for i in range(n)]
		xx = ''.join(xx)
		num2[i] = int(xx)
	return max(num2) - min(num2)
from itertools import permutations
(k, n) = R()
num = []
a = list(range(n))
for _ in range(k):
	num.append(list(permutations(S())))
min_dif = math.inf
num2 = zip(*num)
for i in num2:
	j = [int(''.join(k)) for k in i]
	min_dif = min(min_dif, max(j) - min(j))
print(min_dif)