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

public class Permutation {

	static HashSet<String> perm;
	static int n,k;

	static String toString(int[] idx) {
		StringBuilder sb = new StringBuilder("");
		for(int i=0;i<k;i++)
			sb.append(""+idx[i]);
		return sb.toString();

	}

	static void permutations(int[] idx,int i) {
		perm.add(toString(idx));
		if(i<k-1) permutations(idx,i+1);
		for(int j=i+1;j<k;j++) {
			swap(idx,i,j);
			permutations(idx,i+1);
			swap(idx,j,i);
		}
	}

	static void swap(int idx[],int a, int b) {
		int remp = idx[b];
		idx[b] = idx[a];
		idx[a] = remp;
	}

	public static void main(String[] args) {
        FastScanner in = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);
        n = in.nextInt(); k = in.nextInt();
        char ch[][] = new char[n][k];
        for(int i=0;i<n;i++) {
        	ch[i] = in.next().toCharArray();
        }
        perm = new HashSet<>();
        int idx[] = new int[k];
        for(int i=1;i<=k;i++) idx[i-1] = i;
        for(int i=0;i<k;i++) {
        	swap(idx,0,i);
        	permutations(idx,0);
        }
        int ans = Integer.MAX_VALUE;
        for(String str : perm) {
        	int max = 0, min =Integer.MAX_VALUE;
        	char c[] = str.toCharArray();
        	for(int i=0;i<n;i++) {
        		int x = 0;
        		for(char y : c) {
        			x = 10*x + (ch[i][(y-'1')]-'0');
        		}
        		min = Math.min(min, x);
        		max = Math.max(max, x);
        	}
        	ans = Math.min(ans, max-min);
        }
        out.println(ans);
        out.flush();
	}

	static class FastScanner {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer("");

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

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

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

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

		Integer[] readArray(long n) {
		    Integer a[] = new Integer[(int)n];
			for(int i=0;i<n;i++) a[i] = nextInt();
			return a;
		}

		long[] readArray(int n,long x) {
			long a[] = new long[n];
			for(int i=0;i<n;i++) a[i] = nextLong();
			return a;
		}

	}

	static class Pair implements Comparable<Pair> {
		int x, y;
		Pair(int a, int b){ x = a; y = b; }
		int getKey() { return x; }
		int getVal() { return y; }
		@Override
		public int compareTo(Pair o) {
			if(o.getVal() - this.getVal()>0)
				return -1;
			else if(o.getVal() - this.getVal()<0)
				return 1;
			else
				return 0;
		}

	}

	static boolean arrayEquals(char a[], char b[]) {
		int n = a.length;
		boolean verdict = true;
		for(int i=0;i<n;i++) {
			if(a[i]!=b[i]) {
				verdict = false;break;
			}
		}
		return verdict;
	}

	static long lcm(long a, long b) {
		return (a*b)/gcd(a,b);
	}

	static long gcd(long a, long b) {
		if(b==0) return a;
		else return gcd(b,a%b);
	}

	static long hashInt(int x,int y) {
		return x*(1_000_000_000L)+y;
	}
}

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Scanner;

public class B {

	static int getValue(String num, int perm[])
	{
		int res = 0;
		for(int i = 0; i < perm.length; i++)
			res = res * 10 + (num.charAt(perm[i]) - '0');
		return res;
	}
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		ArrayList<String> nums = new ArrayList<String>();
		int n = in.nextInt();
		int k = in.nextInt();
		for(int i = 0; i < n;i++)
		{
			String l = in.nextInt() + "";
			while(l.length() < k) l = "0" + l;
			nums.add(l);
		}

		PermutationGenerator p = new PermutationGenerator(k);
		int result = Integer.MAX_VALUE;
		while(p.hasMore())
		{
			int min = Integer.MAX_VALUE;
			int max = Integer.MIN_VALUE;

			int ind[] = p.getNext();
//			for(int i = 0; i < ind.length; i++) System.out.print(ind[i]); System.out.println();
			for(int i = 0; i < nums.size(); i++)
			{
				int a = getValue(nums.get(i), ind);
				if(a < min) min = a;
				if(a > max) max = a;
			}
			if(result > Math.abs(min - max)) result = Math.abs(min - max);
		}
		System.out.println(result);
	}

}

class PermutationGenerator {

  private int[] a;
  private BigInteger numLeft;
  private BigInteger total;

  //-----------------------------------------------------------
  // Constructor. WARNING: Don't make n too large.
  // Recall that the number of permutations is n!
  // which can be very large, even when n is as small as 20 --
  // 20! = 2,432,902,008,176,640,000 and
  // 21! is too big to fit into a Java long, which is
  // why we use BigInteger instead.
  //----------------------------------------------------------

  public PermutationGenerator (int n) {
    if (n < 1) {
      throw new IllegalArgumentException ("Min 1");
    }
    a = new int[n];
    total = getFactorial (n);
    reset ();
  }

  //------
  // Reset
  //------

  public void reset () {
    for (int i = 0; i < a.length; i++) {
      a[i] = i;
    }
    numLeft = new BigInteger (total.toString ());
  }

  //------------------------------------------------
  // Return number of permutations not yet generated
  //------------------------------------------------

  public BigInteger getNumLeft () {
    return numLeft;
  }

  //------------------------------------
  // Return total number of permutations
  //------------------------------------

  public BigInteger getTotal () {
    return total;
  }

  //-----------------------------
  // Are there more permutations?
  //-----------------------------

  public boolean hasMore () {
    return numLeft.compareTo (BigInteger.ZERO) == 1;
  }

  //------------------
  // Compute factorial
  //------------------

  private static BigInteger getFactorial (int n) {
    BigInteger fact = BigInteger.ONE;
    for (int i = n; i > 1; i--) {
      fact = fact.multiply (new BigInteger (Integer.toString (i)));
    }
    return fact;
  }

  //--------------------------------------------------------
  // Generate next permutation (algorithm from Rosen p. 284)
  //--------------------------------------------------------

  public int[] getNext () {

    if (numLeft.equals (total)) {
      numLeft = numLeft.subtract (BigInteger.ONE);
      return a;
    }

    int temp;

    // Find largest index j with a[j] < a[j+1]

    int j = a.length - 2;
    while (a[j] > a[j+1]) {
      j--;
    }

    // Find index k such that a[k] is smallest integer
    // greater than a[j] to the right of a[j]

    int k = a.length - 1;
    while (a[j] > a[k]) {
      k--;
    }

    // Interchange a[j] and a[k]

    temp = a[k];
    a[k] = a[j];
    a[j] = temp;

    // Put tail end of permutation after jth position in increasing order

    int r = a.length - 1;
    int s = j + 1;

    while (r > s) {
      temp = a[s];
      a[s] = a[r];
      a[r] = temp;
      r--;
      s++;
    }

    numLeft = numLeft.subtract (BigInteger.ONE);
    return a;

  }

}

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;

// am just trying :D //
public class B_92 {

    static ArrayList<String> a = new ArrayList<String>();

    public static void perm(boolean[] used, char[] out, char[] its, int len,
            int len2) {
        if (len2 == len) {
            a.add((new String(out)));

            //System.out.println(new String(out));
            return;
        }
        for (int i = 0; i < len; i++) {
            if (!used[i]) {
                out[len2] = its[i];
                used[i] = true;
                perm(used, out, its, len, len2 + 1);
                used[i] = false;
            }
        }
    }

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);

        int n = s.nextInt();

        int k = s.nextInt();

        boolean[] used = new boolean[k];
        char[] out = new char[k];

        char [] arr = {'0','1','2','3','4','5','6','7','8'};

        perm(used, out, arr, k, 0);

        String [] items = new String [n];

        for(int i = 0 ; i < n ; i ++)
        {
            items[i] = s.next();

        }

        int [] temp = new int[items.length];

        int first = -1 ; int second = -1 ;
        int max = 999999999;

        for(int i = 0 ; i < a.size() ; i++)
        {
            for(int j = 0 ; j < items.length ; j++)
            {
                String ele = "";

                for(int oo = 0 ; oo < a.get(i).length(); oo++)
                {
                    ele+= items[j].charAt(Integer.parseInt(a.get(i).charAt(oo)+""));
                }
                temp[j] = Integer.parseInt(ele);
            }

            Arrays.sort(temp);
            first = temp[temp.length - 1] ;
            second = temp[0];

            if(first-second < max){
                max = first - second;
            }

        }

        System.out.println(max);
    }
}

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

public class Main {

    static boolean FROM_FILE = false;

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;
        public FastReader() {
            if (FROM_FILE) {
                try {
                    br = new BufferedReader(new FileReader("input.txt"));
                } catch (IOException error) {
                }
            } else {
                br = new BufferedReader(new InputStreamReader(System.in));
            }
        }
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException  e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }
        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

    static int n, k;
    static char[][] original;
    static int res;

    static void dfs(int i, char[][] current, ArrayList<Integer> choice) {
        if (i == k) {
            int min_val = Integer.MAX_VALUE, max_val = Integer.MIN_VALUE;
            for (int k = 0; k < n; k += 1) {
                int num = Integer.parseInt(String.valueOf(current[k]));
                min_val = Math.min(min_val, num);
                max_val = Math.max(max_val, num);
            }
            // System.out.println(max_val + " " + min_val);
            res = Math.min(res, max_val - min_val);
            return;
        }
        for (Integer idx : new ArrayList<Integer>(choice)) {
            choice.remove(idx);
            for (int k = 0; k < n; k += 1) current[k][i] = original[k][idx];
            dfs(i + 1, current, choice);
            choice.add(idx);
        }
    }

    public static void main(String[] args) {
        FastReader fr = new FastReader();
        PrintWriter out = null;
        if (FROM_FILE) {
            try {
                out = new PrintWriter(new FileWriter("output.txt"));
            } catch (IOException error) {

            }
        } else {
            out = new PrintWriter(new OutputStreamWriter(System.out));
        }
        n = fr.nextInt(); k = fr.nextInt();
        original = new char[n][];
        for (int i = 0; i < n; i += 1) {
            original[i] = fr.nextLine().toCharArray();
        }
        res = Integer.MAX_VALUE;
        char[][] current = new char[n][k];
        ArrayList<Integer> choice = new ArrayList<>();
        for (int i = 0; i < k; i += 1) choice.add(i);
        dfs(0, current, choice);
        out.println(res);

        out.flush();
    }
}

import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;

public class Contest {
	private static PrintWriter out = new PrintWriter(System.out);
	private static final Random random = new Random();
	private static int n, m, k, tc, x;
	private static char[][] a;
	private static int res = 0;
	private static int[] perm;
	private static boolean[] vis;

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		k = sc.nextInt();
		a = new char[n][k];
		perm = new int[k];
		vis = new boolean[k];
		for(int i = 0;i < n;i++)
			a[i] = sc.next().toCharArray();
		res = Integer.MAX_VALUE;
		perm(0);
		out.println(res);
		out.flush();
	}

	private static void perm(int in) {
		if(in == k) {
			// solve
			int max = Integer.MIN_VALUE;
			int min = Integer.MAX_VALUE;
			for(int i = 0;i < n;i++) {
				int ret = getInt(a[i]);
				max = Math.max(ret,  max);
				min = Math.min(min, ret);
			}
			res = Math.min(res, max - min);
		}
		for(int i = 0;i < k;i++) {
			if(!vis[i]) {
				vis[i] = true;
				perm[in] = i;
				perm(in + 1);
				vis[i] = false;
				perm[in] = 0;
			}
		}
	}

	private static int getInt(char[] s) {
		int ret = 0;
		for(int i = 0;i < s.length;i++) {
			ret *= 10;

			ret += (s[perm[i]]-'0');
		}
		return ret;
	}

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

	private static class Scanner {
		public BufferedReader reader;
		public StringTokenizer st;

		public Scanner(InputStream stream) {
			reader = new BufferedReader(new InputStreamReader(stream));
			st = null;
		}

		public String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					String line = reader.readLine();
					if (line == null)
						return null;
					st = new StringTokenizer(line);
				} catch (Exception e) {
					throw (new RuntimeException());
				}
			}
			return st.nextToken();
		}

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

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

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

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

public class Permutation implements Runnable {
	char[][] a;
	int n, k;
	boolean[] mark;
	int res = Integer.MAX_VALUE / 2;
	int[] b;

	private void solve() throws IOException {
		// long time = System.currentTimeMillis();
		n = nextInt();
		k = nextInt();
		a = new char[n][];
		b = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = nextToken().toCharArray();
		mark = new boolean[k];
		List<Integer> list = new ArrayList<Integer>();
		go(0, list);
		// writer.println("Running time: " + (System.currentTimeMillis() -
		// time));
		writer.println(res);
	}

	private void go(int num, List<Integer> list) {
		// TODO Auto-generated method stub
		if (num >= k) {
			for (int i = 0; i < n; i++) {
				String s = "";
				for (int x : list) {
					s += a[i][x];
				}
				b[i] = Integer.valueOf(s);
			}
			Arrays.sort(b);
			res = Math.min(b[n - 1] - b[0], res);
			return;
		}
		for (int i = 0; i < k; i++) {
			if (!mark[i]) {
				List<Integer> nList = new ArrayList<Integer>();
				for (int x : list)
					nList.add(x);
				nList.add(i);
				mark[i] = true;
				go(num + 1, nList);
				mark[i] = false;
			}
		}
	}

	public static void main(String[] args) {
		new Permutation().run();
	}

	BufferedReader reader;
	StringTokenizer tokenizer;
	PrintWriter writer;

	public void run() {
		try {
			reader = new BufferedReader(new InputStreamReader(System.in));
			tokenizer = null;
			writer = new PrintWriter(System.out);
			solve();
			reader.close();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}

	String nextToken() throws IOException {
		while (tokenizer == null || !tokenizer.hasMoreTokens()) {
			tokenizer = new StringTokenizer(reader.readLine());
		}
		return tokenizer.nextToken();
	}
}

import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author aircube
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }
}

class TaskB {
    int ans = Integer.MAX_VALUE / 2;
    public void solve(int testNumber, Scanner in, PrintWriter out) {
        int n = in.nextInt();
        int k = in.nextInt();
        int[][] a = new int[n][k];
        String[] s = new String[n];
        for (int i = 0; i < n; ++i) {
            s[i] = in.next();
            for (int j = 0; j < a[0].length; ++j)
                a[i][j] = s[i].charAt(j) - '0';
        }
        int perm[] = new int[k];
        dfs(0, new boolean[k], perm, a);
        out.print(ans   );
    }

    private void dfs(int pos, boolean[] used, int[] perm, int[][] a) {
        if (pos == a[0].length) {
            int[][] b = new int[a.length][a[0].length];
            for (int i = 0; i < a.length; ++i)
                for (int j = 0; j < a[0].length; ++j) {
                    b[i][j] = a[i][perm[j]];
                }
            int mn = Integer.MAX_VALUE / 2;
            int mx = -Integer.MAX_VALUE / 2;
            for (int i = 0; i < a.length; ++i) {
                int num = 0;
                for (int j =0 ; j < a[0].length; ++j)
                    num = num * 10 + b[i][j];
                mn = Math.min(mn, num);
                mx = Math.max(mx, num);
            }
            ans = Math.min(ans, mx-mn);
        }  else {
            for (int i = 0; i < a[0].length; ++i)
                if (!used[i]) {
                    perm[pos] = i;
                    used[i] = true;
                    dfs(pos + 1, used, perm, a);
                    used[i] = false;
                }
        }
    }
}

import java.util.Scanner;

public class B {

    int n, k, min;
    char[][] a;
    boolean[] u;
    int[] order;

    void dfs(int K){
        if(K==k){
            char[][] t = new char[n][k];
            for(int i=0;i<n;i++)for(int j=0;j<k;j++)t[i][j] = a[i][order[j]];
            int max = 0;
            int m = 1<<29;
            for(int i=0;i<n;i++){
                int x = Integer.parseInt(new String(t[i]));
                max = Math.max(max, x);
                m = Math.min(m, x);
            }
            min = Math.min(min, max-m);
            return;
        }
        for(int i=0;i<k;i++){
            if(u[i])continue;
            u[i]=true;
            order[K]=i;
            dfs(K+1);
            u[i]=false;
        }
    }

    void run(){
        Scanner sc = new Scanner(System.in);
        min = 1<<29;
        n = sc.nextInt(); k = sc.nextInt();
        a = new char[n][k];
        for(int i=0;i<n;i++)a[i]=sc.next().toCharArray();
        u = new boolean[k];
        order = new int[k];
        dfs(0);
        System.out.println(min);
    }

    public static void main(String[] args) {
        new B().run();
    }
}

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    static int p[],  n,  m;

    static boolean nextPermutation() {
        int a = p.length - 2;
        while (a >= 0 && p[a] >= p[a + 1]) {
            a--;
        }
        if (a == -1) {
            return false;
        }
        int b = p.length - 1;
        while (p[b] <= p[a]) {
            b--;
        }
        int t = p[a];
        p[a] = p[b];
        p[b] = (char) t;
        for (int i = a + 1,  j = p.length - 1; i < j; i++, j--) {
            t = p[i];
            p[i] = p[j];
            p[j] = t;
        }
        return true;
    }
    static String uno;

    public static void main(String[] args) {
        Scanner l = new Scanner(System.in);
        n = l.nextInt();
        m = l.nextInt();
        p = new int[m];
        String arr[] = new String[n];
        int max = Integer.MAX_VALUE, aux;
        args = new String[n];
        for (int i = 0; i < m; i++) {
            p[i] = i;
        }
        for (int i = 0; i < n; i++) {
            args[i] = l.next();
        }
        for (int i = 0; i < n; i++) {
            uno = "";
            for (int j = 0; j < m; j++) {
                uno += args[i].charAt(p[j]);
            }
            arr[i] = uno;
        }
        Arrays.sort(arr);
        aux = Integer.parseInt(arr[n - 1]) - Integer.parseInt(arr[0]);
        max = Math.min(aux, max);

        if (n == 1) {
            System.out.println("0");
        } else {
            while (true) {
                if (nextPermutation()) {
                    for (int i = 0; i < n; i++) {
                        uno = "";
                        for (int j = 0; j < m; j++) {
                            uno += args[i].charAt(p[j]);
                        }
                        arr[i] = uno;
                    }
                    Arrays.sort(arr);
                    aux = Integer.parseInt(arr[n - 1]) - Integer.parseInt(arr[0]);
                    max = Math.min(aux, max);
                } else {
                    break;
                }
            }
            System.out.println(max);
        }
    }
}

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

public class Main{

    int n,k,ans, yk = 0;
    int a[];
    char g[][];
    boolean used[];
    public void run(){
	Scanner in = new Scanner(System.in);
	n = in.nextInt();
	k = in.nextInt();
	g = new char[n][k];
	for(int i=0;i<n;i++){
	    String s = in.next();
	    for(int j=0;j<k;j++){
		g[i][j] = s.charAt(j);
	    }
	}
	a = new int[k];
	used = new boolean[k];
	ans = Integer.MAX_VALUE;
	for(int i=0;i<k;i++){
	    used[i]  = true;
	    a[yk++] = i;
	    generate();
	    yk--;
	    used[i] = false;
	}
	System.out.println(ans);
    }

    private void generate(){
	if (yk == k){
	    //System.out.println(Arrays.toString(a));
	    int lmin = getDiff();
	    if (lmin < ans) ans = lmin;
	}else{
	    for(int i=0;i<k;i++){
		if (!used[i]){
		    used[i] = true;
		    a[yk++] = i;
		    generate();
		    yk--;
		    used[i] = false;
		}
	    }
	}
    }
    private int getDiff(){
	char t[][] = new char[n][k];
	for(int i=0;i<n;i++){
	    for(int j=0;j<k;j++){
		t[i][j] = g[i][a[j]];
	    }
	}
	/*for(int i=0;i<n;i++){
	    for(int j=0;j<k;j++){
		System.out.print(t[i][j] + " ");
	    }
	    System.out.println();
	}*/
	int nums[] = new int[n];
	for(int i=0;i<n;i++){
	    nums[i] = Integer.parseInt(new String(t[i]));
	}
	int min = nums[0];
	int max = nums[0];
	for(int i=0;i<n;i++){
	    if (min > nums[i]) min = nums[i];
	    if (max < nums[i]) max = nums[i];
	}
	return max - min;
    }
    public static void main(String args[]){
	new Main().run();
    }
}

import java.util.Arrays;
import java.util.Scanner;

public class B124 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        char[][]a = new char[n+1][k+1];
        for (int i = 1; i <= n; i++) {
            String s = sc.next();
            for (int j = 0; j < k; j++) {
                a[i][j+1] = s.charAt(j);
            }
        }
        int[]perm = new int[k+1];
        for (int i = 1; i <= k; i++) {
            perm[i] = i;
        }
        int ans = (int) 1e9;
        int[]temp = new int[n+1];
        while (true) {
            for (int i = 1; i <= n; i++) {
                temp[i] = 0;
                for (int j = 1; j <= k; j++) {
                    temp[i] = temp[i]*10+(int)a[i][perm[j]]-48;
                }
            }
            int min = (int) 1e9,max = 0;
            for (int i = 1; i <= n; i++) {
                min = Math.min(min, temp[i]);
                max = Math.max(max, temp[i]);
            }
            ans = Math.min(ans, max-min);
            for (int i = 2; i <= n; i++) {
                min = Math.min(min, temp[i]-temp[i-1]);
            }
            int p1 = k;
            while (p1 > 1 && perm[p1] < perm[p1-1])
                p1--;
            if (p1==1)
                break;
            int p2 = k;
            while (perm[p2] < perm[p1-1])
                p2--;
            int t = perm[p1-1];
            perm[p1-1] = perm[p2];
            perm[p2] = t;
            for (int i = 1; i <= ((k-p1) >> 1)+1; i++) {
                t = perm[p1+i-1];
                perm[p1+i-1] = perm[k+1-i];
                perm[k+1-i] = t;
            }
        }
        System.out.println(ans);
    }
}

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

public class CodefB {

    public static void main (String [] args) throws Exception{

        Scanner in = new Scanner (System.in);
        PrintWriter out = new PrintWriter(System.out);
        int n = in.nextInt();
        int q = in.nextInt();
        int [] a = new int [60000];
        int [] b = new int [60000];
        int i;
        int []g = new int[10];
        g[1]=1;
        for (i=2; i<=9;i++)
            g[i]=g[i-1]*10;
        int inf;
        int sup;
        int ch;
        int res=1000000000;
        int f=1;
        for (i=2; i<=q;i++)
            f*=i;
        for (i = 1; i<=q; i++){
            a[i] = i;
        }
        String s;
        char [][] c= new char [100][100];
        for (i=1; i<=n;i++){
            s= in.next();
            c[i]= s.toCharArray();
        }
        a[0] = q+1;
        sup=-1;
        inf=1000000000;
        for (i=1; i<=n; i++){
            ch=0;
            for (int j=1; j<=q;j++){
                int u=Character.digit(c[i][a[j]-1],10);
                ch+=((u))*g[j];
            }
            if (ch>sup)
              sup=ch;
            if (ch<inf)
              inf=ch;
        }
        if (res>(sup-inf))
            res=(sup-inf);
        for (int z=2; z<=f;z++){
        int k=0;
        for (i = q; i>=1; i--){
            if (a[i]>a[i-1]) {
                k=i-1;
                break;
            }
        }
        if (k>0){
            int t = k+1;
            for (i=t+1; i<=q; i++){
                if((a[k]<a[i])&&(a[t]>a[i]))
                    t = i;
            }
            int x;
            x=a[k];
            a[k]=a[t];
            a[t]=x;
            //for (i=1; i<=k; i++)
                //out.print(a[i]+" ");
            int y=k+1;
            for (i=q; i>k; i--){
                //out.print(a[i]+" ");
                b[y++]=a[i];
                }
            for (i=q; i>k; i--)
                a[i]=b[i];
            sup=-1;
            inf=1000000000;
            for (i=1; i<=n; i++){
                ch=0;
                for (int j=1; j<=q;j++){
                    int u=Character.digit(c[i][a[j]-1],10);
                    ch+=((u))*g[j];
                }
                if (ch>sup)
                  sup=ch;
                if (ch<inf)
                  inf=ch;
            }
            if (res>(sup-inf))
                res=(sup-inf);
            }

        }
        out.print(res);
        out.close();
        }

}

import java.util.*;
import java.io.*;
public class a {
public static void main(String[] args) throws IOException
{
    input.init(System.in);
    PrintWriter out = new PrintWriter(System.out);
    int n = input.nextInt(), k = input.nextInt();
    data = new ArrayList<String>();
    for(int i =0; i<n; i++) data.add(input.next());
    out.println(go(new int[k], new boolean[k], 0));
    out.close();
}
static ArrayList<String> data;
static int go(int[] numbers, boolean[] used, int at)
{
    int n = numbers.length;
    if(at == n)
    {
        //process
        //System.out.println(Arrays.toString(numbers));
        int[] nums = new int[data.size()];
        int cur = 0;
        for(int i = 0; i<data.size(); i++)
        {
            String s = "";
            for(int j= 0; j<n;j++) s += data.get(i).charAt(numbers[j]);
            nums[cur++] = Integer.parseInt(s);
        }
        Arrays.sort(nums);
        return nums[nums.length-1] - nums[0];
    }
    int res = 987654321;
    for(int i = 0; i<n; i++)
    {
        if(!used[i])
        {
            used[i] = true;
            numbers[at] = i;
            res = Math.min(res, go(numbers, used, at+1));
            used[i] = false;
        }
    }
    return res;
}
static int gcd(int a, int b)
{
    if(b==0) return a;
    return gcd(b, a%b);
}
static class Soldier implements Comparable<Soldier> {
    int b, i;
    public Soldier(int bb, int ii)
    {
        b = bb; i = ii;
    }
    @Override
    public int compareTo(Soldier that) {
        // TODO Auto-generated method stub
        return that.b - this.b;
    }
}
public static class input {
    static BufferedReader reader;
    static StringTokenizer tokenizer;

    /** call this method to initialize reader for InputStream */
    static void init(InputStream input) {
        reader = new BufferedReader(
                     new InputStreamReader(input) );
        tokenizer = new StringTokenizer("");
    }

    /** get next word */
    static String next() throws IOException {
        while ( ! tokenizer.hasMoreTokens() ) {
            //TODO add check for eof if necessary
            tokenizer = new StringTokenizer(
                   reader.readLine() );
        }
        return tokenizer.nextToken();
    }

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

    static double nextDouble() throws IOException {
        return Double.parseDouble( next() );
    }
    static long nextLong() throws IOException {
        return Long.parseLong( next() );
    }
}
static class IT
{
    int[] left,right, val, a, b;
    IT(int n)
    {
        left = new int[4*n];
        right = new int[4*n];
        val = new int[4*n];
        a = new int[4*n];
        b = new int[4*n];
        init(0,0, n);
    }
    int init(int at, int l, int r)
    {
        a[at] = l;
        b[at] = r;
        if(l==r)
            left[at] = right [at] = -1;
        else
        {
            int mid = (l+r)/2;
            left[at] = init(2*at+1,l,mid);
            right[at] = init(2*at+2,mid+1,r);
        }
        return at++;
    }
    //return the sum over [x,y]
    int get(int x, int y)
    {
        return go(x,y, 0);
    }
    int go(int x,int y, int at)
    {
        if(at==-1) return 0;
        if(x <= a[at] && y>= b[at]) return val[at];
        if(y<a[at] || x>b[at]) return 0;
        return go(x, y, left[at]) + go(x, y, right[at]);
    }
    //add v to elements x through y
    void add(int x, int y, int v)
    {
        go3(x, y, v, 0);
    }
    void go3(int x, int y, int v, int at)
    {
        if(at==-1) return;
        if(y < a[at] || x > b[at]) return;
        val[at] += (Math.min(b[at], y) - Math.max(a[at], x) + 1)*v;
        go3(x, y, v, left[at]);
        go3(x, y, v, right[at]);
    }
}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;

public class B {

    private void solve() throws IOException {
        int n = nextInt();
        int k = nextInt();
        int[] a = new int[k];
        String[] nums = new String[n];
        for (int i = 0; i < nums.length; i++) {
            nums[i] = nextToken();
        }
        res = Integer.MAX_VALUE;
        perm(0 , a, new int[k], new boolean[k] , nums);
        System.out.println(res);
    }

    private int arrange(String nums, int[] d) {
        String res = "";
        String s = nums;
        for (int i = 0; i < d.length; i++)
            res += s.charAt(d[i]);
        return Integer.parseInt(res);
    }

    int res;
    private void perm(int i, int[] a, int[] perms , boolean[] visited , String[] nums) {
        if (i == a.length) {
            int max = Integer.MIN_VALUE;
            int min = Integer.MAX_VALUE;

            for (int i1 = 0; i1 < nums.length; i1++) {
                int R = arrange(nums[i1] , perms);
                max = Math.max(max, R);
                min = Math.min(min, R);
            }
            res = Math.min(max - min, res);
        }
        else {
            for (int j = 0; j < a.length; j++) {
                if (visited[j]) continue;
                perms[i] = j;
                visited[j] = true;
                perm(i + 1, a , perms , visited , nums);
                visited[j] = false;
            }
        }
    }

    public static void main(String[] args) {
        new B().run();
    }

    BufferedReader reader;
    StringTokenizer tokenizer;
    PrintWriter writer;

    public void run() {
        try {
            reader = new BufferedReader(new InputStreamReader(System.in));
            tokenizer = null;
            writer = new PrintWriter(System.out);
            solve();
            reader.close();
            writer.close();
        }
        catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }

    double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }

    BigInteger nextBigInteger() throws IOException {
        return new BigInteger(nextToken());
    }

    String nextToken() throws IOException {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            tokenizer = new StringTokenizer(reader.readLine());
        }
        return tokenizer.nextToken();
    }
}

import java.util.ArrayList;
import java.util.Scanner;

public class B124 {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt(), k = in.nextInt();
		char[][] strs = new char[n][k];
		for (int x = 0; x < n; x++) {
			strs[x] = in.next().toCharArray();
		}
		int[] indices = new int[k];
		int mind = Integer.MAX_VALUE;
		while(indices[0] < k) {
			int[] map = new int[k];
			ArrayList<Integer> pq = new ArrayList<Integer>();
			for(int x = 0;x<k;x++) {
				pq.add(x);
			}
			for(int x = 0;x<k;x++) {
				map[x] = pq.remove(indices[x]);
			}
			int max = 0;
			int min = Integer.MAX_VALUE;
			for(int x = 0;x<n;x++) {
				char[] c = new char[k];
				for(int y=0;y<k;y++) {
					c[y] = strs[x][map[y]];
				}
				int i = Integer.parseInt(new String(c));
				if(i>max) max = i;
				if(i<min) min = i;
			}
			int diff = max-min;
			if(diff<mind) mind = diff;
			int x = k-1;
			indices[x]++;
			while(x>0&&indices[x]>=(k-x)) {
				indices[x] = 0;
				x--;
				indices[x]++;
			}
		}
		System.out.println(mind);
	}
}

import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;

public class Main implements Runnable {

    static PrintWriter out;
    static StringTokenizer st;
    static BufferedReader br;

    public static void main(String[] args) {
        out = new PrintWriter(System.out);
        br = new BufferedReader(new InputStreamReader(System.in));
        new Main().run();
    }

    public void run() {
        solve();
        out.close();
    }

    String ns() {
        try {
            while (st == null || !st.hasMoreTokens()) {
                st = new StringTokenizer(br.readLine());
            }
            return st.nextToken();
        } catch (Exception ex) {
            return null;
        }
    }

    int ni() {
        return Integer.valueOf(ns());
    }

    long nl() {
        return Long.valueOf(ns());
    }

    double nd() {
        return Double.valueOf(ns());
    }

    String nline() {
        try {
            st = null;
            return br.readLine();
        } catch (Exception ex) {
            return null;
        }
    }

    char[][] mas;
    int n;
    int k;
    int ans = Integer.MAX_VALUE;

    void swap(int a, int b) {
        for (int i = 0; i < n; i++) {
            char t = mas[i][a];
            mas[i][a] = mas[i][b];
            mas[i][b] = t;
        }
    }

    int calc() {
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < n; i++) {
            int a = Integer.valueOf(String.valueOf(mas[i]));
            if (a < min) {
                min = a;
            }
            if (a > max) {
                max = a;
            }
        }

        return max - min;
    }

    void generate(int p) {
        if (p == 0) {
            int t = calc();
            if (t < ans) {
                ans = t;
            }
            return;
        }
        for (int i = 0; i < p; i++) {
            swap(i, p - 1);
            generate(p - 1);
            swap(i, p - 1);
        }
    }

    void solve() {
        n = ni();
        k = ni();
        mas = new char[n][k];
        for (int i = 0; i < n; i++) {
            mas[i] = ns().toCharArray();
        }
        generate(k);
        out.print(ans);
    }

}

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TaskB {

	public static boolean nextPermutation(int[] tmp) {
		int i, j, n = tmp.length;
		if (tmp.length < 2) {
			return false;
		} else {
			i = n - 2;
			while (i >= 0 && tmp[i] >= tmp[i + 1]) --i;
			if (i >= 0) {
				j = i + 1;
				while (j < n-1  && tmp[j + 1] > tmp[i]) ++j;
				int a = tmp[i];
					tmp[i] = tmp[j];
					tmp[j] = a;
				for (int k = i + 1; k < i + 1 + (n-i-1)/2; ++k) {
					a = tmp[k];
					tmp[k] = tmp[n - k + i];
					tmp[n - k + i] = a;
				}
				return true;
			} else {
				return false;
			}
		}
	}
	public static void print(int[] a) {
		for (int i = 0; i < a.length; ++i) {
			System.out.print(a[i]);
		}
		System.out.println();
	}
	public static String processString(String tmp, int[] a) {
		String result = "";
		for (int i = 0; i < a.length; ++i) {
			result +=tmp.charAt(a[i]);
		}
		return result;
	}
	public static void main(String[] args) throws IOException {
		PrintWriter jout = new PrintWriter(System.out);
		Scanner jin = new Scanner(new InputStreamReader(System.in));
		int n = jin.nextInt();
		int k = jin.nextInt();
		String[] numbers = new String[n];
		for (int i = 0; i < n; ++i) {
			numbers[i] = jin.next();
		}
		int[] permutation = new int[k];
		for (int i = 0; i < k; ++i) {
			permutation[i] = i;
		}
		List<int[]> permutations = new ArrayList<int[]>();
		do {
			//print(permutation);
			permutations.add(permutation.clone());
		}while(nextPermutation(permutation));

		int min = Integer.MAX_VALUE;
		for (int i = 0; i < permutations.size(); ++i) {
			int [] num = new int[n];
			for (int j = 0; j < n; ++j) {
				int [] a = permutations.get(i);
				num[j] = Integer.parseInt(processString(numbers[j], a));
			}
			Arrays.sort(num);
			if (num[num.length-1] - num[0] < min) {
				min = num[num.length-1] - num[0];
			}
		}
		System.out.println(min);
	}
}

import java.util.Scanner;

public class two {
    static int[] perm = new int[40321];
    static int index = 0;
    static int min = Integer.MAX_VALUE;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        int k = sc.nextInt();
        String[] numbers = new String[n];
        for (int i = 0; i < n; i++)
            numbers[i] = sc.next();
        int[] p = new int[k + 1];
        int[] a = new int[k + 1];
        for (int i = 1; i <= k; i++)
            a[i] = i;
        boolean[] v = new boolean[k + 1];
        genererate(1, a, p, numbers, v);
        System.out.println(min);
    }

    private static void genererate(int i, int[] a, int[] p, String[] numbers,
            boolean[] v) {
        if (i == a.length) {
            find(p, numbers);
        } else {
            for (int j = 1; j < a.length; j++)
                if (!v[j]) {
                    v[j] = true;
                    p[i] = a[j];
                    genererate(i + 1, a, p, numbers, v);
                    v[j] = false;
                }

        }

    }

    private static void find(int[] p, String[] numbers) {
        int minNum = Integer.MAX_VALUE;
        int maxNum = Integer.MIN_VALUE;
        for (int i = 0; i < numbers.length; i++) {
            int n = reArrange(p, numbers[i]);
            minNum = Math.min(minNum, n);
            maxNum = Math.max(maxNum, n);
        }
        min = Math.min(min, maxNum - minNum);

    }

    private static int reArrange(int[] p, String i) {
        String s = i + "";
        int[] temp = new int[p.length];
        for (int j = 1; j < p.length; j++)
            temp[j] = Integer.parseInt(s.charAt(p[j]-1) + "");
        s = "";
        for (int j = 1; j < temp.length; j++)
            s += temp[j];
        return Integer.parseInt(s);
    }
}

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

public class b {
    BufferedReader in;
    StringTokenizer st;
    PrintWriter out;

    String _token() throws IOException {
        while (in.ready() && !st.hasMoreTokens()) {
            st = new StringTokenizer(in.readLine());
        }
        return st.nextToken();
    }

    int _int() throws NumberFormatException, IOException {
        return Integer.parseInt(_token());
    }

    long _long() throws NumberFormatException, IOException {
        return Long.parseLong(_token());
    }

    double _double() throws NumberFormatException, IOException {
        return Double.parseDouble(_token());
    }

    void deb(String s) {
        System.err.println(s);
    }

    void deb(Object a) {
        System.err.println(a.toString());
    }

    void init(boolean FILE, String name) throws NumberFormatException,
            IOException {
        Locale.setDefault(Locale.US);
        if (FILE) {
            in = new BufferedReader(new FileReader(name + ".in"));
            out = new PrintWriter(name + ".out");
        } else {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        }
        st = new StringTokenizer("");
    }

    int p[], n, k;

    void swap(int a, int b) {
        int t = p[a];
        p[a] = p[b];
        p[b] = t;
    }

    boolean next_perm()
    {
        int i = k-1;

        while(i > 0 && p[i] < p[i-1])
            i--;

        if (i == 0 && p[i] == k-1)
            return false;
        i--;

        int j = i+1;
        while (j < k && p[j] > p[i])
            j++;
        j--;

        swap(i,j);
        Arrays.sort(p, i+1, k);
        return true;
    }

    void mainProgram() throws NumberFormatException, IOException {
        //      test("b.in");
        init(false, "b");

        n = _int();
        k = _int();
        p = new int[k];
        for(int i=0;i<k;i++)
            p[i] = i;

        char[][]s = new char[n][k];
        for(int i=0;i<n;i++)
            s[i] = _token().toCharArray();

        BigInteger best = val(999999999999999l);

        do
        {
            BigInteger max = val(0);
            BigInteger min = val(999999999999999l);

            for(int i=0;i<n;i++) {
                BigInteger now = val(0);
                for(int j=0;j<k;j++) {
                    now = add(mult(now,val(10)),val(s[i][p[j]]-'0'));
                }
                max = max.max(now);
                min = min.min(now);
            }
            best = best.min(sub(max,min));
        } while (next_perm());
        out.println(best);
        out.close();
    }

    int rand(int x) {
        return (int) (Math.random() * x);
    }

    void test(String name) throws IOException {
        out = new PrintWriter(new File(name));

        out.close();
    }

    public static void main(String[] args) throws NumberFormatException,
            IOException {
        long T = System.currentTimeMillis();
        new b().mainProgram();
        System.err.println("Time of working: "
                + (System.currentTimeMillis() - T) + " ms");
    }

    BigInteger add(BigInteger A, BigInteger B) {
        return A.add(B);
    }

    BigInteger mult(BigInteger A, BigInteger B) {
        return A.multiply(B);
    }

    BigInteger sub(BigInteger A, BigInteger B) {
        return A.subtract(B);
    }

    BigInteger div(BigInteger A, BigInteger B) {
        return A.divide(B);
    }

    BigInteger mi(BigInteger A) {
        return (BigInteger.ZERO).subtract(A);
    }

    BigInteger sq(BigInteger A) {
        return A.multiply(A);
    }

    BigInteger val(long a) {
        return BigInteger.valueOf(a);
    }

    int cmp(BigInteger a, BigInteger b) {
        return a.compareTo(b);
    }

}

import java.util.*;
public class B124 {

	int n,k;

	boolean flag[] = new boolean[20];
	String num[] = new String[20];
	int min = 999999999 ;

	public void find(int x, String now[]){

		if (x==k){
			int small = 99999999;
			int big = 0;

			for(int i = 0 ; i<n; i++){
				int tt = Integer.parseInt(now[i]);
				small = Math.min(small, tt);
				big = Math.max(tt, big);
			}
			min = Math.min(big-small, min);
			return;
		}

		for(int i = 0 ; i < k ; i ++){
			if (flag[i]){
				flag[i]=false;
				String temp[] = new String[20];
				for(int j = 0 ; j < n ; j++){
					temp[j]=now[j]+num[j].charAt(i);
				}
				find(x+1,temp);
				flag[i]=true;
			}

		}

	}

	public B124(Scanner input){
		n = input.nextInt();
		k = input.nextInt();

		for(int i = 0 ; i < n ; i ++){

			num[i] =input.next();
		}
		Arrays.fill(flag, true);
		String start[] = new String[20];
		Arrays.fill(start,"");

		find(0,start);
		System.out.println(min);

	}

	public static void main(String args[]){

		new B124(new Scanner(System.in));
	}

}

import java.util.Scanner;

public class B {

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int k = scan.nextInt();
		g= new char[n][k];
		a= new char[n][k];
		min = Integer.MAX_VALUE;
		v = new boolean[k];
		for(int i = 0;i<n;i++)
		{
			String s = scan.next();
			for(int j=0;j<k;j++)
				g[i][j] = s.charAt(j);
		}
		dfs(0);
		System.out.println(min);
	}
	static int min;
	static char[][] g;
	static char[][] a;
	static boolean[] v;
	static void dfs(int pos)
	{
		if(pos == g[0].length)
		{
			int max = -1;
			int mn = Integer.MAX_VALUE;
			for(int i=0;i<g.length;i++)
			{
				int s = Integer.parseInt(new String(a[i]));
				if(s > max) max = s;
				if(s < mn) mn = s;
			}
			min = Math.min(min,max-mn);
		}else{
			for(int i=0;i<g[0].length;i++)if(!v[i])
			{
				v[i] = true;
				for(int j = 0;j < g.length;j++)
					a[j][pos] = g[j][i];
				dfs(pos+1);
				v[i] = false;
			}
		}
	}

}

import java.util.*;
public class Main{
	Scanner sc = new Scanner(System.in);
	int n,k;
	int[][] d;
	int r;
	Main(){
		n= sc.nextInt();k=sc.nextInt();
		d=new int[n][k];
		for(int i=0;i<n;i++){
			String s=sc.next();
			for(int j=0;j<k;j++)d[i][j]=s.charAt(j)-'0';
		}
		r=Integer.MAX_VALUE;
		solve(0,new int[k],new boolean[k]);
		System.out.println(r);
	}
	private void solve(int i, int[] p,boolean[] used) {
		if(i==k){
			int[] nums=new int[n];
			for(int a=0;a<n;a++){
				for(int b=0;b<k;b++){
					nums[a]=nums[a]*10+d[a][p[b]];
				}
			}
			int max=0,min=Integer.MAX_VALUE;
			for(int a=0;a<n;a++){
				if(max<nums[a])max=nums[a];
				if(nums[a]<min)min=nums[a];
			}
			if(max-min<r)r=max-min;
			return;
		}
		for(int j=0;j<k;j++){
			if(used[j])continue;
			used[j]=true;
			p[i]=j;
			solve(i+1,p,used);
			used[j]=false;
		}
	}
	public static void main(String[] args){new Main();}
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

/**
 *
 */

/**
 * @author antonio081014
 * @since Nov 3, 2011, 7:45:54 AM
 */
public class B {

	public static List<List<Integer>> list;
	public static List<Integer> store;
	public static int k;
	public static int n;

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String strLine = br.readLine();
		n = Integer.parseInt(strLine.split(" ")[0]);
		k = Integer.parseInt(strLine.split(" ")[1]);
		list = new ArrayList<List<Integer>>();
		store = new ArrayList<Integer>();
		for (int i = 0; i < n; i++) {
			String tmp = br.readLine();
			list.add(new ArrayList<Integer>());
			permuteString("", tmp, i);
		}
		// for (int i = 0; i < list.get(0).size(); i++) {
		// System.out.println(list.get(0).get(i) + " --- "
		// + list.get(1).get(i));
		// }
		// System.out.println();

		int mmin = Integer.MAX_VALUE;
		for (int i = 0; i < list.get(0).size(); i++) {
			List<Integer> set = new ArrayList<Integer>();
			for (int j = 0; j < n; j++) {
				set.add(list.get(j).get(i));
			}
			Collections.sort(set);
			mmin = Math.min(mmin, set.get(n - 1) - set.get(0));
		}
		System.out.println(mmin);
	}

	public static void permuteString(String beginningString,
			String endingString, int index) {
		if (endingString.length() <= 1) {
			list.get(index).add(
					Integer.parseInt(beginningString + endingString));
			return;
		}
		for (int i = 0; i < endingString.length(); i++) {
			try {
				String newString = endingString.substring(0, i)
						+ endingString.substring(i + 1);

				permuteString(beginningString + endingString.charAt(i),
						newString, index);
			} catch (StringIndexOutOfBoundsException exception) {
				exception.printStackTrace();
			}
		}
	}
}

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

public class B {

	MyScanner in;
	PrintWriter out;

	public static void main(String[] args) throws Exception {
		new B().run();
	}

	public void run() throws Exception {
		in = new MyScanner();
		out = new PrintWriter(System.out);

		solve();

		out.close();
	}

	boolean[] used;
	int[] p;
	int[][] nums;
	int k;
	int n;
	int ans = Integer.MAX_VALUE;

	void check() {
		int min = Integer.MAX_VALUE;
		int max = -Integer.MAX_VALUE;

		for (int i = 0; i < n; i++) {
			int num = 0;
			for (int j = 0; j < k; j++) {
				num = 10 * num + nums[i][p[j]];
			}
			min = Math.min(num, min);
			max = Math.max(num, max);
		}

		ans = Math.min(ans, max - min);
	}

	void perms(int d) {
		if (d == k) {
			check();
		} else {
			for (int i = 0; i < k; i++) {
				if (!used[i]) {
					used[i] = true;
					p[d] = i;
					perms(d + 1);
					used[i] = false;
				}
			}
		}
	}
	public void solve() throws Exception {
		n = in.nextInt();
		k = in.nextInt();

		nums = new int[n][k];
		used = new boolean[k];
		p = new int[k];

		for (int i = 0; i < n; i++) {
			char[] chnums = in.next().toCharArray();
			for (int j = 0; j < k; j++) {
				nums[i][j] = (chnums[j]) - '0';
			}
		}
		perms(0);

		out.println(ans);
	}

	class MyScanner {
		BufferedReader br;
		StringTokenizer st;

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

		String next() throws Exception {
			while ((st == null) || (!st.hasMoreTokens())) {
				st = new StringTokenizer(br.readLine());
			}
			return st.nextToken();
		}

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

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

		boolean nextBoolean() throws Exception {
			return Boolean.parseBoolean(next());
		}

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

}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author pttrung
 */
public class B {

    static int[] dp;
    static int[] x = {0, 0, 1, -1};
    static int[] y = {1, -1, 0, 0};

    public static void main(String[] args) {
        Scanner in = new Scanner();
        PrintWriter out = new PrintWriter(System.out);
        int n = in.nextInt();
        int k = in.nextInt();
        String[] data = new String[n];
        for (int i = 0; i < n; i++) {
            data[i] = in.next();
        }
        int[] o = new int[k];
        for (int i = 0; i < k; i++) {
            o[i] = i;
        }
        int result = Integer.MAX_VALUE;
        do{
            int []convert = new int[n];
            for(int i = 0; i < n; i++ ){
                int val = 0;
                for(int j = 0; j < o.length; j++){
                    int temp = data[i].charAt(o[j]) - '0';
                    val = val*10 + temp;
                }
                convert[i] = val;
            }
            Arrays.sort(convert);
            result = Math.min(result, convert[n - 1] - convert[0]);
        }while(nextPer(o));
        out.println(result);
        out.close();
    }

    public static boolean nextPer(int[] data) {
        int i = data.length - 1;
        while (i > 0 && data[i] < data[i - 1]) {
            i--;
        }
        if (i == 0) {
            return false;
        }
        int j = data.length - 1;
        while (data[j] < data[i - 1]) {
            j--;
        }
        int temp = data[i - 1];
        data[i - 1] = data[j];
        data[j] = temp;
        Arrays.sort(data, i, data.length);
        return true;
    }

    public double pow(double a, int b) {
        if (b == 0) {
            return 1;
        }
        if (b == 1) {
            return a;
        }
        double val = pow(a, b / 2);
        if (b % 2 == 0) {
            return val * val;
        } else {
            return val * val * a;
        }
    }

    public static long gcd(long a, long b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    public static long lcm(long a, long b) {
        return a * b / gcd(a, b);
    }

    static class Scanner {

        BufferedReader br;
        StringTokenizer st;

        public Scanner() {
            // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public String next() {

            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (Exception e) {
                    throw new RuntimeException();
                }
            }
            return st.nextToken();
        }

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

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

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

        public String nextLine() {
            st = null;
            try {
                return br.readLine();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }

        public boolean endLine() {
            try {
                String next = br.readLine();
                while (next != null && next.trim().isEmpty()) {
                    next = br.readLine();
                }
                if (next == null) {
                    return true;
                }
                st = new StringTokenizer(next);
                return st.hasMoreTokens();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    }
}

import static java.lang.Math.*;
import java.util.*;
import java.io.*;

public class B {

    public void solve() throws Exception {
        n=nextInt(); k=nextInt();
        nums = nextArrS(n);
        p = new int[nums.length];
        int[] x = new int[k];
        for (int i=0; i<k; ++i) x[i]=i;
        gen(0,x);
        println(best);
    }

    String[] nums;
    int n,k, best=Integer.MAX_VALUE, p[];

    void gen(int pos, int[] ord) {
        if (pos==k-1) {
            for (int i=0; i<k; ++i) for (int j=0; j<nums.length; ++j)
                p[j]=(i==0?0:p[j]*10)+nums[j].charAt(ord[i])-48;
            best = min(best,max(p)-min(p));
        } else for (int i=pos; i<k; ++i) {
            int[] p = ord.clone();
            int temp = p[pos]; p[pos] = p[i]; p[i] = temp;
            gen(pos+1,p);
        }
    }

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

    boolean showDebug = true;

    double EPS = 1e-7;
    int INF = Integer.MAX_VALUE;
    long INFL = Long.MAX_VALUE;
    double INFD = Double.MAX_VALUE;

    int absPos(int num) {
        return num<0 ? 0:num;
    }
    long absPos(long num) {
        return num<0 ? 0:num;
    }
    double absPos(double num) {
        return num<0 ? 0:num;
    }

    int min(int... nums) {
        int r = INF;
        for (int i: nums)
            if (i<r) r=i;
        return r;
    }
    int max(int... nums) {
        int r = -INF;
        for (int i: nums)
            if (i>r) r=i;
        return r;
    }
    long minL(long... nums) {
        long r = INFL;
        for (long i: nums)
            if (i<r) r=i;
        return r;
    }
    long maxL(long... nums) {
        long r = -INFL;
        for (long i: nums)
            if (i>r) r=i;
        return r;
    }
    double minD(double... nums) {
        double r = INFD;
        for (double i: nums)
            if (i<r) r=i;
        return r;
    }
    double maxD(double... nums) {
        double r = -INFD;
        for (double i: nums)
            if (i>r) r=i;
        return r;
    }

    long sumArr(int[] arr) {
        long res = 0;
        for (int i: arr)
            res+=i;
        return res;
    }
    long sumArr(long[] arr) {
        long res = 0;
        for (long i: arr)
            res+=i;
        return res;
    }
    double sumArr(double[] arr) {
        double res = 0;
        for (double i: arr)
            res+=i;
        return res;
    }

    long partsFitCnt(long partSize, long wholeSize) {
        return (partSize+wholeSize-1)/partSize;
    }

    boolean odd(long num) {
        return (num&1)==1;
    }

    boolean hasBit(int num, int pos) {
        return (num&(1<<pos))>0;
    }

    long binpow(int a, int n) {
        long r = 1;
        while (n>0) {
            if ((n&1)!=0) r*=a;
            a*=a;
            n>>=1;
        }
        return r;
    }

    boolean isLetter(char c) {
        return (c>='a' && c<='z') || (c>='A' && c<='Z');
    }
    boolean isLowercase(char c) {
        return (c>='a' && c<='z');
    }
    boolean isUppercase(char c) {
        return (c>='A' && c<='Z');
    }
    boolean isDigit(char c) {
        return (c>='0' && c<='9');
    }

    String stringn(String s, int n) {
        if (n<1) return "";
        StringBuilder sb = new StringBuilder(s.length()*n);
        for (int i=0; i<n; ++i) sb.append(s);
        return sb.toString();
    }
    String str(Object o) {
        return o.toString();
    }

    long timer = System.currentTimeMillis();
    void startTimer() {
        timer = System.currentTimeMillis();
    }
    void stopTimer() {
        System.err.println("time: "+(System.currentTimeMillis()-timer)/1000.0);
    }

    class InputReader {
        private byte[] buf;
        private int bufPos = 0, bufLim = -1;
        public InputReader(int size) {
            buf = new byte[size];
        }
        private void fillBuf() throws IOException {
            bufLim = System.in.read(buf);
            bufPos = 0;
        }
        char read() throws IOException {
            if (bufPos>=bufLim) fillBuf();
            return (char)buf[bufPos++];
        }
        boolean hasInput() throws IOException {
            if (bufPos>=bufLim) fillBuf();
            return bufPos<bufLim;
        }
    }

    InputReader inputReader = new InputReader(1<<16);
    static BufferedWriter outputWriter = new BufferedWriter(new OutputStreamWriter(System.out), 1<<16);

    char nextChar() throws IOException {
        return inputReader.read();
    }
    char nextNonWhitespaceChar() throws IOException {
        char c = inputReader.read();
        while (c<=' ') c=inputReader.read();
        return c;
    }
    String nextWord() throws IOException {
        StringBuilder sb = new StringBuilder();
        char c = inputReader.read();
        while (c<=' ') c=inputReader.read();
        while (c>' ') {
            sb.append(c);
            c = inputReader.read();
        }
        return new String(sb);
    }
    String nextLine() throws IOException {
        StringBuilder sb = new StringBuilder();
        char c = inputReader.read();
        while (c<=' ') c=inputReader.read();
        while (c!='\n' && c!='\r') {
            sb.append(c);
            c = inputReader.read();
        }
        return new String(sb);
    }
    int nextInt() throws IOException {
        int r = 0;
        char c = nextNonWhitespaceChar();
        boolean neg = false;
        if (c=='-') neg=true;
        else r=c-48;
        c = nextChar();
        while (c>='0' && c<='9') {
            r*=10;
            r+=c-48;
            c=nextChar();
        }
        return neg ? -r:r;
    }
    long nextLong() throws IOException {
        long r = 0;
        char c = nextNonWhitespaceChar();
        boolean neg = false;
        if (c=='-') neg=true;
        else r = c-48;
        c = nextChar();
        while (c>='0' && c<='9') {
            r*=10L;
            r+=c-48L;
            c=nextChar();
        }
        return neg ? -r:r;
    }
    double nextDouble() throws NumberFormatException, IOException {
        return Double.parseDouble(nextWord());
    }
    int[] nextArr(int size) throws NumberFormatException, IOException {
        int[] arr = new int[size];
        for (int i=0; i<size; ++i)
            arr[i] = nextInt();
        return arr;
    }
    long[] nextArrL(int size) throws NumberFormatException, IOException {
        long[] arr = new long[size];
        for (int i=0; i<size; ++i)
            arr[i] = nextLong();
        return arr;
    }
    double[] nextArrD(int size) throws NumberFormatException, IOException {
        double[] arr = new double[size];
        for (int i=0; i<size; ++i)
            arr[i] = nextDouble();
        return arr;
    }
    String[] nextArrS(int size) throws NumberFormatException, IOException {
        String[] arr = new String[size];
        for (int i=0; i<size; ++i)
            arr[i] = nextWord();
        return arr;
    }
    char[] nextArrCh(int size) throws IOException {
        char[] arr = new char[size];
        for (int i=0; i<size; ++i)
            arr[i] = nextNonWhitespaceChar();
        return arr;
    }
    char[][] nextArrCh(int rows, int columns) throws IOException {
        char[][] arr = new char[rows][columns];
        for (int i=0; i<rows; ++i)
            for (int j=0; j<columns; ++j)
                arr[i][j] = nextNonWhitespaceChar();
        return arr;
    }
    char[][] nextArrChBorders(int rows, int columns, char border) throws IOException {
        char[][] arr = new char[rows+2][columns+2];
        for (int i=1; i<=rows; ++i)
            for (int j=1; j<=columns; ++j)
                arr[i][j] = nextNonWhitespaceChar();
        for (int i=0; i<columns+2; ++i) {
            arr[0][i] = border;
            arr[rows+1][i] = border;
        }
        for (int i=0; i<rows+2; ++i) {
            arr[i][0] = border;
            arr[i][columns+1] = border;
        }
        return arr;
    }

    void printf(String format, Object... args) throws IOException {
        outputWriter.write(String.format(format, args));
    }
    void print(Object o) throws IOException {
        outputWriter.write(o.toString());
    }
    void println(Object o) throws IOException {
        outputWriter.write(o.toString());
        outputWriter.newLine();
    }
    void print(Object... o) throws IOException {
        for (int i=0; i<o.length; ++i) {
            if (i!=0) outputWriter.write(' ');
            outputWriter.write(o[i].toString());
        }
    }
    void println(Object... o) throws IOException {
        print(o);
        outputWriter.newLine();
    }
    void printn(Object o, int n) throws IOException {
        String s = o.toString();
        for (int i=0; i<n; ++i) {
            outputWriter.write(s);
            if (i!=n-1) outputWriter.write(' ');
        }
    }
    void printnln(Object o, int n) throws IOException {
        printn(o, n);
        outputWriter.newLine();
    }
    void printArr(int[] arr) throws IOException {
        for (int i=0; i<arr.length; ++i) {
            if (i!=0) outputWriter.write(' ');
            outputWriter.write(Integer.toString(arr[i]));
        }
    }
    void printArr(long[] arr) throws IOException {
        for (int i=0; i<arr.length; ++i) {
            if (i!=0) outputWriter.write(' ');
            outputWriter.write(Long.toString(arr[i]));
        }
    }
    void printArr(double[] arr) throws IOException {
        for (int i=0; i<arr.length; ++i) {
            if (i!=0) outputWriter.write(' ');
            outputWriter.write(Double.toString(arr[i]));
        }
    }
    void printArr(String[] arr) throws IOException {
        for (int i=0; i<arr.length; ++i) {
            if (i!=0) outputWriter.write(' ');
            outputWriter.write(arr[i]);
        }
    }
    void printArr(char[] arr) throws IOException {
        for (char c: arr) outputWriter.write(c);
    }
    void printlnArr(int[] arr) throws IOException {
        printArr(arr);
        outputWriter.newLine();
    }
    void printlnArr(long[] arr) throws IOException {
        printArr(arr);
        outputWriter.newLine();
    }
    void printlnArr(double[] arr) throws IOException {
        printArr(arr);
        outputWriter.newLine();
    }
    void printlnArr(String[] arr) throws IOException {
        printArr(arr);
        outputWriter.newLine();
    }
    void printlnArr(char[] arr) throws IOException {
        printArr(arr);
        outputWriter.newLine();
    }
    void halt(Object... o) throws IOException {
        if (o.length!=0) println(o);
        outputWriter.flush(); outputWriter.close();
        System.exit(0);
    }

    void debug(Object... o) {
        if (showDebug) System.err.println(Arrays.deepToString(o));
    }

    public static void main(String[] args) throws Exception {
        Locale.setDefault(Locale.US);
        new B().solve();
        outputWriter.flush(); outputWriter.close();
    }
}

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

public class B92 implements Runnable {

    private char[][] m;

    private void solve() throws IOException {
        int n = nextInt();
        int k = nextInt();
        m = new char[n][];
        int[] order = new int[k];
        for (int i = 0; i < n; i++) {
            m[i] = nextToken().toCharArray();
        }

        for (int i = 0; i < k; i++) {
            order[i] = -1;
        }
        writer.print(getDiff(order, k));

    }

    private int getDiff(int[] order, int k) {
        if(k==0){
            int mi=Integer.MAX_VALUE;
            int ma =Integer.MIN_VALUE;
            for(int i=0;i<m.length;i++){
                char[] number = new char[m[i].length];
                for(int z=0;z<order.length;z++){
                    char c = m[i][z];
                    number[order[z]]=c;
                }
                mi = Math.min(mi,Integer.parseInt(new String(number)));
                ma = Math.max(ma, Integer.parseInt(new String(number)));
            }
            return ma-mi;
        }

        k--;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < order.length; i++) {
            if (order[i] == -1) {
                order[i] = k;
                int diff = getDiff(order, k);
                if (diff < min) min = diff;
                order[i]=-1;
            }
        }
        return min;
    }

    public static void main(String[] args) {
        new B92().run();
    }

    BufferedReader reader;
    StringTokenizer tokenizer;
    PrintWriter writer;

    public void run() {
        try {

            boolean oj = System.getProperty("ONLINE_JUDGE") != null;

            reader = oj ? new BufferedReader(new InputStreamReader(System.in)) :
                    new BufferedReader(new FileReader(new File("input.txt")));

            tokenizer = null;
            writer = new PrintWriter(System.out);
            solve();
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }

    double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }

    String nextToken() throws IOException {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            tokenizer = new StringTokenizer(reader.readLine());
        }
        return tokenizer.nextToken();
    }
}

import java.util.*;
public class Permutations {
	public static int[][] val;
	public static int[] perm;
	public static int ans;
	public static void main(String[] Args){
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int k = sc.nextInt();
		val = new int[n][k];
		perm = new int[k];
		for(int j = 0;j<n;j++){
			int temp = sc.nextInt();
			for(int i = 0;i<k;i++){
				val[j][i]= temp%10;
				temp/=10;
			}
		}
		ans = 1000000000;
		rec(0,0);
		System.out.println(ans);
	}
	private static void rec(int i, int mask) {
		if(mask==(1<<val[0].length)-1){
			check();
			return;
		}
		for(int k =0;k<val[0].length;k++){
			if((mask&(1<<k))==0){
				perm[i] = k;
				rec(i+1,mask|(1<<k));
			}
		}
	}
	private static void check() {

		int max = 0;
		int inda  = 0;
		int min = 0;
		int indi = 0;
		for(int k = 0;k<val.length;k++){
			int temp = diff(0,k);
			if(max<temp){
				max = temp;
				inda = k;
			}
			if(min>temp){
				min = temp;
				indi = k;
			}
		}
		ans = Math.min(ans, Math.abs(diff(inda, indi)));
	}
	private static int diff(int i, int k) {
		int tans = 0;
		for(int j = 0;j<val[0].length;j++){
			tans*=10;
			tans += val[i][perm[j]]-val[k][perm[j]];
		}
		return tans;
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author AlexFetisov
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB_cf92 solver = new TaskB_cf92();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB_cf92 {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int k = in.nextInt();
            char[][] c = new char[n][];
            int[] p = new int[k];
            for (int i = 0; i < k; ++i) p[i] = i;
            for (int i = 0; i < n; ++i) {
                c[i] = in.nextString().toCharArray();
            }
            int best = Integer.MAX_VALUE;
            do {
                int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
                for (int i = 0; i < n; ++i) {
                    char[] nc = new char[k];
                    for (int j = 0; j < k; ++j) {
                        nc[j] = c[i][p[j]];
                    }
                    int x = Integer.parseInt(new String(nc));
                    min = Math.min(x, min);
                    max = Math.max(x, max);
                }
                best = Math.min(best, max - min);
            } while (ArrayUtils.nextPermutation(p));
            out.println(best);
        }

    }

    static class InputReader {
        private BufferedReader reader;
        private StringTokenizer stt;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream));
        }

        public String nextLine() {
            try {
                return reader.readLine();
            } catch (IOException e) {
                return null;
            }
        }

        public String nextString() {
            while (stt == null || !stt.hasMoreTokens()) {
                stt = new StringTokenizer(nextLine());
            }
            return stt.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(nextString());
        }

    }

    static class ArrayUtils {
        public static boolean nextPermutation(int[] p) {
            for (int a = p.length - 2; a >= 0; --a) {
                if (p[a] < p[a + 1]) {
                    for (int b = p.length - 1; ; --b) {
                        if (p[b] > p[a]) {
                            int t = p[a];
                            p[a] = p[b];
                            p[b] = t;
                            for (++a, b = p.length - 1; a < b; ++a, --b) {
                                t = p[a];
                                p[a] = p[b];
                                p[b] = t;
                            }
                            return true;
                        }
                    }
                }
            }
            return false;
        }

    }
}

import java.util.*;
public class HeapAlgo
{
    static String[] b = new String[8];
    static int n;
    static int min = 1000000000;
    //Prints the array
    void printArr(int a[], int k)
    {
        String[] nums = new String[n];
        for (int i=0; i<n; i++)
            nums[i] = "";
        for (int i=0; i<n; i++)
            for(int j=0; j<k; j++)
                nums[i] += b[i].charAt(a[j]);
        int m1 = -10000;
        int m2 = 1000000000;
        for(int i = 0; i < n; i++)
        {
            m1 = Math.max(Integer.parseInt(nums[i]),m1);
            m2 = Math.min(Integer.parseInt(nums[i]),m2);

        }
        min = Math.min(min, m1-m2);
        //System.out.println(min);
    }

    //Generating permutation using Heap Algorithm
    void heapPermutation(int a[], int size, int n)
    {
        // if size becomes 1 then prints the obtained
        // permutation
        if (size == 1)
            printArr(a,n);

        for (int i=0; i<size; i++)
        {
            heapPermutation(a, size-1, n);

            // if size is odd, swap first and last
            // element
            if (size % 2 == 1)
            {
                int temp = a[0];
                a[0] = a[size-1];
                a[size-1] = temp;
            }

            // If size is even, swap ith and last
            // element
            else
            {
                int temp = a[i];
                a[i] = a[size-1];
                a[size-1] = temp;
            }
        }
    }
    // Driver code
    public static void main(String args[])
    {
        Scanner s1 = new Scanner(System.in);
        String s = s1.nextLine();
        n = Integer.parseInt(s.split(" ")[0]);
        int k = Integer.parseInt(s.split(" ")[1]);
        for(int i = 0; i < n; i++)
            b[i] = s1.nextLine();
        HeapAlgo obj = new HeapAlgo();
        int[] a = new int[k];
        for(int i = 0; i < k; i++)
            a[i] = i;
        obj.heapPermutation(a, a.length, a.length);
        System.out.println(min);
    }
}

//package codeforces;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.StringTokenizer;

public class A implements Closeable {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

    A() throws IOException {
//        reader = new BufferedReader(new FileReader("input.txt"));
//        writer = new PrintWriter(new FileWriter("output.txt"));
    }

    StringTokenizer stringTokenizer;

    String next() throws IOException {
        while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
            stringTokenizer = new StringTokenizer(reader.readLine());
        }
        return stringTokenizer.nextToken();
    }

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

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

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

    private int MOD = 1000 * 1000 * 1000 + 7;

    int sum(int a, int b) {
        a += b;
        return a >= MOD ? a - MOD : a;
    }

    int product(int a, int b) {
        return (int) (1l * a * b % MOD);
    }

    int pow(int x, int k) {
        int result = 1;
        while (k > 0) {
            if (k % 2 == 1) {
                result = product(result, x);
            }
            x = product(x, x);
            k /= 2;
        }
        return result;
    }

    int inv(int x) {
        return pow(x, MOD - 2);
    }

    void solve() throws IOException {
        final int n = nextInt(), k = nextInt();
        final char[][] s = new char[n][];
        for(int i = 0; i < n; i++) {
            s[i] = next().toCharArray();
        }
        class Utils {
            int minDifference(int mask, int[] array) {
                if(mask == (1 << k) - 1) {
                    int min = array[0];
                    int max = min;
                    for (int x : array) {
                        min = Math.min(min, x);
                        max = Math.max(max, x);
                    }
                    return max - min;
                }
                for(int i = 0; i < n; i++) {
                    array[i] *= 10;
                }
                int best = Integer.MAX_VALUE;
                for(int i = 0; i < k; i++) {
                    if((mask & (1 << i)) == 0) {
                        for(int j = 0; j < n; j++) {
                            array[j] += s[j][i] - '0';
                        }
                        best = Math.min(best, minDifference(mask | (1 << i), array));
                        for(int j = 0; j < n; j++) {
                            array[j] -= s[j][i] - '0';
                        }
                    }
                }
                for(int i = 0; i < n; i++) {
                    array[i] /= 10;
                }
                return best;
            }
        }
        writer.println(new Utils().minDifference(0, new int[n]));
    }

    public static void main(String[] args) throws IOException {
        try (A a = new A()) {
            a.solve();
        }
    }

    @Override
    public void close() throws IOException {
        reader.close();
        writer.close();
    }
}

import java.io.*;
import java.util.*;
public class Permutations {
    static BufferedReader br;
    static String[] numbers;
    static int k;
    public static void main(String[] args) {
        try {
            br = new BufferedReader(new InputStreamReader(System.in));
            init();
            System.out.println(solve());
            br.close();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
    private static void init() throws IOException {
    	StringTokenizer st = new StringTokenizer(br.readLine());
    	numbers = new String[Integer.parseInt(st.nextToken())];
    	k = Integer.parseInt(st.nextToken());
    	for(int i = 0; i < numbers.length; i++)
    		numbers[i] = br.readLine();
    }
    private static String solve() {
    	int min = Integer.MAX_VALUE;
    	String s1 = "";
    	for(int i = 0; i < k; i++)
    		s1 += i + "";
    	String[] s = possibleDigits(s1);
        String[] changeable = new String[numbers.length];
        for(int i = 0; i < changeable.length; i++)
        	changeable[i] = "";
    	for(int i = 0; i < s.length; i++) {
    		int total = 0;
    		for(int j = 0; j < changeable.length; j++) {
    			for(int k = 0; k < numbers[j].length(); k++) {
    				String a = s[i].substring(k, k + 1);
    				changeable[j] += numbers[j].substring(Integer.parseInt(a), Integer.parseInt(a) + 1);
    			}
    		}
    		Arrays.sort(changeable);
    		total = Integer.parseInt(changeable[changeable.length - 1]) - Integer.parseInt(changeable[0]);
    		if(total < min)
    			min = total;
    		changeable = new String[numbers.length];
    		for(int j = 0; j < changeable.length; j++)
    			changeable[j] = "";
    	}
    	return String.valueOf(min);
    }
    private static String[] possibleDigits(String s) {
    	ArrayList<String> list = new ArrayList<String>();
    	list.add(s.substring(0, 1));
    	for(int i = 1; i < s.length(); i++) {
    		for(int j = list.size() - 1; j >= 0; j--) {
    			String str = list.remove(j);
    			for(int k = 0; k <= str.length(); k++)
    				list.add(str.substring(0, k) + s.charAt(i) + str.substring(k));
    		}
    	}
    	String[] res = new String[list.size()];
    	for(int i = 0; i < list.size(); i++)
    		res[i] = list.get(i);
    	return res;
    }
}

import java.util.*;

public class Permutations {
  public static void main(String[]args) {
    Scanner input = new Scanner(System.in);
    int n = input.nextInt();
    int k = input.nextInt();
    input.nextLine();
    String[] arr = new  String[n];
    for(int i = 0; i < n; i++)
      arr[i] = input.nextLine();
    int dif = Integer.MAX_VALUE;
    List<List<Integer>> perms = perms(k);
    for(List<Integer> i : perms) {
      int[] arrTwo = new int[n];
      for(int j = 0; j < n; j++) {
        arrTwo[j] = mix(i, arr[j], k);
      }
      int min = minArray(arrTwo);
      int max = maxAbsArray(arrTwo);
      dif = Math.min(dif, max-min);
    }
    System.out.println(dif);
  }

  public static int minArray(int[] arr) {
    int min = Integer.MAX_VALUE;
    for(int i = 0; i < arr.length; i++)
      min = Math.min(arr[i], min);
    return min;
  }

  public static int maxAbsArray(int[] arr) {
    int max = Integer.MIN_VALUE;
    for(int i = 0; i < arr.length; i++)
      max = Math.max(Math.abs(arr[i]), max);
    return max;
  }

  public static int mix(List<Integer> perms, String n, int k) {
    String s = n;
    if(s.length() < k) {
      for(int i = 0; i < k-1; i++) {
        s = "0"+s;
      }
    }
    String res = "";
    for(int i = 0; i < perms.size(); i++) {
      res += String.valueOf(s.charAt(perms.get(i)-1));
    }
    return Integer.parseInt(res);
  }

  public static List<List<Integer>> perms(int num) {
    List<List<Integer>> res = new ArrayList<>();
    if(num == 1) {
      res.add(new ArrayList<Integer>());
      res.get(0).add(1);
      return res;
    } else {
      List<List<Integer>> r = perms(num-1);
      for(List<Integer> l : r) {
        for(int i = 0; i < num; i++) {
          List<Integer> r2 = new ArrayList<>();
          for(int j : l) {
            r2.add(j);
          }
          r2.add(i, num);
          res.add(r2);
        }
      }
      return res;
    }
  }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author OmarYasser
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        public void solve(int testNumber, Scanner sc, PrintWriter out) {
            int n = sc.nextInt(), k = sc.nextInt();
            int[][] a = new int[n][k];
            for (int i = 0; i < n; i++) {
                char[] s = sc.next().toCharArray();
                for (int j = 0; j < k; j++)
                    a[i][j] = s[j] - '0';
            }

            int[] p = new int[k];
            for (int i = 0; i < k; i++)
                p[i] = i;

            int best = Integer.MAX_VALUE;
            do {
                int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
                for (int i = 0; i < n; i++) {
                    int num = apply(p, a[i]);
                    min = Math.min(min, num);
                    max = Math.max(max, num);
                }
                best = Math.min(best, max - min);
            } while (next_permutation(p));
            out.println(best);
        }

        static int apply(int[] p, int a[]) {
            int res = 0;
            for (int i = 0; i < a.length; i++) {
                res *= 10;
                res += a[p[i]];
            }
            return res;
        }

        static boolean next_permutation(int[] A) {
            for (int a = A.length - 2; a >= 0; --a) {
                if (A[a] < A[a + 1]) {
                    for (int b = A.length - 1; ; --b) {
                        if (A[b] > A[a]) {
                            int t = A[a];
                            A[a] = A[b];
                            A[b] = t;
                            for (++a, b = A.length - 1; a < b; ++a, --b) {
                                t = A[a];
                                A[a] = A[b];
                                A[b] = t;
                            }
                            return true;
                        }
                    }
                }
            }
            return false;
        }

    }

    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream s) {
            br = new BufferedReader(new InputStreamReader(s));
        }

        public Scanner(FileReader f) {
            br = new BufferedReader(f);
        }

        public String next() {
            while (st == null || !st.hasMoreTokens())
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (Exception e) {
                }
            return st.nextToken();
        }

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

    }
}

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

public class Main implements Runnable {

    // leave empty to read from stdin/stdout
    private static final String TASK_NAME_FOR_IO = "";

    // file names
    private static final String FILE_IN = TASK_NAME_FOR_IO + ".in";
    private static final String FILE_OUT = TASK_NAME_FOR_IO + ".out";

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tokenizer = new StringTokenizer("");

    public static void main(String[] args) {
        new Thread(new Main()).start();
    }

    private void solve() throws IOException {
        int n = nextInt(), k = nextInt();
        char [][]a = new char[n][k];
        for(int i = 0; i < n; ++i) {
            String s = nextToken();
            for(int j = 0; j < k; ++j) {
                a[i][j] = s.charAt(j);
            }
        }

        int []b = new int[k];
        for(int i = 0; i < k; ++i) b[i] = i;
        int min = Integer.MAX_VALUE/2;

        while(b.length > 0) {
            char [][]tmp = new char[n][k];
            for(int i = 0; i < n; ++i) {
                for(int j = 0; j < k; ++j) {
                    tmp[i][j] = a[i][b[j]];
                }
            }
            int []c = new int[n];
            for(int i = 0; i < n; ++i) {
                c[i] = Integer.parseInt(new String(tmp[i]));
            }
            Arrays.sort(c);
            // System.out.println(Arrays.toString(c) + " " + Arrays.toString(b));
            min = Math.min(min, c[n-1] - c[0]);
            // System.out.println(Arrays.toString(b));
            b = nextPermutation(b);
        }
        out.println(min);
    }

    private int[] nextPermutation(int []a) {
        int n = a.length, k = n - 2;
        if (n == 1) return new int[]{};
        while(k >= 0 && a[k] > a[k + 1]) {
            k--;
            if (k < 0) return new int[]{};
        }
        int idx = -1;
        for(int i = k + 1;i < n; ++i) {
            if (a[k] < a[i] && (idx == -1 || a[idx] > a[i])) {
                idx = i;
            }
        }

        int tmp = a[k];
        a[k] = a[idx];
        a[idx] = tmp;

        for(int i = k + 1, j = n - 1; i < j; ++i, --j) {
            tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }

        return a;
    }

    public void run() {
        long timeStart = System.currentTimeMillis();

        boolean fileIO = TASK_NAME_FOR_IO.length() > 0;
        try {

            if (fileIO) {
                in = new BufferedReader(new FileReader(FILE_IN));
                out = new PrintWriter(new FileWriter(FILE_OUT));
            } else {
                in = new BufferedReader(new InputStreamReader(System.in));
                out = new PrintWriter(new OutputStreamWriter(System.out));
            }

            solve();

            in.close();
            out.close();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
        long timeEnd = System.currentTimeMillis();

        if (fileIO) {
            System.out.println("Time spent: " + (timeEnd - timeStart) + " ms");
        }
    }

    private String nextToken() throws IOException {
        while (!tokenizer.hasMoreTokens()) {
            String line = in.readLine();
            if (line == null) {
                return null;
            }
            tokenizer = new StringTokenizer(line);
        }
        return tokenizer.nextToken();
    }

    private int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    private BigInteger nextBigInt() throws IOException {
        return new BigInteger(nextToken());
    }

    private long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }

    private double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }

}

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

public class B {
    public static StreamTokenizer in = new StreamTokenizer(System.in);
    public static boolean bg = true;
    public static long[][] data = null;
    public static long finmin = Long.MAX_VALUE;
    public static void main(String[] args) throws Exception {
        Scanner scan = new Scanner(System.in);
        int n1 = Integer.parseInt(scan.next());
        int k1 = Integer.parseInt(scan.next());

        data = new long[n1][];
        for (int i=0;i<n1;i++){
            char[] cur = scan.next().toCharArray();
            long[] cur2 = new long[cur.length];
            for (int j = 0;j<cur2.length;j++){
                cur2[j] = cur[j] - '0';
            }
            data[i] = cur2;
        }

        gen(k1);
        pn(finmin);
    }

    public static void gen(int k1){
        gen(new ArrayList(), new HashSet(), k1);
    }

    public static void gen(ArrayList<Integer> l1, HashSet<Integer> s1, int k1){
        if (l1.size()==k1){
            //pn(l1);
            long max = Long.MIN_VALUE;
            long min = Long.MAX_VALUE;
            for (long[] e: data){
                long cur = 0;
                for (int f: l1){
                    cur *=10;
                    cur += e[f];
                }
                if (cur>max){
                    max = cur;
                }
                if (cur<min){
                    min = cur;
                }
            }
            if (max-min<finmin){
                finmin = max - min;
            }
            //pn(max - min);

        }
        for (int i = 0;i<k1; i++){
            if (!s1.contains(i)){
                l1.add(i);
                s1.add(i);
                gen(l1,s1,k1);
                l1.remove(l1.size()-1);
                s1.remove(i);
            }
        }
    }

    private static int ni() throws Exception {
        in.nextToken();
        return (int) in.nval;
    }

    private static long nl() throws Exception {
        in.nextToken();
        return (long) in.nval;
    }

    private static double nd() throws Exception {
        in.nextToken();
        return in.nval;
    }

    private static void pn(Object o1) {
        System.out.println(o1);
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author cunbidun
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        BPermutations solver = new BPermutations();
        solver.solve(1, in, out);
        out.close();
    }

    static class BPermutations {
        private static final int INF = (int) 2e9 + 7;
        private int n;
        private int k;
        private boolean[] used = new boolean[10];
        private int[] a = new int[10];
        private int ans = INF;
        private char[][] c;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            n = in.nextInt();
            k = in.nextInt();
            c = in.nextCharTable(n, k, 1, 1);
            bt(1);
            out.println(ans);
        }

        private void bt(int pos) {
            if (pos == k + 1) {

                int max = 0;
                int min = INF;
                for (int i = 1; i <= n; i++) {
                    int cur = 0;
                    for (int j = 1; j <= k; j++) {
                        cur *= 10;
                        cur += c[i][a[j]] - '0';
                    }
                    max = MaxMin.Max(max, cur);
                    min = MaxMin.Min(min, cur);
                }
                ans = MaxMin.Min(ans, max - min);
            }
            for (int i = 1; i <= k; i++)
                if (!used[i]) {
                    a[pos] = i;
                    used[i] = true;
                    bt(pos + 1);
                    used[i] = false;
                }
        }

    }

    static class MaxMin {
        public static <T extends Comparable<T>> T Max(T x, T y) {
            T max = x;
            if (y.compareTo(max) > 0) max = y;
            return max;
        }

        public static <T extends Comparable<T>> T Min(T x, T y) {
            T min = x;
            if (y.compareTo(min) < 0) min = y;
            return min;
        }

    }

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

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

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

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public char[][] nextCharTable(int row, int col, int rowSt, int colSt) {
            char[][] arr = new char[row + rowSt][col + colSt];
            for (int i = rowSt; i < row + rowSt; i++) {
                for (int j = colSt; j < col + colSt; j++) {
                    arr[i][j] = nextCharacter();
                }
            }
            return arr;
        }

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

        public char nextCharacter() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            return (char) c;
        }

    }
}

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

public class Main {
    public static void main(String args[]) throws IOException {
        Scan sc = new Scan();
        int n = sc.scanInt();
        int k = sc.scanInt();
        Sol sol = new Sol(n, k);
        for(int i = 0; i < n; ++i){
            sol.add(i, sc.scanString());
        }
        sol.dfs(0, 0);
        System.out.println(sol.res);
    }
}

class Sol {
    int n, k, res;
    char[][] nums;

    Sol(int n, int k){
        res = Integer.MAX_VALUE;
        this.n = n;
        this.k = k;
        nums = new char[n][k];
    }

    void add(int i, String num){
        nums[i] = num.toCharArray();
    }

    void dfs(int depth, int start){
        if(depth == k){
            compute();
        }

        for(int i = start; i < k; ++i){
            swap(i, start);
            dfs(depth+1, start+1);
            swap(i, start);
        }
    }

    void compute(){
        int max = 0;
        int min = Integer.MAX_VALUE;
        for(char[] num : nums){
            int val = 0;
            for(char dig : num)
                val = (val*10 + (dig-'0'));
            if(val < min)
                min = val;
            if(val > max)
                max = val;
        }
        int diff = max- min;
        res = diff < res ? diff : res;
    }

    void swap(int i , int j){
        for(char[] num : nums){
            char t = num[i];
            num[i] = num[j];
            num[j] = t;
        }
    }
}

class Scan
{
    private byte[] buf=new byte[1024];
    private int index;
    private InputStream in;
    private int total;
    public Scan()
    {
        in=System.in;
    }
    public int scan()throws IOException
    {
        if(total<0)
        throw new InputMismatchException();
        if(index>=total)
        {
            index=0;
            total=in.read(buf);
            if(total<=0)
            return -1;
        }
        return buf[index++];
    }
    public int scanInt()throws IOException
    {
        int integer=0;
        int n=scan();
        while(isWhiteSpace(n))
        n=scan();
        int neg=1;
        if(n=='-')
        {
            neg=-1;
            n=scan();
        }
        while(!isWhiteSpace(n))
        {
            if(n>='0'&&n<='9')
            {
                integer*=10;
                integer+=n-'0';
                n=scan();
            }
            else throw new InputMismatchException();
        }
        return neg*integer;
    }
    public double scanDouble()throws IOException
    {
        double doub=0;
        int n=scan();
        while(isWhiteSpace(n))
        n=scan();
        int neg=1;
        if(n=='-')
        {
            neg=-1;
            n=scan();
        }
        while(!isWhiteSpace(n)&&n!='.')
        {
            if(n>='0'&&n<='9')
            {
                doub*=10;
                doub+=n-'0';
                n=scan();
            }
            else throw new InputMismatchException();
        }
        if(n=='.')
        {
            n=scan();
            double temp=1;
            while(!isWhiteSpace(n))
            {
                if(n>='0'&&n<='9')
                {
                    temp/=10;
                    doub+=(n-'0')*temp;
                    n=scan();
                }
                else throw new InputMismatchException();
            }
        }
        return doub*neg;
    }
    public String scanString()throws IOException
    {
        StringBuilder sb=new StringBuilder();
        int n=scan();
        while(isWhiteSpace(n))
        n=scan();
        while(!isWhiteSpace(n))
        {
            sb.append((char)n);
            n=scan();
        }
        return sb.toString();
    }
    private boolean isWhiteSpace(int n)
    {
        if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
        return true;
        return false;
    }
}

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class B92
{
	public static Scanner SCANNER = new Scanner(System.in);

	public static void swap(int[] a, int x, int y)
	{
		int temp = a[x];
		a[x] = a[y];
		a[y] = temp;
	}

	public static void heapPermutation(int a[], int size, List<int[]> result)
	{
		if (size == 1)
		{
			result.add(Arrays.copyOf(a, a.length));
		}
		for (int i = 0; i < size; i++)
		{
			heapPermutation(a, size - 1, result);
			if (size % 2 == 1)
			{
				swap(a, 0, size - 1);
			}
			else
			{
				swap(a, i, size - 1);
			}
		}
	}

	public static List<int[]> heapPermutation(int n)
	{
		List<int[]> result = new ArrayList<>();
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
		{
			a[i] = i;
		}
		heapPermutation(a, n, result);
		return result;
	}

	public static int[] permutate(int[] digits, int[] permutation)
	{
		int[] result = new int[digits.length];
		for (int i = 0; i < digits.length; i++)
		{
			result[permutation[i]] = digits[i];
		}
		return result;
	}

	public static int number(int[] digits)
	{
		int result = 0;
		for (int digit : digits)
		{
			result *= 10;
			result += digit;
		}
		return result;
	}

	public static void main(String[] args)
	{
		int n = SCANNER.nextInt();
		int k = SCANNER.nextInt();
		int[][] digits = new int[n][k];
		for (int i = 0; i < n; i++)
		{
			String string = SCANNER.next();
			for (int j = 0; j < k; j++)
			{
				digits[i][j] = string.charAt(j) - 48;
			}
		}
		List<int[]> permutations = heapPermutation(k);
		int result = 99999999;
		for (int[] permutation : permutations)
		{
			int min = 99999999;
			int max = 0;
			for (int i = 0; i < n; i++)
			{
				int number = number(permutate(digits[i], permutation));
				min = Math.min(min, number);
				max = Math.max(max, number);
			}
			result = Math.min(result, max - min);
		}
		System.out.println(result);
	}
}

//package acc;
//import java.math.BigInteger;
import java.util.*;

   public class ACC {

    public static void main(String[] args) {

        Scanner in=new Scanner (System.in);
        int n1=in.nextInt();
        int n=n1;
        String arr[]=new String[n];
 //       String arr1[]=new String[n];

        int k=in.nextInt();
        while(n1--!=0){
            arr[n1]=in.next();
   //         arr1[n1]=arr[n1];
        }
        if(n==1) System.out.print(0);
        else{
        int per[]=new int[k];
        for(int i=0;i<k;i++) per[i]=i;
        int ans=1000000000;
        do{
            int max=0;
            int min=1000000000;
            for(int i=0;i<n;i++){

                char[]copy=arr[i].toCharArray();
                for(int j=0;j<k;j++){
                    copy[j]= arr[i].charAt(per[j]);
                }
                String h=String.valueOf(copy);
                int p=Integer.parseInt(h);
                    if(p>max) max=p;
                    if(p<min) min=p;
            }
            if(max-min<ans) ans=max-min;
        }while(next_permutation(per)!=0);
       System.out.print(ans);
    }
    }

    public static class Pair<L,R> {
    private L l;
    private R r;
    public Pair(L l, R r){
        this.l = l;
        this.r = r;
    }
    public L getL(){ return l; }
    public R getR(){ return r; }
    public void setL(L l){ this.l = l; }
    public void setR(R r){ this.r = r; }
}
     public void print(int[] array) {
 for (int tmp : array) {
     System.out.print(" " + tmp);
 }
 System.out.println();
    }

    public static int next_permutation(int[] array) {
 int i, j;
 // Find the largest index k such that a[k] < a[k + 1]. If no such index
 // exists, the permutation is the last permutation.
 for (i = array.length - 2; i >= 0; i--) {
     if (array[i] < array[i + 1])
  break;
 }
 if (i < 0) {
     //System.out.println("End");
     return 0;
 }

 // Find the largest index l such that a[k] < a[l]. Since k + 1 is such
 // an index, l is well defined and satisfies k < l.
 for (j = array.length - 1; j > i; j--) {
     if (array[j] > array[i])
  break;
 }

 // Swap a[k] with a[l].
 swap(array, i++, j);

 // Reverse the sequence from a[k + 1] up to and including the final
 // element a[n].
 for (j = array.length - 1; j > i; i++, j--) {
     swap(array, i, j);
 }
 return 1;
    }

    public static void swap(int[] array, int x, int y) {
 array[x] ^= array[y];
 array[y] ^= array[x];
 array[x] ^= array[y];
    }
}

import java.util.ArrayList;
import java.util.Scanner;
//probB

public class Main {

	public static void main(String[] args)
	{
		Scanner scanner = new Scanner(System.in);
		int numbers = scanner.nextInt();
		scanner.nextInt();
		ArrayList<ArrayList<String>> lists = new ArrayList<ArrayList<String>>();
		for(int i = 0; i < numbers; ++i)
		{
			String num = scanner.next();
			lists.add(permute(new StringBuilder(num),0,num.length(),new ArrayList<String>()));
		}
		int min = Integer.MAX_VALUE;
		for(int n = 0; n < lists.get(0).size(); ++n)
		{
			int tempMin = Integer.MAX_VALUE;
			int tempMax = Integer.MIN_VALUE;
			for(int i = 0; i < numbers; ++i)
			{
				if(Integer.valueOf(lists.get(i).get(n)) > tempMax) tempMax = Integer.valueOf(lists.get(i).get(n));
				if(Integer.valueOf(lists.get(i).get(n)) < tempMin) tempMin = Integer.valueOf(lists.get(i).get(n));
			}
			if(tempMax - tempMin < min) min = tempMax - tempMin;
		}
		System.out.println(min);
	}

	public static void exchange(StringBuilder input, int i, int j)
	{
		String temp = input.substring(i,i+1);
		input.replace(i, i+1, input.substring(j,j+1));
		input.replace(j,j+1,temp);
	}

	public static ArrayList<String> permute(StringBuilder input, int i, int length, ArrayList<String> list)
	{
		if(i == length - 1)
		{
			list.add(input.toString());
		}
		else
		{
			for(int j = i; j < length; ++j)
			{
				exchange(input, i, j);
				permute(input, i+1,length,list);
				exchange(input,i,j);

			}
		}

		return list;

	}

}

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

public class Template implements Runnable {

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

    void init() throws FileNotFoundException {
        try {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        } catch (Exception e) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        }
    }

    class GraphBuilder {
        int n, m;
        int[] x, y;
        int index;
        int[] size;

        GraphBuilder(int n, int m) {
            this.n = n;
            this.m = m;
            x = new int[m];
            y = new int[m];
            size = new int[n];
        }

        void add(int u, int v) {
            x[index] = u;
            y[index] = v;
            size[u]++;
            size[v]++;
            index++;
        }

        int[][] build() {
            int[][] graph = new int[n][];
            for (int i = 0; i < n; i++) {
                graph[i] = new int[size[i]];
            }
            for (int i = index - 1; i >= 0; i--) {
                int u = x[i];
                int v = y[i];
                graph[u][--size[u]] = v;
                graph[v][--size[v]] = u;
            }
            return graph;
        }
    }

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            try {
                tok = new StringTokenizer(in.readLine());
            } catch (Exception e) {
                return null;
            }
        }
        return tok.nextToken();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

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

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

    long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }

    <T> List<T>[] createGraphList(int size) {
        List<T>[] list = new List[size];
        for (int i = 0; i < size; i++) {
            list[i] = new ArrayList<>();
        }
        return list;
    }

    public static void main(String[] args) {
        new Template().run();
        // new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start();
    }

    long timeBegin, timeEnd;

    void time() {
        timeEnd = System.currentTimeMillis();
        System.err.println("Time = " + (timeEnd - timeBegin));
    }

    long memoryTotal, memoryFree;

    void memory() {
        memoryFree = Runtime.getRuntime().freeMemory();
        System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10)
                + " KB");
    }

    public void run() {
        try {
            timeBegin = System.currentTimeMillis();
            memoryTotal = Runtime.getRuntime().freeMemory();
            init();
            solve();
            out.close();
            if (System.getProperty("ONLINE_JUDGE") == null) {
                time();
                memory();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    char[][] a;
    int[] index;
    int best = Integer.MAX_VALUE;

    void brut(int pos) {
        if (pos == index.length) {
            int min = Integer.MAX_VALUE;
            int max = Integer.MIN_VALUE;
            for (int x = 0; x < a.length; x++) {
                int v = 0;
                for (int i : index) {
                    v = v * 10 + a[x][i] - '0';
                }
                min = Math.min(min, v);
                max = Math.max(max, v);
            }
            best = Math.min(best, max - min);
            return;
        }

        for (int i = pos; i < index.length; i++) {
            int t = index[i];
            index[i] = index[pos];
            index[pos] = t;
            brut(pos + 1);
            t = index[i];
            index[i] = index[pos];
            index[pos] = t;
        }
    }

    void solve() throws IOException {
        int n = readInt();
        int k = readInt();
        a = new char[n][];
        for (int i = 0; i < n; i++) {
            a[i] = readString().toCharArray();
        }
        index = new int[k];
        for (int i = 0; i < k; i++) {
            index[i] = i;
        }
        brut(0);
        out.println(best);

    }

}

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

public class Permutations {
    public static int n;
    public static int k;
    public static String[] a;
    public static int[] p;
    public static boolean[] b;
    public static int gmin = Integer.MAX_VALUE;
    public static void main(String[] args) throws IOException {
        BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(f.readLine());
        n = Integer.parseInt(st.nextToken());
        k = Integer.parseInt(st.nextToken());
        a = new String[n];
        for (int i = 0; i < n; i++)
            a[i] = f.readLine();

        p = new int[k];
        b = new boolean[k];
        f(0);
        System.out.println(gmin);
    }

    public static void f(int m) {
        if (m == k) {
            int min = Integer.MAX_VALUE;
            int max = 0;
            for (int i = 0; i < n; i++) {
                String str = a[i];
                String s = "";
                for (int j = 0; j < k; j++)
                    s += str.charAt(p[j]);
                int x = Integer.parseInt(s);
                if (x < min)
                    min = x;
                if (x > max)
                    max = x;
            }
            if (max-min < gmin)
                gmin = max-min;
        }

        for (int i = 0; i < k; i++)
            if (!b[i]) {
                p[m] = i;
                b[i] = true;
                f(m+1);
                b[i] = false;
            }

    }
}

import java.util.*;
import java.math.*;
import java.io.*;
public class P124B {
        int[] vals;
        int K;
        int digit(int val, int d) {
                for (int i=0; i<d; i++)
                        val/=10;
                return val%10;
        }
        int foo(int k, int mask, int[] v) {
                if (k==0) {
                        int min = Integer.MAX_VALUE;
                        int max = Integer.MIN_VALUE;
                        for (int i: v) {
                                min = Math.min(min,i);
                                max = Math.max(max,i);
                        }
                        return max-min;
                }

                int best = Integer.MAX_VALUE;
                for (int i=0; i<K; i++)
                        if (((mask>>i)&1)==0) {
                                int[] nvals = new int[vals.length];
                                for (int j=0; j<vals.length; j++)
                                        nvals[j] = v[j]*10 + digit(vals[j],i);
                                        best = Math.min(best,foo(k-1,mask|(1<<i),nvals));
                        }
                return best;
        }
        P124B(FastScanner in) throws Exception {
                int N = in.nextInt();
                K = in.nextInt();
                vals = new int[N];
                for (int i=0; i<N; i++)
                        vals[i] = in.nextInt();
                System.out.println(foo(K,0,new int[N]));
        }
        public static void main(String[] args) throws Exception {
                new P124B(new FastScanner(System.in));
        }

        static class FastScanner {
                BufferedReader br;
                StringTokenizer st;
                public FastScanner(InputStream in) throws Exception {
                        br = new BufferedReader(new InputStreamReader(in));
                        st = new StringTokenizer(br.readLine().trim());
                }
                public String next() throws Exception {
                        if (!st.hasMoreTokens()) {
                                st = new StringTokenizer(br.readLine().trim());
                                return next();
                        }
                        return st.nextToken();
                }
                public double nextDouble() throws Exception {
                        return Double.parseDouble(next());
                }
                public long nextLong() throws Exception {
                        return Long.parseLong(next());
                }
                public int nextInt() throws Exception {
                        return Integer.parseInt(next());
                }
                public String nextLine() throws Exception {
                        return br.readLine().trim();
                }
        }
}

//package ComeBack;
import java.util.Arrays;
import java.util.Scanner;

public class B {
	static int n , k;
	static String[] arr;
	static int ans = (int)1e9;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		k = sc.nextInt();
		int[] ind = new int[k];
		for(int i=0;i<k;i++)
			ind[i]=i;
		arr = new String[n];
		for(int i=0;i<n;i++)
			arr[i] = sc.next();
		do{
			int[] b = new int[n];
			for(int i=0;i<n;i++)
			{
				StringBuilder s = new StringBuilder();
				for(int x : ind)
					s.append(arr[i].charAt(x));
				b[i] = Integer.parseInt(s.toString());
			}
			Arrays.sort(b);
			ans = Math.min(ans, b[b.length-1]-b[0]);
		}
		while(nextPermutation(ind));
		System.out.println(ans);
		sc.close();
	}

	static boolean nextPermutation(int[] c)
	{
		int first = getFirst(c);
		if(first == -1)
			return false;
		int toSwap = c.length - 1;
		while (c[first] >= c[toSwap])
			--toSwap;
		swap(c, first++, toSwap);
		toSwap = c.length - 1;
		while(first < toSwap)
			swap(c, first++, toSwap--);
		return true;
	}
	static int getFirst(int[] c)
	{
		for ( int i = c.length - 2; i >= 0; i--)
			if (c[i] < c[i + 1])
				return i;
		return -1;
	}
	static void swap(int[] c,int i, int j)
	{
		int tmp = c[i];
		c[i] = c[j];
		c[j] = tmp;
	}
}

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

public class Main {
	static int mod = 1000000007;
	public static boolean next_permutation(int[] p) {
		  for (int a = p.length - 2; a >= 0; --a)
		    if (p[a] < p[a + 1])
		      for (int b = p.length - 1;; --b)
		        if (p[b] > p[a]) {
		          int t = p[a];
		          p[a] = p[b];
		          p[b] = t;
		          for (++a, b = p.length - 1; a < b; ++a, --b) {
		            t = p[a];
		            p[a] = p[b];
		            p[b] = t;
		          }
		          return true;
		        }
		  return false;
		}

	public static int get(char s[][] , int n , int k , int perm[]) {
		int mx = (int )-1e9; int mn = (int)1e9;
		for(int i = 0; i<n; i++) {
			int t = 0;
			for(int j = 0; j<k; j++) {
				t = t*10 + (s[i][perm[j]] - '0');
			}
			mx = Math.max(t , mx);
			mn = Math.min(t,  mn);
		}
		return mx -mn;
	}

	public static void solve(InputReader in, OutputWriter out) {
		int n = in.readInt();
		int k = in.readInt();
		char s[][] = new char[n][k];
		int perm[] = new int[k];
		for(int i =0; i<k; i++)
			perm[i] = i;
		for(int i = 0; i<n; i++) {
			char p[] = in.readString().toCharArray();
			for(int j = 0; j<k; j++) {
				s[i][j] = p[j];
			}
		}
		int ans = get(s , n , k , perm);
		while(next_permutation(perm)) {
			ans = Math.min(ans, get(s,n,k,perm));
		}
		out.print(ans);
	}

	public static void main(String[] args) {
		InputReader in = new InputReader(System.in);
		OutputWriter out = new OutputWriter(System.out);
		int t = 1;
		while (t-- > 0) {
			solve(in , out);
			System.out.println();
		}
		out.flush();
		out.close();
	}
}

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

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

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

     public int readInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

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

     public long readLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			if (c < '0' || c > '9') {
				throw new InputMismatchException();
			}
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

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

     public String next() {
		return readString();
	}

     public interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}
}

class OutputWriter {
	private final PrintWriter writer;

	public OutputWriter(OutputStream outputStream) {
		writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
	}

	public OutputWriter(Writer writer) {
		this.writer = new PrintWriter(writer);
	}

	public void print(Object... objects) {
		for (int i = 0; i < objects.length; i++) {
			if (i != 0)
				writer.print(' ');
			writer.print(objects[i]);
		}
	}

	public void println(Object... objects) {
		print(objects);
		writer.println();
	}

	public void close() {
		writer.close();
	}

	public void flush() {
		writer.flush();
	}
}

import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.List;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Alex
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskB {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
	    int n = in.ri(), k = in.ri();
	    int[][] nums = new int[n][k];
	    for(int i = 0; i < n; i++)
		    for(int j = 0; j < k; j++)
			    nums[i][j] = (Character.getNumericValue(in.readCharacter()));
	    ArrayList<ArrayList<Integer>>[] permutations = new ArrayList[n];
	    for(int i = 0; i < n; i++) permutations[i] = permute(nums[i]);
	    int res = Integer.MAX_VALUE;
	    for(int i = 0; i < permutations[0].size(); i++) {
		    int min = Integer.MAX_VALUE, max = 0;
		    for(int j = 0; j < n; j++) {
			    int val = getVal(permutations[j].get(i));
			    min = Math.min(min, val);
			    max = Math.max(max, val);
		    }
res = Math.min(res, max - min);
}
	    out.printLine(res);
    }
	int getVal(ArrayList<Integer> num){
		int res = 0;
		for(int i = 0; i < num.size(); i++) {
			res += num.get(i) * (int) IntegerUtils.power(10, num.size() - i - 1);
		}
		return res;
	}
	public ArrayList<ArrayList<Integer>> permute(int[] num) {
		ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
		result.add(new ArrayList<Integer>());
		for (int i = 0; i < num.length; i++) {
			ArrayList<ArrayList<Integer>> current = new ArrayList<ArrayList<Integer>>();
			for (ArrayList<Integer> l : result) {
				for (int j = 0; j < l.size()+1; j++) {
					l.add(j, num[i]);
					ArrayList<Integer> temp = new ArrayList<Integer>(l);
					current.add(temp);
					l.remove(j);
				}
			}
			result = new ArrayList<ArrayList<Integer>>(current);
		}
		return result;
	}
}

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

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

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

	public int readInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}
	public boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return isWhitespace(c);
	}

	public static boolean isWhitespace(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}
	public char readCharacter() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		return (char) c;
	}
	public interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}
}

class OutputWriter {
	private final PrintWriter writer;

	public OutputWriter(OutputStream outputStream) {
		writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
	}
	public void close() {
		writer.close();
	}
	public void printLine(int i) {
		writer.println(i);
	}

}

class IntegerUtils {
	public static long power(long base, long exponent) {
		if (exponent == 0)
			return 1;
		long result = power(base, exponent >> 1);
		result = result * result;
		if ((exponent & 1) != 0)
			result = result * base;
		return result;
	}
}

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {

	static int n,k;
	static int[] perm ;
	static char[][] a;
	static boolean[] taken;

	static int parse(int idx)
	{
		StringBuilder s = new StringBuilder();
		for(int i = 0; i < k;i++)
			s.append(a[idx][perm[i]]);
		return Integer.parseInt(s.toString());
	}

	static int f()
	{
		int min = Integer.MAX_VALUE , max = Integer.MIN_VALUE;
		for (int i = 0; i < n; i++)
		{
			int cur = parse(i);
			max = Math.max(max, cur);
			min = Math.min(min, cur);
		}
		return max-min;
	}

	static int solve(int idx)
	{
		if(idx<0)return f();
		int ans = Integer.MAX_VALUE;
		for(int i = 0; i < k;i++)
		{
			if(!taken[i])
			{
				taken[i] = true;
				perm[idx] = i;
				ans = Math.min(ans, solve(idx-1));
				taken[i] = false;
			}
		}
		return ans;
	}

	public static void main(String[] args) throws Throwable {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt() ; k = sc.nextInt();
		taken = new boolean[k];
		perm = new int[k];
		a = new char[n][k];
		for (int i = 0; i < n; i++)
			a[i] = sc.nextLine().toCharArray();
		System.out.println(solve(k-1));
	}

	static class Scanner
	{
		StringTokenizer st;
		BufferedReader br;
		public Scanner(InputStream s){	br = new BufferedReader(new InputStreamReader(s));}
		public Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file));}
		public String next() throws IOException
		{
			while (st == null || !st.hasMoreTokens())st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}
		public int nextInt() throws IOException {return Integer.parseInt(next());}
		public long nextLong() throws IOException {return Long.parseLong(next());}
		public String nextLine() throws IOException {return br.readLine();}
		public double nextDouble() throws IOException
		{
			String x = next();
			StringBuilder sb = new StringBuilder("0");
			double res = 0, f = 1;
			boolean dec = false, neg = false;
			int start = 0;
			if(x.charAt(0) == '-'){neg = true;start++;}
			for(int i = start; i < x.length(); i++)
				if(x.charAt(i) == '.')
				{
					res = Long.parseLong(sb.toString());
					sb = new StringBuilder("0");
					dec = true;
				}
				else{sb.append(x.charAt(i));if(dec)f *= 10;}
			res += Long.parseLong(sb.toString()) / f;
			return res * (neg?-1:1);
		}
		public int[] nexIntArray() throws Throwable
		{
			st = new StringTokenizer(br.readLine());
			int[] a = new int[st.countTokens()];
			for(int i = 0; i < a.length;i++)a[i]=nextInt();
			return a;
		}
		public boolean ready() throws IOException {return br.ready();}
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Artem Gilmudinov
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Reader in = new Reader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        public void solve(int testNumber, Reader in, PrintWriter out) {
            int n, k;
            n = in.ni();
            k = in.ni();
            int[] a = new int[k];
            for (int i = 0; i < k; i++) {
                a[i] = i;
            }
            String[] nums = new String[n];
            for (int i = 0; i < n; i++) {
                nums[i] = in.rl();
            }
            int pow = (int) Utils.binpow(10, k - 1, 1_000_000_000);
            int res = Integer.MAX_VALUE;
            do {
                int min = Integer.MAX_VALUE;
                int max = Integer.MIN_VALUE;
                for (int i = 0; i < n; i++) {
                    int cur = 0;
                    for (int z = 0, p = pow; z < k; z++, p /= 10) {
                        cur += ((nums[i].charAt(a[z]) - '0') * p);
                    }
                    min = Math.min(cur, min);
                    max = Math.max(cur, max);
                }
                res = Math.min(res, max - min);

            } while (Utils.nextPermutation(a));
            out.println(res);
        }

    }

    static class Utils {
        public static long binpow(long a, long pow, long mod) {
            if (pow == 0) {
                return 1;
            }
            long res = binpow(a, pow / 2, mod);
            if (pow % 2 == 0) {
                return (res * res) % mod;
            } else {
                return (((res * res) % mod) * a) % mod;
            }
        }

        public static boolean nextPermutation(int[] a) {
            int temp, mid, n;
            n = a.length;
            for (int i = n - 1; i > 0; i--) {
                if (a[i] > a[i - 1]) {
                    for (int j = n - 1; j >= i; j--) {
                        if (a[j] > a[i - 1]) {
                            temp = a[i - 1];
                            a[i - 1] = a[j];
                            a[j] = temp;
                            break;
                        }
                    }
                    mid = i + (n - i) / 2;
                    for (int j = i, z = 0; j < mid; z++, j++) {
                        temp = a[j];
                        a[j] = a[n - z - 1];
                        a[n - z - 1] = temp;
                    }
                    return true;
                }
            }
            return false;
        }

    }

    static class Reader {
        private BufferedReader in;
        private StringTokenizer st = new StringTokenizer("");
        private String delim = " ";

        public Reader(InputStream in) {
            this.in = new BufferedReader(new InputStreamReader(in));
        }

        public String next() {
            if (!st.hasMoreTokens()) {
                st = new StringTokenizer(rl());
            }
            return st.nextToken(delim);
        }

        public String rl() {
            try {
                return in.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        public int ni() {
            return Integer.parseInt(next());
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author pandusonu
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        public int ans;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.readInt();
            int k = in.readInt();
            ans = Integer.MAX_VALUE;
            String[] a = new String[n];
            for (int i = 0; i < n; i++) {
                a[i] = in.readString();
            }
            ArrayList<Integer> x = new ArrayList<>();
            for (int i = 0; i < k; i++) {
                x.add(i);
                genPerm(x, a, k);
                x.remove(new Integer(i));
            }
            out.println(ans);
        }

        public void genPerm(ArrayList<Integer> x, String[] a, int k) {
            if (x.size() == k) {
                getAns(x, a);
                return;
            }
            for (int i = 0; i < k; i++) {
                if (!x.contains(i)) {
                    x.add(i);
                    genPerm(x, a, k);
                    x.remove(new Integer(i));
                }
            }
        }

        public void getAns(ArrayList<Integer> x, String[] a) {
            int[] newA = new int[a.length];
            for (int i = 0; i < x.size(); i++) {
                for (int j = 0; j < a.length; j++) {
                    newA[j] = newA[j] * 10 + (a[j].charAt(x.get(i)) - '0');
                }
            }
            Arrays.sort(newA);
            ans = Math.min(ans, newA[a.length - 1] - newA[0]);
        }

    }

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

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

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

        public int readInt() {
            return (int) readLong();
        }

        public long readLong() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
                if (c == -1) throw new RuntimeException();
            }
            boolean negative = false;
            if (c == '-') {
                negative = true;
                c = read();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9') throw new InputMismatchException();
                res *= 10;
                res += (c - '0');
                c = read();
            } while (!isSpaceChar(c));
            return negative ? (-res) : (res);
        }

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

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

    }
}

import java.io.*;
import java.math.*;
import java.security.KeyStore.Entry;
import java.util.*;

 public class Main {
	private InputStream is;
	private PrintWriter out;
	int time = 0, dp[][], DP[][], start[], end[], val[], black[], MOD = (int)(1e9+7), arr[], arr1[];
	int MAX = 500010, N, K, p;
	ArrayList<Integer>[] amp, amp1;
	boolean b[], b1[];
	Pair prr[];
	char ch[][];
	HashSet<Integer> hs = new HashSet<>();

	public static void main(String[] args) throws Exception {
		new Thread(null, new Runnable() {
		public void run() {
			try {

		//new Main().soln();
		} catch (Exception e) {
				System.out.println(e);
			}
		}
	}, "1", 1 << 26).start();
		new Main().soln();
	}
	class Node{
		Node next;
		int value;
	}
	void solve() {
		N = ni(); K = ni();
		ch = new char[N][K];
		for(int i = 0; i<N; i++) ch[i] = ns().toCharArray();
		recur(0);
		System.out.println(ans);
		/*
		N = ni(); K= ni();
		arr = na(N);
		amp = (ArrayList<Integer>[]) new ArrayList[100000];
		p = 0;
		dp = new int[2000][2000];
		DP = new int[2000][2000];
		for(int i = 0;i<2000;i++) for (int j = 0; j< 2000;j++){
			DP[i][j] = -1;
			dp[i][j]=-1;
		}
		recur(0,0);
		//System.out.println(K);
		for(int i = 0; i< p ;i++){
			//System.out.println(amp[i]);
			arr1 = new int[amp[i].size()];
			N = arr1.length;
			for(int j = 0; j< N;j++){
				arr1[j] = amp[i].get(j);
			}
			recur1(0,0);
			//System.out.println(HS.size());
		}
		//System.out.println(HS);
		ArrayList<Integer> ans = new ArrayList<>();
		out.println(HS.size());

		for(int i : HS) ans.add(i);
		Collections.sort(ans);
		for(int i : ans) out.print(i+" ");*/

	}
	int ans = Integer.MAX_VALUE;
	ArrayList<Integer> bbb = new ArrayList<>();
	void recur(int i){
		if(i==K){
		//	System.out.println(bbb);
		StringBuilder sb = new StringBuilder();
		TreeSet<Integer> temp = new TreeSet<>();
		for(int j = 0; j<N;j++){
			sb = new StringBuilder();
			for(int k = 0; k<K;k++){
				sb.append(ch[j][bbb.get(k)]);
			}
			temp.add(Integer.parseInt(sb.toString()));
		}
		ans = Math.min(ans, (temp.last()-temp.first()));
		//System.out.println(ans);
		return;
		}
		for(int j = 0;j<K;j++){
			if(!bbb.contains(j)){
				bbb.add(j);
				recur(i+1);
				bbb.remove((Integer)(j));
			}
		}
	}
	HashSet<Integer> HS = new HashSet<>();
	void recur1(int n, int k){
		if(k>K) return;
		if(k<=K) HS.add(k);
		if(DP[n][k]!=-1) return;
		DP[n][k] = -1;
		for(int i = n; i<N;i++){
			recur1(i+1,k+arr[arr1[i]]);
		}
	}
	ArrayList<Integer> temp = new ArrayList<>();
	void recur(int n, int k){
		//System.out.println(k);
		//System.out.println(temp);
		if(k>K || n>=N) return;
		if(k==K){
			amp[p++] = (ArrayList<Integer>) temp.clone();
			return;
		}
		if(dp[n][k]!=-1) return;
		dp[n][k] = 1;
		for(int i = n; i< N; i++){
			temp.add(i);
			recur(i+1,k+arr[i]);
			temp.remove((Integer)i);
		}
	}
	int min(int x,int y){
		if(x<y) return x;
		return y;
	}
	int max(int x,int y){
		if(x>y) return x;
		return y;
	}
	void dfs(int x){
		b[x] = true;
		for(int i : amp[x]){
			if(!b[i]){
				dfs(i);
			}
		}
	}
	void buildGraph(int m){
		while(m-->0)
		{
			int x = ni(), y = ni();
			amp[--x].add(--y);
		}
	}
	long modInverse(long a, long mOD2){
        return  power(a, mOD2-2, mOD2);
	}
	long power(long x, long y, long m)
	{
		if (y == 0)
    return 1;
	long p = power(x, y/2, m) % m;
	p = (p * p) % m;

	return (y%2 == 0)? p : (x * p) % m;
	}
	boolean isPrime(int x){
		for(int i = 2;i*1L*i<=x;i++) if(x%i==0) return false;
		return true;
	}
	public long gcd(long a, long b){
		if(b==0) return a;
		return gcd(b,a%b);
	}
	void failFn(String str, int arr[]){
		int len = 0;
		arr[0] = 0;
		int i = 1;
		while(i<arr.length){
			if(str.charAt(i)==str.charAt(len)){
				arr[i++] = ++len;
				continue;
			}
			if(len == 0){
				arr[i] = len;
				i++;
				continue;
			}
			if(str.charAt(i)!=str.charAt(len)){
				len = arr[len-1];
			}
		}
	}
	static class ST1{
		int arr[], st[], size;
		ST1(int a[]){
			arr = a.clone();
			size = 10*arr.length;
			st = new int[size];
			build(0,arr.length-1,1);
		}
		void build(int ss, int se, int si){
			if(ss==se){
				st[si] = arr[ss];
				return;
			}
			int mid = (ss+se)/2;
			int val = 2*si;
			build(ss,mid,val); build(mid+1,se,val+1);
			st[si] = (st[val]+ st[val+1]);
		}
		int get(int ss, int se, int l, int r, int si){
			if(l>se || r<ss || l>r) return Integer.MAX_VALUE;
			if(l<=ss && r>=se) return st[si];
			int mid = (ss+se)/2;
			int val = 2*si;
			return (get(ss,mid,l,r,val)+ get(mid+1,se,l,r,val+1));
		}
	}
	static class ST{
		int arr[],lazy[],n;
		ST(int a){
			n = a;
			arr = new int[10*n];
			lazy = new int[10*n];
		}
		void up(int l,int r,int val){
			update(0,n-1,0,l,r,val);
		}
		void update(int l,int r,int c,int x,int y,int val){
			if(lazy[c]!=0){
				lazy[2*c+1]+=lazy[c];
				lazy[2*c+2]+=lazy[c];
				if(l==r)
					arr[c]+=lazy[c];
				lazy[c] = 0;
			}
			if(l>r||x>y||l>y||x>r)
				return;
			if(x<=l&&y>=r){
				lazy[c]+=val;
				return ;
			}
			int mid = l+r>>1;
			update(l,mid,2*c+1,x,y,val);
			update(mid+1,r,2*c+2,x,y,val);
			arr[c] = (arr[2*c+1]+ arr[2*c+2]);
		}
		int an(int ind){
			return ans(0,n-1,0,ind);
		}
		int ans(int l,int r,int c,int ind){
			if(lazy[c]!=0){
				lazy[2*c+1]+=lazy[c];
				lazy[2*c+2]+=lazy[c];
				if(l==r)
					arr[c]+=lazy[c];
				lazy[c] = 0;
			}
			if(l==r)
				return arr[c];
			int mid = l+r>>1;
			if(mid>=ind)
				return ans(l,mid,2*c+1,ind);
			return ans(mid+1,r,2*c+2,ind);
		}
	}
	public static class FenwickTree {

	    int[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates

	    public FenwickTree(int size) {
	        array = new int[size + 1];
	    }
	    public int rsq(int ind) {
	        assert ind > 0;
	        int sum = 0;
	        while (ind > 0) {
	            sum += array[ind];
	            //Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number
	            ind -= ind & (-ind);
	        }
	        return sum;
	    }
	    public int rsq(int a, int b) {
	        assert b >= a && a > 0 && b > 0;
	        return rsq(b) - rsq(a - 1);
	    }
	    public void update(int ind, int value) {
	        assert ind > 0;
	        while (ind < array.length) {
	            array[ind] += value;
	            //Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number
	            ind += ind & (-ind);
	        }
	    }
	    public int size() {
	        return array.length - 1;
	    }
	}
	public static int[] shuffle(int[] a, Random gen){
		for(int i = 0, n = a.length;i < n;i++)
		{
			int ind = gen.nextInt(n-i)+i;
			int d = a[i];
			a[i] = a[ind];
			a[ind] = d;
		}
	return a;
	}

	class Pair implements Comparable<Pair>{
		int u, v;
		Pair(int u, int v){
			this.u = u;
			this.v = v;
		}public int hashCode() {
			return Objects.hash();
		}
		public boolean equals(Object o) {
			Pair other = (Pair) o;
			return ((u == other.u && v == other.v));// || (v == other.u && u == other.v));
		}
		public int compareTo(Pair other) {
			//return Integer.compare(val, other.val);
			return Long.compare(u, other.u) != 0 ? (Long.compare(u, other.u)) : (Long.compare(other.v,v));
		}
		public String toString() {
			return "[u=" + u + ", v=" + v + "]";
		}
	}
	long power(long x, long y, int mod){
		long ans = 1;
		while(y>0){
			if(y%2==0){
				x = (x*x)%mod;
				y/=2;
			}
			else{
				ans = (x*ans)%mod;
				y--;
			}
		}
		return ans;
	}
	void soln() {
		is = System.in;
		out = new PrintWriter(System.out);
		long s = System.currentTimeMillis();
		solve();
		//out.close();
		out.flush();
		//tr(System.currentTimeMillis() - s + "ms");
	}

	// To Get Input
	// Some Buffer Methods
	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;

	private int readByte() {
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf) {
			ptrbuf = 0;
			try {
				lenbuf = is.read(inbuf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) {
		return !(c >= 33 && c <= 126);
	}

	private int skip() {
		int b;
		while ((b = readByte()) != -1 && isSpaceChar(b))
			;
		return b;
	}

	private double nd() {
		return Double.parseDouble(ns());
	}

	private char nc() {
		return (char) skip();
	}
	private String ns() {
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != '
									// ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n) {
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n && !(isSpaceChar(b))) {
			buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m) {
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	private int[] na(int n) {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}

	private int ni() {
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl() {
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

	private void tr(Object... o) {
		if (!oj)
			System.out.println(Arrays.deepToString(o));
	}
}

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

public class Permutation {

	static SortedSet<String> perm;
	static int n,k;

	static String toString(int[] idx) {
		StringBuilder sb = new StringBuilder("");
		for(int i=0;i<k;i++)
			sb.append(""+idx[i]);
		return sb.toString();

	}

	static void permutations(int[] idx,int i) {
		perm.add(toString(idx));
		if(i<k-1) permutations(idx,i+1);
		for(int j=i+1;j<k;j++) {
			swap(idx,i,j);
			permutations(idx,i+1);
			swap(idx,j,i);
		}
	}

	static void swap(int idx[],int a, int b) {
		int remp = idx[b];
		idx[b] = idx[a];
		idx[a] = remp;
	}

	public static void main(String[] args) {
        FastScanner in = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);
        n = in.nextInt(); k = in.nextInt();
        char ch[][] = new char[n][k];
        for(int i=0;i<n;i++) {
        	ch[i] = in.next().toCharArray();
        }
        perm = new TreeSet<>();
        int idx[] = new int[k];
        for(int i=1;i<=k;i++) idx[i-1] = i;
        for(int i=0;i<k;i++) {
        	swap(idx,0,i);
        	permutations(idx,0);
        }
        int ans = Integer.MAX_VALUE;
        for(String str : perm) {
        	int max = 0, min =Integer.MAX_VALUE;
        	char c[] = str.toCharArray();
        	for(int i=0;i<n;i++) {
        		int x = 0;
        		for(char y : c) {
        			x = 10*x + (ch[i][(y-'1')]-'0');
        		}
        		min = Math.min(min, x);
        		max = Math.max(max, x);
        	}
        	ans = Math.min(ans, max-min);
        }
        out.println(ans);
        out.flush();
	}

	static class FastScanner {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer("");

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

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

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

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

		Integer[] readArray(long n) {
		    Integer a[] = new Integer[(int)n];
			for(int i=0;i<n;i++) a[i] = nextInt();
			return a;
		}

		long[] readArray(int n,long x) {
			long a[] = new long[n];
			for(int i=0;i<n;i++) a[i] = nextLong();
			return a;
		}

	}

	static class Pair implements Comparable<Pair> {
		int x, y;
		Pair(int a, int b){ x = a; y = b; }
		int getKey() { return x; }
		int getVal() { return y; }
		@Override
		public int compareTo(Pair o) {
			if(o.getVal() - this.getVal()>0)
				return -1;
			else if(o.getVal() - this.getVal()<0)
				return 1;
			else
				return 0;
		}

	}

	static boolean arrayEquals(char a[], char b[]) {
		int n = a.length;
		boolean verdict = true;
		for(int i=0;i<n;i++) {
			if(a[i]!=b[i]) {
				verdict = false;break;
			}
		}
		return verdict;
	}

	static long lcm(long a, long b) {
		return (a*b)/gcd(a,b);
	}

	static long gcd(long a, long b) {
		if(b==0) return a;
		else return gcd(b,a%b);
	}

	static long hashInt(int x,int y) {
		return x*(1_000_000_000L)+y;
	}
}

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

public class Permutation {

	static HashSet<String> perm;
	static int n,k;

	static void permutations(char[] idx,int i) {
		perm.add(new String(idx));
		if(i<k-1) permutations(idx,i+1);
		for(int j=i+1;j<k;j++) {
			swap(idx,i,j);
			permutations(idx,i+1);
			swap(idx,j,i);
		}
	}

	static void swap(char idx[],int a, int b) {
		char remp = idx[b];
		idx[b] = idx[a];
		idx[a] = remp;
	}

	public static void main(String[] args) {
        FastScanner in = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);
        n = in.nextInt(); k = in.nextInt();
        char ch[][] = new char[n][k];
        for(int i=0;i<n;i++) {
        	ch[i] = in.next().toCharArray();
        }
        perm = new HashSet<>();
        char idx[] = new char[k];
        int i=0;char a = '1';
        while(i<k) {
        	idx[i] = a;a++;i++;
        }
        for(i=0;i<k;i++) {
        	swap(idx,0,i);
        	permutations(idx,0);
        }
        int ans = Integer.MAX_VALUE;
        for(String str : perm) {
        	int max = 0, min =Integer.MAX_VALUE;
        	char c[] = str.toCharArray();
        	for(i=0;i<n;i++) {
        		int x = 0;
        		for(char y : c) {
        			x = 10*x + (ch[i][(y-'1')]-'0');
        		}
        		min = (min>x)?x:min;
        		max = (max<x)?x:max;
        	}
        	ans = Math.min(ans, max-min);
        }
        out.println(ans);
        out.flush();
	}

	static class FastScanner {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer("");

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

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

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

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

		Integer[] readArray(long n) {
		    Integer a[] = new Integer[(int)n];
			for(int i=0;i<n;i++) a[i] = nextInt();
			return a;
		}

		long[] readArray(int n,long x) {
			long a[] = new long[n];
			for(int i=0;i<n;i++) a[i] = nextLong();
			return a;
		}

	}

	static class Pair implements Comparable<Pair> {
		int x, y;
		Pair(int a, int b){ x = a; y = b; }
		int getKey() { return x; }
		int getVal() { return y; }
		@Override
		public int compareTo(Pair o) {
			if(o.getVal() - this.getVal()>0)
				return -1;
			else if(o.getVal() - this.getVal()<0)
				return 1;
			else
				return 0;
		}

	}

	static boolean arrayEquals(char a[], char b[]) {
		int n = a.length;
		boolean verdict = true;
		for(int i=0;i<n;i++) {
			if(a[i]!=b[i]) {
				verdict = false;break;
			}
		}
		return verdict;
	}

	static long lcm(long a, long b) {
		return (a*b)/gcd(a,b);
	}

	static long gcd(long a, long b) {
		if(b==0) return a;
		else return gcd(b,a%b);
	}

	static long hashInt(int x,int y) {
		return x*(1_000_000_000L)+y;
	}
}

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

public class Permutation {

	static HashSet<String> perm;
	static int n,k;

	static void permutations(char[] idx,int i) {
		perm.add(new String(idx));
		if(i<k-1) permutations(idx,i+1);
		for(int j=i+1;j<k;j++) {
			swap(idx,i,j);
			permutations(idx,i+1);
			swap(idx,j,i);
		}
	}

	static void swap(char idx[],int a, int b) {
		char remp = idx[b];
		idx[b] = idx[a];
		idx[a] = remp;
	}

	public static void main(String[] args) {
        FastScanner in = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);
        n = in.nextInt(); k = in.nextInt();
        char ch[][] = new char[n][k];
        for(int i=0;i<n;i++) {
        	ch[i] = in.next().toCharArray();
        }
        perm = new HashSet<>();
        char idx[] = new char[k];
        int i=0;char a = '1';
        while(i<k) {
        	idx[i] = a;a++;i++;
        }
        for(i=0;i<k;i++) {
        	swap(idx,0,i);
        	permutations(idx,0);
        }
        int ans = Integer.MAX_VALUE;
        for(String str : perm) {
        	int max = 0, min =Integer.MAX_VALUE;
        	char c[] = str.toCharArray();
        	for(i=0;i<n;i++) {
        		int x = 0;
        		for(char y : c) {
        			x = 10*x + (ch[i][(y-'1')]-'0');
        		}
        		min = (min>x)?x:min;
        		max = (max<x)?x:max;
        	}
        	ans = (ans>max-min)?max-min:ans;
        }
        out.println(ans);
        out.flush();
	}

	static class FastScanner {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer("");

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

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

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

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

		Integer[] readArray(long n) {
		    Integer a[] = new Integer[(int)n];
			for(int i=0;i<n;i++) a[i] = nextInt();
			return a;
		}

		long[] readArray(int n,long x) {
			long a[] = new long[n];
			for(int i=0;i<n;i++) a[i] = nextLong();
			return a;
		}

	}

	static class Pair implements Comparable<Pair> {
		int x, y;
		Pair(int a, int b){ x = a; y = b; }
		int getKey() { return x; }
		int getVal() { return y; }
		@Override
		public int compareTo(Pair o) {
			if(o.getVal() - this.getVal()>0)
				return -1;
			else if(o.getVal() - this.getVal()<0)
				return 1;
			else
				return 0;
		}

	}

	static boolean arrayEquals(char a[], char b[]) {
		int n = a.length;
		boolean verdict = true;
		for(int i=0;i<n;i++) {
			if(a[i]!=b[i]) {
				verdict = false;break;
			}
		}
		return verdict;
	}

	static long lcm(long a, long b) {
		return (a*b)/gcd(a,b);
	}

	static long gcd(long a, long b) {
		if(b==0) return a;
		else return gcd(b,a%b);
	}

	static long hashInt(int x,int y) {
		return x*(1_000_000_000L)+y;
	}
}

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

public class Permutation {

	static SortedSet<String> perm;
	static int n,k;

	static void permutations(char[] idx,int i) {
		perm.add(new String(idx));
		if(i<k-1) permutations(idx,i+1);
		for(int j=i+1;j<k;j++) {
			swap(idx,i,j);
			permutations(idx,i+1);
			swap(idx,j,i);
		}
	}

	static void swap(char idx[],int a, int b) {
		char remp = idx[b];
		idx[b] = idx[a];
		idx[a] = remp;
	}

	public static void main(String[] args) {
        FastScanner in = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);
        n = in.nextInt(); k = in.nextInt();
        char ch[][] = new char[n][k];
        for(int i=0;i<n;i++) {
        	ch[i] = in.next().toCharArray();
        }
        perm = new TreeSet<>();
        char idx[] = new char[k];
        int i=0;char a = '1';
        while(i<k) {
        	idx[i] = a;a++;i++;
        }
        for(i=0;i<k;i++) {
        	swap(idx,0,i);
        	permutations(idx,0);
        }
        int ans = Integer.MAX_VALUE;
        for(String str : perm) {
        	int max = 0, min =Integer.MAX_VALUE;
        	char c[] = str.toCharArray();
        	for(i=0;i<n;i++) {
        		int x = 0;
        		for(char y : c) {
        			x = 10*x + (ch[i][(y-'1')]-'0');
        		}
        		min = Math.min(min, x);
        		max = Math.max(max, x);
        	}
        	ans = Math.min(ans, max-min);
        }
        out.println(ans);
        out.flush();
	}

	static class FastScanner {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer("");

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

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

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

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

		Integer[] readArray(long n) {
		    Integer a[] = new Integer[(int)n];
			for(int i=0;i<n;i++) a[i] = nextInt();
			return a;
		}

		long[] readArray(int n,long x) {
			long a[] = new long[n];
			for(int i=0;i<n;i++) a[i] = nextLong();
			return a;
		}

	}

	static class Pair implements Comparable<Pair> {
		int x, y;
		Pair(int a, int b){ x = a; y = b; }
		int getKey() { return x; }
		int getVal() { return y; }
		@Override
		public int compareTo(Pair o) {
			if(o.getVal() - this.getVal()>0)
				return -1;
			else if(o.getVal() - this.getVal()<0)
				return 1;
			else
				return 0;
		}

	}

	static boolean arrayEquals(char a[], char b[]) {
		int n = a.length;
		boolean verdict = true;
		for(int i=0;i<n;i++) {
			if(a[i]!=b[i]) {
				verdict = false;break;
			}
		}
		return verdict;
	}

	static long lcm(long a, long b) {
		return (a*b)/gcd(a,b);
	}

	static long gcd(long a, long b) {
		if(b==0) return a;
		else return gcd(b,a%b);
	}

	static long hashInt(int x,int y) {
		return x*(1_000_000_000L)+y;
	}
}

import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;
import java.util.*;
import java.io.*;

public class Main {

	public static void main(String[] args) throws IOException {
		try {
			if (new File("input.txt").exists())
				System.setIn(new FileInputStream("input.txt"));
		} catch (SecurityException e) {
		}
		new Main().run();
	}

	BufferedReader in;
	PrintWriter out;
	StringTokenizer st = new StringTokenizer("");
	int ans = 1000000000;
	int[][] grid;
	int n, k;
	int[] num;

	private void run() throws IOException {
		in = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);

		n = nextInt();
		k = nextInt();
		num = new int[k];
		fill(num, -1);
		grid = new int[n][k];
		for (int i = 0; i < n; i++) {
			char[] s = nextLine().toCharArray();
			for (int j = 0; j < k; j++)
				grid[i][j] = (int)(s[j] - '0');
		}
		rec(0);
		out.println(ans);

		in.close();
		out.close();
	}

	void rec(int step) {
		if (step == k) {
			int[] numbers = new int[n];
			for (int i = 0; i < k; i++) {
				int ind = -1;
				for (int j = 0; j < k; j++)
					if (num[j] == i) {
						ind = j;
						break;
					}
				for (int j = 0; j < n; j++)
					numbers[j] = numbers[j] * 10 + grid[j][ind];
			}
			sort(numbers);
			ans = min(ans, numbers[n - 1] - numbers[0]);
		} else {
			for (int i = 0; i < k; i++)
				if (num[i] == -1) {
					num[i] = step;
					rec(step + 1);
					num[i] = -1;
				}
		}
	}

	void chk(boolean b) {
		if (b)
			return;
		System.out.println(new Error().getStackTrace()[1]);
		exit(999);
	}
	void deb(String fmt, Object... args) {
		System.out.printf(Locale.US, fmt + "%n", args);
	}
	String nextToken() throws IOException {
		while (!st.hasMoreTokens())
			st = new StringTokenizer(in.readLine());
		return st.nextToken();
	}
	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}
	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}
	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}
	String nextLine() throws IOException {
		st = new StringTokenizer("");
		return in.readLine();
	}
	boolean EOF() throws IOException {
		while (!st.hasMoreTokens()) {
			String s = in.readLine();
			if (s == null)
				return true;
			st = new StringTokenizer(s);
		}
		return false;
	}
}

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.io.PrintWriter;
public class B92 {
	static Scanner in = new Scanner(System.in);
	static PrintWriter w1 = new PrintWriter(System.out, true);

	static int ni() {
		return in.nextInt();
	}

	static String nl() {
		return in.nextLine();
	}

	public static void main(String[] args) {

		n = ni();
		int k = ni();
		nl();
		s = new int[n][k];
		for (int i = 0; i < n; i ++) {
			String t = nl();
			for (int j = 0; j < k; j++) s[i][j] = (int)(t.charAt(j) - '0');
		}
		w = new int[n][k];
		w2 = new int[n];
		M = (int) Math.pow(10, k-1);
		ArrayList<Integer> al = new ArrayList<Integer>();
		for (int i = 1; i <= k; i++) al.add(i);
		//long t1 = System.currentTimeMillis();
		work(new ArrayList<Integer>(), al);
		w1.println(min1);
		//w1.println(System.currentTimeMillis() - t1);
	}

	static int min1 = Integer.MAX_VALUE;
	static int[][] s;
	static int[][] w;
	static int[] w2;
	static int M, n;

	static void work(ArrayList<Integer> al, ArrayList<Integer> up) {
		if (up.isEmpty()) {
			count(make(al));
		//	for (int i : al) w1.print(i);
			//w1.println();
		} else {
			for (int i = 0; i < up.size(); i++) {
				al.add(up.remove(i));
				work(al, up);
			}
		}
		if (al.size() > 0) {
			Integer re = al.remove(al.size()-1);
			int i = 0;
			while ( i < up.size() && re > up.get(i)) i++;
			up.add(i, re);
		}
	}

	static int[] make(ArrayList<Integer> l) {
		int m = M;
		Arrays.fill(w2, 0);
		for (Integer p : l) {
			for (int i = 0; i < n; i++) {
				w2[i] += s[i][p-1]*m;
			}
			m/=10;
		}
	//	w1.println(Arrays.toString(w2));
		return w2;
	}

	static void count(int[] nn) {
		int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
		for (int n : nn) {
			if (n < min) min = n;
			if (n > max) max = n;
		}
		min1 = Math.min(min1, max-min);
	}

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Solution {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] input = br.readLine().split(" ");
		int n =Integer.parseInt(input[0]);
		int k = Integer.parseInt(input[1]);
		int[][] data = new int[n][k];

		for(int i=0;i<n;i++){
			String temp = br.readLine();
			for(int j=0;j<k;j++){
				data[i][j] = temp.charAt(j)-'0';
			}
		}
		int diff = Integer.MAX_VALUE;
		int[] perm = new int[k];
		for(int i=0;i<k;i++){
			perm[i] = ((char) i);
		}
		do{
			int max = Integer.MIN_VALUE;
			int min = Integer.MAX_VALUE;

			for(int i=0;i<n;i++){
				int current = 0;
				for(int j=0;j<k;j++){
					current += (int) (data[i][perm[j]]*Math.pow(10, k-j-1));
				}
				if(current>max){
					max=current;
				}
				if(current<min){
					min = current;
				}

			}
			int temp = max-min;
			if(temp<diff){
				diff=temp;
			}

		}while(next_permutation(perm));

		System.out.println(diff);

	}

	static boolean next_permutation(int[] p) {
		  for (int a = p.length - 2; a >= 0; --a)
		    if (p[a] < p[a + 1])
		      for (int b = p.length - 1;; --b)
		        if (p[b] > p[a]) {
		          int t = p[a];
		          p[a] = p[b];
		          p[b] = t;
		          for (++a, b = p.length - 1; a < b; ++a, --b) {
		            t = p[a];
		            p[a] = p[b];
		            p[b] = t;
		          }
		          return true;
		        }
		  return false;
		}

}

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

    public class Main{
        static class Run implements Runnable{
            //TODO parameters
            final boolean consoleIO = true;
            final String inFile = "input.txt";
            final String outFile = "output.txt";

            int n, k;
            Vector<Integer[]> v;
            Integer[] t;

            void swap(int a, int b) {
                Integer tmp = t[a];
                t[a] = t[b];
                t[b] = tmp;
            }

            void gen(int n) {
                if(n == 1)
                    v.add(t.clone());
                else {
                    for(int i = 0; i < n; ++i) {
                        swap(i, n-1);
                        gen(n-1);
                        swap(i, n-1);
                    }
                }
            }

            String[] dig;

            int get(String s, Integer[] seq) {
                StringBuilder b = new StringBuilder();
                for(int i = 0; i < seq.length; ++i)
                    b.append(s.charAt(seq[i]));

                return Integer.valueOf(b.toString());
            }

            Pair<Integer,Integer> dif(Integer[] seq) {
                int min = Integer.MAX_VALUE;
                int max = Integer.MIN_VALUE;

                for(int i = 0; i < dig.length; ++i) {
                    int cur = get(dig[i], seq);
                    if(cur < min)
                        min = cur;

                    if(cur > max)
                        max = cur;
                }

                return new Pair<Integer,Integer>(min, max);
            }

            @Override
            public void run() {
                n = nextInt();
                k = nextInt();
                v = new Vector<Integer[]>();
                t = new Integer[k];

                for(int i = 0; i < k; ++i)
                    t[i] = i;
                gen(k);

                dig = new String[n];
                for(int i = 0; i < n; ++i)
                    dig[i] = nextLine();

                int sz = v.size();
                int min = Integer.MAX_VALUE;

                for(int i = 0; i < sz; ++i) {
                    Pair<Integer,Integer> p = dif(v.get(i));
                    int cur = p.b - p.a;

                    if(cur < min)
                        min = cur;
                }

                print(min);
                close();
            }
        //=========================================================================================================================
            BufferedReader in;
            PrintWriter out;
            StringTokenizer strTok;

            Run() {
                if (consoleIO) {
                    initConsoleIO();
                }
                else {
                    initFileIO();
                }
            }

            void initConsoleIO() {
                in = new BufferedReader(new InputStreamReader(System.in));
                out = new PrintWriter(new OutputStreamWriter(System.out));
            }

            void initFileIO() {
                try {
                    in = new BufferedReader(new FileReader(inFile));
                    out = new PrintWriter(new FileWriter(outFile));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            void close() {
                try {
                    in.close();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

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

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

            float nextFloat() {
                return Float.parseFloat(nextToken());
            }

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

            String nextLine() {
                try {
                    return in.readLine();
                } catch (IOException e) {
                    return "__NULL";
                }
            }

            boolean hasMoreTokens() {
                return (strTok == null) || (strTok.hasMoreTokens());
            }

            String nextToken() {
                while (strTok == null || !strTok.hasMoreTokens()) {
                    String line;
                    try {
                        line = in.readLine();
                        strTok = new StringTokenizer(line);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                return strTok.nextToken();
            }

            void cout(Object o){
                System.out.println(o);
            }

            void print(Object o) {
                out.write(o.toString());
            }

            void println(Object o) {
                out.write(o.toString() + '\n');
            }

            void printf(String format, Object... args) {
                out.printf(format, args);
            }

            String sprintf(String format, Object... args) {
            return MessageFormat.format(format, args);
        }
        }

        static class Pair<A, B> {
            A a;
            B b;

            A f() {
                return a;
            }

            B s() {
                return b;
            }

            Pair(A a, B b) {
                this.a = a;
                this.b = b;
            }

            Pair(Pair<A, B> p) {
                a = p.f();
                b = p.s();
            }
        }

        public static void main(String[] args) throws IOException {
            Run run = new Run();
            Thread thread = new Thread(run);
            thread.run();
        }
    }

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

/**
 * Author -
 * User: kansal
 * Date: 11/3/11
 * Time: 8:38 PM
 */
public class CF92B {
    public static void main(String[] args) {
        reader = new BufferedReader(new InputStreamReader(System.in));

        int n = nextInt(), k = nextInt();
        int[] nums = new int[n];
        f = new int[n][k];
        temp = new int[k];
        temp1 = new int[n];
        for(int i = 0; i < n; ++i) {
            nums[i] = nextInt();
        }

        int[] p = new int[k];
        for(int i = 0; i < k; ++i) {
            p[i] = i;
        }

        int res = 1000000000;
        do {
            res = Math.min(res, calc(nums, k, p));
        } while (next_permutation(p, 0, k));

        System.out.println(res);
    }

    private static int[][] f;
    private static int[] temp;
    private static int[] temp1;
    private static int calc(int[] nums, int k, int[] p) {
        int n = nums.length;
        for(int i = 0; i < n; ++i) {
            int p10 = 1;
            for(int j = 0; j < k; ++j) {
                f[i][j] = nums[i] / p10 % 10;
                p10 *= 10;
            }

            for(int j = 0; j < k; ++j) {
                temp[j] = f[i][p[j]];
            }
            System.arraycopy(temp, 0, f[i], 0, k);

            temp1[i] = 0;
            for(int j = 0; j < k; ++j) {
                temp1[i] = temp1[i] * 10 + temp[j];
            }
        }

        Arrays.sort(temp1);
        return temp1[n-1] - temp1[0];
    }

    public static boolean next_permutation(int[] arr, int beg, int end) {
        if (end - beg <= 1)
            return false;
        int i = end - 1;

        for (; ;) {
            int ii = i;
            --i;
            if (arr[i] < arr[ii]) {
                int j = end;
                while (!(arr[i] < arr[--j])) ;
                int tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
                for (int k = ii, l = end - 1; k < l; ++k, --l) {
                    tmp = arr[k];
                    arr[k] = arr[l];
                    arr[l] = tmp;
                }
                return true;
            }
            if (i == beg) {
                for (int k = beg, l = end - 1; k < l; ++k, --l) {
                    int tmp = arr[k];
                    arr[k] = arr[l];
                    arr[l] = tmp;
                }
                return false;
            }
        }
    }

    public static BufferedReader reader;

    public static StringTokenizer tokenizer = null;

    static String nextToken() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }

    static public int nextInt() {
        return Integer.parseInt(nextToken());
    }

    static public long nextLong() {
        return Long.parseLong(nextToken());
    }

    static public String next() {
        return nextToken();
    }

    static public String nextLine() {
        try {
            return reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

import java.awt.*;
import java.io.*;
import java.math.*;
import java.util.*;
import static java.lang.Math.*;

public class BetaRound92_Div2_B implements Runnable {

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok;

    public static void main(String[] args) {
        new Thread(null, new BetaRound92_Div2_B(), "", 256 * (1L << 20)).start();
    }

    @Override
    public void run() {
        try {
            long startTime = System.currentTimeMillis();
            if (System.getProperty("ONLINE_JUDGE") != null) {
                in = new BufferedReader(new InputStreamReader(System.in));
                out = new PrintWriter(System.out);
            } else {
                in = new BufferedReader(new FileReader("input.txt"));
                out = new PrintWriter("output.txt");
            }
            Locale.setDefault(Locale.US);
            tok = new StringTokenizer("");
            solve();
            in.close();
            out.close();
            long endTime = System.currentTimeMillis();
            System.err.println("Time = " + (endTime - startTime));
            long freeMemory = Runtime.getRuntime().freeMemory();
            long totalMemory = Runtime.getRuntime().totalMemory();
            System.err.println("Memory = " + ((totalMemory - freeMemory) >> 10));
        } catch (Throwable t) {
            t.printStackTrace(System.err);
            System.exit(-1);
        }
    }

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine());
        }
        return tok.nextToken();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }

    /** http://pastebin.com/j0xdUjDn */
    static class Utils {

        private Utils() {}

        public static void mergeSort(int[] a) {
            mergeSort(a, 0, a.length - 1);
        }

        private static final int MAGIC_VALUE = 50;

        private static void mergeSort(int[] a, int leftIndex, int rightIndex) {
            if (leftIndex < rightIndex) {
                if (rightIndex - leftIndex <= MAGIC_VALUE) {
                    insertionSort(a, leftIndex, rightIndex);
                } else {
                    int middleIndex = (leftIndex + rightIndex) / 2;
                    mergeSort(a, leftIndex, middleIndex);
                    mergeSort(a, middleIndex + 1, rightIndex);
                    merge(a, leftIndex, middleIndex, rightIndex);
                }
            }
        }

        private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) {
            int length1 = middleIndex - leftIndex + 1;
            int length2 = rightIndex - middleIndex;
            int[] leftArray = new int[length1];
            int[] rightArray = new int[length2];
            System.arraycopy(a, leftIndex, leftArray, 0, length1);
            System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
            for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
                if (i == length1) {
                    a[k] = rightArray[j++];
                } else if (j == length2) {
                    a[k] = leftArray[i++];
                } else {
                    a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++];
                }
            }
        }

        private static void insertionSort(int[] a, int leftIndex, int rightIndex) {
            for (int i = leftIndex + 1; i <= rightIndex; i++) {
                int current = a[i];
                int j = i - 1;
                while (j >= leftIndex && a[j] > current) {
                    a[j + 1] = a[j];
                    j--;
                }
                a[j + 1] = current;
            }
        }

    }

    // solution

    int n, k;
    int[] p;
    int[][] a;
    int best = Integer.MAX_VALUE;
    int[] rp;

    boolean less(int[] a, int[] b) {
        for (int i = 0; i < k; i++) {
            if (a[rp[i]] < b[rp[i]]) return true;
            if (a[rp[i]] > b[rp[i]]) return false;
        }
        return false;
    }

    boolean greater(int[] a, int[] b) {
        for (int i = 0; i < k; i++) {
            if (a[rp[i]] > b[rp[i]]) return true;
            if (a[rp[i]] < b[rp[i]]) return false;
        }
        return false;
    }

    int get(int[] a) {
        int res = 0;
        int p = 1;
        for (int i = 0; i < k; i++) {
            res += p * a[rp[k - i - 1]];
            p *= 10;
        }
        return res;
    }

    void update() {
        int minI = -1, maxI = -1;
        for (int i = 0; i < n; i++) {
            if (minI == -1 || less(a[i], a[minI])) {
                minI = i;
            }
            if (maxI == -1 || greater(a[i], a[maxI])) {
                maxI = i;
            }
        }
        int x = get(a[minI]), y = get(a[maxI]);
        best = min(best, abs(x - y));
    }

    void swap(int i, int j) {
        int t = p[i];
        p[i] = p[j];
        p[j] = t;
    }

    void gen(int L, int R) {
        if (L == R) {
            for (int i = 0; i < k; i++) {
                rp[p[i]] = i;
            }
            update();
        } else {
            for (int i = L; i <= R; i++) {
                swap(i, L);
                gen(L + 1, R);
                swap(i, L);
            }
        }
    }

    void solve() throws IOException {
        n = readInt();
        k = readInt();
        p = new int[k];
        a = new int[n][k];
        for (int i = 0; i < n; i++) {
            String s = readString();
            for (int j = 0; j < k; j++) {
                a[i][j] = s.charAt(j) - '0';
            }
        }
        for (int i = 0; i < k; i++) {
            p[i] = i;
        }
        rp = new int[k];
        gen(0, k-1);
        out.print(best);
    }

}

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.Locale;

public class Main {

    static void nextp(int[] a) {
        int i,j;
        int n = a.length;
        for (i=n-1;i>0;--i) {
            if (a[i]>a[i-1]) {
                for (j=n-1;j>i;--j)
                    if (a[j]>a[i-1]) break;

                int tmp = a[i-1]; a[i-1] = a[j]; a[j] = tmp; // swap

                break;
            }
        }
        for(j=n-1;j>i;--j,++i) {
            int tmp = a[i]; a[i] = a[j]; a[j] = tmp; // swap
        }
    }

    public static void main(String[] args)throws Exception {
        String[] s = inB.readLine().split(" ");
        int n = Integer.parseInt(s[0]);
        int k = Integer.parseInt(s[1]);

        int[][] c = new int[n][k];

        for(int i = 0; i<n; i++) {
            char[] cc = inB.readLine().toCharArray();
            for(int j = 0; j<k; j++) {
                c[i][j] = cc[j] - '0';
            }
        }

        int[] pt = new int[k];
        for(int i = 0; i<k; i++)pt[i] = i+1;

        int fact = 1;
        for(int i = 1; i<=k; i++)fact *= i;

        int min = INF;
        for(int i = 0; i<fact; i++, nextp(pt)) {
            int[] curmas = new int[n];
            for(int j = 0; j<n; j++) {
                for(int ii = 0, dec=1; ii<k; ii++, dec *= 10) {
                    curmas[j] += c[j][pt[ii]-1]*dec;
                }
            }
            Arrays.sort(curmas);
            if(curmas[n-1] - curmas[0] < min)
                min = curmas[n-1] - curmas[0];

        }

        println(min);
        //out.flush();
    }

    /////////////////////////////////////////////////////////////////
    // IO
    /////////////////////////////////////////////////////////////////
    private static StreamTokenizer in;
    private static PrintWriter out;
    private static BufferedReader inB;

    private static boolean FILE=false;

    private static int nextInt() throws Exception{
        in.nextToken();
        return (int)in.nval;
    }

    private static String nextString() throws Exception{
        in.nextToken();
        return in.sval;
    }

    static{
        try {
            out = new PrintWriter(FILE ? (new FileOutputStream("output.txt")) : System.out);
            inB = new BufferedReader(new InputStreamReader(FILE ? new FileInputStream("input.txt") : System.in));
        } catch(Exception e) {e.printStackTrace();}
        in = new StreamTokenizer(inB);
    }
    /////////////////////////////////////////////////////////////////

    /////////////////////////////////////////////////////////////////
    // pre - written
    /////////////////////////////////////////////////////////////////
    private static void println(Object o) throws Exception {
        out.println(o);
        out.flush();
    }
    private static void exit(Object o) throws Exception {
        println(o);
        exit();
    }
    private static void exit() {
        System.exit(0);
    }
    private static final int  INF = Integer.MAX_VALUE;
    private static final int MINF = Integer.MIN_VALUE;
    //////////////////////////////////////////////////////////////////
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Permutations {
	public static int result = Integer.MAX_VALUE;
	public static String[] list;
	public static int[] track;
	public static boolean[] check;
	public static int n;
	public static int m;

    public static void main(String[] args) throws IOException {
        BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(f.readLine());
        n = Integer.parseInt(st.nextToken());
        m = Integer.parseInt(st.nextToken());
		list = new String[n];
		int a = 0;
		for (int i = 0; i < n; i++) {
			list[i] = f.readLine();
		}
		track = new int[m];
		check = new boolean[m];
		recurse(a);
		System.out.println(result);
	}

	public static void recurse(int a) {
		if (m == a) {
			int max = 0;
			int min = Integer.MAX_VALUE;
			for (int i = 0; i < n; i++) {
				String str = "";
				String finish = list[i];
				for (int j = 0; j < m; j++) {
					str += finish.charAt(track[j]);
				}
				int look = Integer.parseInt(str);
				if (min > look) {
					min = look;
				}
				if (max < look) {
					max = look;
				}

			}
			if (result > max-min) {
				result = max-min;
			}
		}
		for (int i = 0; i < m; i++) {
			if (!check[i]) {
				check[i] = true;
				track[a] = i;
				recurse(a+1);
				check[i] = false;

			}
		}
	}

}

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

public class B {

    static int[] perm;
    static int[][] a;
    static int n, k;

    static int best_diff;

    public static int eval(int row) {
	int t = 0;
	for (int j=0; j<k; j++) {
	    t = t*10;
	    t += a[row][perm[j]];
	}
	return t;
    }

    public static void update_diff() {
	int max, min;
	max = min = eval(0);
	for (int i=1; i<n; i++) {
	    int e = eval(i);
	    max = Math.max(max, e);
	    min = Math.min(min, e);
	}
	if (max-min < best_diff) best_diff = max-min;
    }

    public static void swap (int i, int j) {
	int t = perm[i];
	perm[i] = perm[j];
	perm[j] = t;
    }

    public static void gen_perm (int i) {
	if (i==k) {
	    update_diff();
	    return;
	};
	for (int j=i; j<k; j++) {
	    swap(i,j);
	    gen_perm(i+1);
	    swap(i,j);
	}
    }

    public static void main(String[] args) throws Exception {
	Scanner sc = new Scanner(System.in);
	n = sc.nextInt();
	k = sc.nextInt();
	perm = new int[k];
	for (int i=0; i<k; i++) perm[i] = i;

	a = new int[n][k];
	for (int i=0; i<n; i++) {
	    int b = sc.nextInt();
	    for (int j=k-1; j>=0; j--) {
		a[i][j] = b % 10;
		b = b/10;
	    }
	}
	best_diff = 1000000000;
	gen_perm(0);
	System.out.println(best_diff);
    }
}

import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Task {

	private static final boolean readFromFile = false;

	public static void main(String args[]){
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		FileOutputStream fileOutputStream;
		FileInputStream fileInputStream;
		if (readFromFile){
			try{
				fileInputStream = new FileInputStream(new File("input.txt"));
				fileOutputStream = new FileOutputStream(new File("output.txt"));
			}catch (FileNotFoundException e){
				throw new RuntimeException(e);
			}
		}
		PrintWriter out = new PrintWriter((readFromFile)?fileOutputStream:outputStream);
		InputReader in = new InputReader((readFromFile)?fileInputStream:inputStream);

		Solver s = new Solver(in,out);
		s.solve();

		out.close();
	}
}

class Solver{
	InputReader in;
	PrintWriter out;

	int perm[];
	char a[][],b[][];
	int n,k,ans;
	boolean us[];

	void build(){
		b = new char[n][k];
		for (int i=0;i<n;i++)
			for (int j=0;j<k;j++)
				b[i][j]=a[i][perm[j]];
	}

	void check(){
		int m[] = new int[n];
		for (int i=0;i<n;i++)
			m[i]=Integer.parseInt(new String(b[i]));
		int maxValue = 0,
			minValue = Integer.MAX_VALUE;
		for (int i=0;i<n;i++){
			maxValue = Math.max(maxValue, m[i]);
			minValue = Math.min(minValue, m[i]);
		}
		ans = Math.min(ans, maxValue-minValue);
	}

	void dfs(int v){
		if (v==k){
			build();
			check();
			return;
		}
		for (int i=0;i<k;i++)
			if (!us[i]){
				us[i]=true;
				perm[v]=i;
				dfs(v+1);
				us[i]=false;
			}
	}

	public void solve(){
		n = in.nextInt();
		k = in.nextInt();
		a = new char[n][k];
		for (int i=0;i<n;i++){
			String temp = in.nextLine();
			a[i] = temp.toCharArray();
		}

		perm = new int[k];
		us = new boolean[k];
		ans = Integer.MAX_VALUE;
		dfs(0);

		out.println(ans);
	}

	Solver(InputReader in, PrintWriter out){
		this.in=in;
		this.out=out;
	}
}

class InputReader{
	private BufferedReader buf;
	private StringTokenizer tok;

	InputReader(InputStream in){
		tok = null;
		buf = new BufferedReader(new InputStreamReader(in));
	}

	InputReader(FileInputStream in){
		tok = null;
		buf = new BufferedReader(new InputStreamReader(in));
	}

	public String next(){
		while (tok==null || !tok.hasMoreTokens()){
			try{
				tok = new StringTokenizer(buf.readLine());
			}catch (IOException e){
				throw new RuntimeException(e);
			}
		}
		return tok.nextToken();
	}

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

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

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

	public float nextFloat(){
		return Float.parseFloat(next());
	}

	public String nextLine(){
		try{
			return buf.readLine();
		}catch (IOException e){
			return null;
		}
	}

}

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Solution124B {
    public static void main(String... bob) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        // BufferedReader in = new BufferedReader(new FileReader("Solution124B"));
        StringTokenizer testCases = new StringTokenizer(in.readLine());
        int N = i(testCases.nextToken()), K = i(testCases.nextToken());
        String[] nums = new String[N];
        for (int i = 0; i < N; i++) {
            nums[i] = in.readLine();
        }
        int[] rule = new int[K];
        int ans = solve (0, new boolean[K], rule, nums);
        System.out.println(ans);
    }

    public static int solve (int index, boolean[] used, int[] rule, String[] nums) {
        if (index == rule.length) {
            int min = Integer.MAX_VALUE;
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < nums.length; i++) {
                StringBuilder str = new StringBuilder();
                for (int j = 0; j < rule.length; j++) {
                    str.append(nums[i].charAt(rule[j]));
                }
                int ans = Integer.parseInt(str.toString());
                min = Math.min(min, ans);
                max = Math.max(max, ans);
            }
            return max - min;
        }
        int ans = Integer.MAX_VALUE;
        for (int i = 0; i < rule.length; i++) {
            if (!used[i]) {
                rule[index] = i;
                used[i] = true;
                ans = Math.min(ans, solve(index + 1, used, rule, nums));
                used[i] = false;
            }
        }
        return ans;
    }

    public static int i(String str) {
        return Integer.parseInt(str);
    }
}

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;

public class Main
{
	private int n;
	private int k;
	private char[][] map;
	private int[] a;
	private boolean[] vis;
	private int minDiff;

	public int getDiff(int[] a)
	{
		int maxNum = Integer.MIN_VALUE;
		int minNum = Integer.MAX_VALUE;
		for(int i = 0;i < n;++i)
		{
			int num = 0;
			for(int j = 0;j < k;++j)
			{
				num = 10 * num + map[i][a[j]] - '0';
			}
			maxNum = Math.max(maxNum, num);
			minNum = Math.min(minNum, num);
		}
		return maxNum - minNum;
	}

	public void dfs(int step, int k)
	{
		if(step >= k)
		{
			minDiff = Math.min(minDiff, getDiff(a));
			return;
		}
		for(int i = 0;i < k;++i)
		{
			if(!vis[i])
			{
				a[step] = i;
				vis[i] = true;
				dfs(step + 1, k);
				vis[i] = false;
			}
		}
	}

	public void foo()
	{
		MyScanner scan = new MyScanner();
		n = scan.nextInt();
		k = scan.nextInt();
		map = new char[n][];
		for(int i = 0;i < n;++i)
		{
			map[i] = scan.next().toCharArray();
		}
		vis = new boolean[k];
		a = new int[k];
		minDiff = Integer.MAX_VALUE;
		dfs(0, k);
		System.out.println(minDiff);
	}

	public static void main(String[] args)
	{
		new Main().foo();
	}

	class MyScanner
	{
	    private byte[] buf = new byte[1024];
	    private int curChar;
	    private int numChars;
	    BufferedInputStream bis = new BufferedInputStream(System.in);

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

	    public int nextInt()
	    {
	        int c = read();
	        while (isSpaceChar(c))
	        {
	        	c = read();
	        }
	        int sgn = 1;
	        if (c == '-')
	        {
	            sgn = -1;
	            c = read();
	        }
	        int res = 0;
	        do
	        {
	            if (c < '0' || c > '9')
	            {
	            	throw new InputMismatchException();
	            }
	            res *= 10;
	            res += c - '0';
	            c = read();
	        } while (!isSpaceChar(c));
	        return res * sgn;
	    }

	    public long nextLong()
	    {
	    	int c = read();
	    	while (isSpaceChar(c))
	    	{
	    		c = read();
	    	}
	    	int sgn = 1;
	    	if (c == '-')
	    	{
	    		sgn = -1;
	    		c = read();
	    	}
	    	long res = 0;
	    	do
	    	{
	    		if (c < '0' || c > '9')
	    		{
	    			throw new InputMismatchException();
	    		}
	    		res *= 10;
	    		res += c - '0';
	    		c = read();
	    	} while (!isSpaceChar(c));
	    	return res * sgn;
	    }

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

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

import java.util.*;
import java.io.*;
public class pt{

          static int min=999999999;
          static void permute(int a[],int pos,int n,int num[][]){

                           if(pos==(n-1)){
                                     int arr[] = new int[num.length];
                                     for(int i=0;i<num.length;i++){
                                         int x=0;
                                        for(int j=0;j<n;j++)
                                               x = x*10+num[i][a[j]];
                                        arr[i]=x;
                                     }
                                  Arrays.sort(arr);
                                  if(min>Math.abs(arr[0]-arr[num.length-1]))
                                     min = Math.abs(arr[0]-arr[num.length-1]);
                                  return;
                            }
                          for(int i=pos;i<n;i++){
                               int t = a[pos];
                                  a[pos]=a[i];
                                  a[i]=t;
                                permute(a,pos+1,n,num);
                                  t = a[pos];
                                  a[pos]=a[i];
                                  a[i]=t;
                         }
                   }

          public static void main(String[] args){
          PrintWriter out = new PrintWriter(System.out);

              int n = ni();
              int k = ni();

              int num[][] = new int[n][k];
              int a[] = new int[k];

                for(int i=0;i<n;i++){
                     int t = ni();
                     int x = k-1;
                     while(t>0){
                            num[i][x--]=t%10;
                            t = t/10;
                    }
               }
               for(int i=0;i<k;i++)
                   a[i]=i;
                permute(a,0,k,num);
               out.println(min);
               out.flush();
    }

       static FastReader sc=new FastReader();

      static int ni(){
                 int x = sc.nextInt();
                 return(x);
        }
      static long nl(){
              long x = sc.nextLong();
              return(x);
         }
      static String n(){
                 String str = sc.next();
                     return(str);
       }
     static String ns(){
                 String str = sc.nextLine();
                   return(str);
      }
     static double nd(){
               double d = sc.nextDouble();
                 return(d);
       }
  static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

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

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

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

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

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

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

import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;

/**
 * 124B
 * θ(n!*n^2 + n*k) time
 * θ(n*k) space
 *
 * @author artyom
 */
public class _124B implements Runnable {
    private BufferedReader in;
    private StringTokenizer tok;
    private Node head;
    private int n, best = Integer.MAX_VALUE;
    private int[][] ds;

    private Object solve() throws IOException {
        n = nextInt();
        int k = nextInt();
        ds = new int[n][k];
        for (int i = 0; i < n; i++) {
            String s = nextToken();
            for (int j = 0; j < k; j++) {
                ds[i][j] = s.charAt(j) - 48;
            }
        }
        Node seq = null;
        for (int i = k - 1; i >= 0; i--) {
            seq = new Node(i, seq);
        }
        genPerm(seq, head = new Node(-1));
        return best;
    }

    private void genPerm(Node node, Node perm) {
        if (node == null) {
            int[] arr = new int[n];
            for (Node y = head.next; y != null; y = y.next) {
                for (int i = 0; i < n; i++) {
                    arr[i] = arr[i] * 10 + ds[i][y.val];
                }
            }
            int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
            for (int i = 0; i < n; i++) {
                min = Math.min(min, arr[i]);
                max = Math.max(max, arr[i]);
            }
            best = Math.min(max - min, best);
            return;
        }
        Node h = node;
        Node x = node.next;
        node.next = null;
        perm.next = node;
        genPerm(x, perm.next);
        node.next = x;

        while (x != null) {
            node.next = x.next;
            perm.next = x;
            x.next = null;
            genPerm(h, perm.next);
            x.next = node.next;
            node.next = x;
            node = x;
            x = node.next;
        }
    }

    //--------------------------------------------------------------
    public static void main(String[] args) {
        new _124B().run();
    }

    @Override
    public void run() {
        try {
            in = new BufferedReader(new InputStreamReader(System.in));
            tok = null;
            System.out.print(solve());
            in.close();
        } catch (IOException e) {
            System.exit(0);
        }
    }

    private String nextToken() throws IOException {
        while (tok == null || !tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine());
        }
        return tok.nextToken();
    }

    private int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    private static final class Node {
        private final int val;
        private Node next;

        private Node(int val) {
            this(val, null);
        }

        private Node(int val, Node next) {
            this.val = val;
            this.next = next;
        }
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Permutations124B {

	static char [] c;
	static ArrayList<ArrayList<String>> e;
	static int idx;

	public static void swap(int s, int e) {
		char temp = c[s];
		c[s] = c[e];
		c[e] = temp;
	}

	public static void nextPermutation(int s) {

		if (s == c.length) {
			if(e.size() > idx && e.get(idx) != null){
				e.get(idx).add(new String(c));
				idx++;
				return;
			}
			ArrayList<String> temp = new ArrayList<>();
			temp.add(new String(c));
			e.add(temp);
			idx++;
			return;
		}

		for (int j = s; j < c.length; j++) { // swaping
			swap(s, j);
			nextPermutation(s + 1);
			swap(s, j);

		}
	}

	public static void main(String[] args) throws IOException {
		MyScanner sc = new MyScanner(System.in);
		PrintWriter pw = new PrintWriter(System.out);
		int n = sc.nextInt();
		int k = sc.nextInt();
		String [] s = new String[n];
		e = new ArrayList<>();
		for(int i = 0;i < n;i++){
			s[i] = sc.nextLine();
			c = s[i].toCharArray();
			idx = 0;
			nextPermutation(0);
		}
		int ans = (int)1e9;
		for(int i = 0;i < e.size();i++){
			int min = (int)1e9;
			int max = (int)-1e9;
			for(int j = 0;j < e.get(i).size();j++){
				min = Math.min(min, Integer.parseInt(e.get(i).get(j)));
				max = Math.max(max, Integer.parseInt(e.get(i).get(j)));

			}
			ans = Math.min(ans, max - min);
		}
		pw.println(ans);
		pw.close();
	}

	static class MyScanner {
		StringTokenizer st;
		BufferedReader br;

		public MyScanner(InputStream s) {
			br = new BufferedReader(new InputStreamReader(s));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

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

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

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public double nextDouble() throws IOException {
			String x = next();
			StringBuilder sb = new StringBuilder("0");
			double res = 0, f = 1;
			boolean dec = false, neg = false;
			int start = 0;
			if (x.charAt(0) == '-') {
				neg = true;
				start++;
			}
			for (int i = start; i < x.length(); i++)
				if (x.charAt(i) == '.') {
					res = Long.parseLong(sb.toString());
					sb = new StringBuilder("0");
					dec = true;
				} else {
					sb.append(x.charAt(i));
					if (dec)
						f *= 10;
				}
			res += Long.parseLong(sb.toString()) / f;
			return res * (neg ? -1 : 1);
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

	}
}

//package com.company;

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

public class Main {
static int n,k,Min = Integer.MAX_VALUE;
static String permutes ="";
static String []digits  = new String[8];
    public static void main(String[] args) throws IOException {
	// write your code here
        // i have use permuation on the size index betwwene 0-k
        //reanggare them by the way
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw= new PrintWriter(new OutputStreamWriter(System.out));
        StringTokenizer st= new StringTokenizer(br.readLine());
        n = Integer.parseInt(st.nextToken());
        k = Integer.parseInt(st.nextToken());
        for (int i=0;i<k;i++)
            permutes+=i;
        for (int i=0;i<n;i++)
            digits[i] = br.readLine();
        permutation("",permutes);
     pw.write(Min+"\n");
     pw.flush();
    }

    private static void permutation(String prefix, String str) {
        int n = str.length();
        if (n == 0) sameRule(prefix);
        else {
            for (int i = 0; i < n; i++)
                permutation(prefix + str.charAt(i),
                        str.substring(0, i) + str.substring(i+1, n));
        }
    }

    private static void sameRule(String prefix) {
      //  System.out.println(prefix);
        int [] arrayOfPermutes  = new int[n];
        for (int i=0;i<n;i++){
            String element = "";
            for (int j=0;j<k;j++)
            {

                int index = Integer.parseInt(""+prefix.charAt(j));
                element+=digits[i].charAt(index);
            }
            arrayOfPermutes[i] = Integer.parseInt(element);
        }
        int min = Integer.MAX_VALUE;
        int Max = Integer.MIN_VALUE;
        for (int i=0;i<n;i++){
            min = Math.min(min,arrayOfPermutes[i]);
            Max = Math.max(Max,arrayOfPermutes[i]);
            }
        Min = Math.min(Math.abs(Max-min),Min);
    }
}

import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author lpeter83
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		Task solver = new Task();
		solver.solve(1, in, out);
		out.close();
	}
}

class Task {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int n = in.nextInt();
        int k = in.nextInt();
        int[] a = new int[k];
        for (int i = 0; i < k; i++) {
            a[i] = i;
        }
        char[][] t = new char[n][k];
        for (int i = 0; i < n; i++) {
            t[i] = in.next().toCharArray();
        }
        int dif = Integer.MAX_VALUE;
        do {
            int[] b = new int[n];
            for (int i = 0; i < n; i++) {
                int s = 0;
                for (int j = 0; j < k; j++) {
                    s = 10 * s + t[i][a[j]] - '0';
                }
                b[i] = s;
            }
            int ma = ArraysUtils.max(b);
            int mi = ArraysUtils.min(b);
            dif = Math.min(dif, ma - mi);

        } while (ArraysUtils.nextPermutation(a));
        out.printLine(dif);
    }
}

class InputReader {
    BufferedReader reader;
    StringTokenizer tokenizer;

    public InputReader(InputStream stream) {
        reader = new BufferedReader(new InputStreamReader(stream));
        tokenizer = null;
    }

    public String next() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }

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

	}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(outputStream);
    }

    public OutputWriter(Writer writer) {
        this.writer = new PrintWriter(writer);
    }

    public void print(Object... objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0)
                writer.print(' ');
            writer.print(objects[i]);
        }
    }

    public void printLine(Object... objects) {
        print(objects);
        writer.println();
    }

    public void close() {
        writer.close();
    }
}

class ArraysUtils {

    public static boolean nextPermutation(int[] a) {
        int N = a.length;
        int i = N - 2;
        for (; i >= 0; i--)
            if (a[i] < a[i + 1])
                break;
        if (i < 0) return false;

        for (int j = N - 1; j >= i; j--) {
            if (a[j] > a[i]) {
                int temp = a[i];
                a[i] = a[j];
                a[j] = temp;
                break;
            }
        }
        for (int j = i + 1; j < (N + i + 1) / 2; j++)        //reverse from a[i+1] to a[N-1]
        {
            int temp = a[j];
            a[j] = a[N + i - j];
            a[N + i - j] = temp;
        }
        return true;
    }

    public static int max(int[] a){
        int res = Integer.MIN_VALUE;
        for(int t: a) {
            if (res < t) res = t;
        }
        return res;
    }

    public static int min(int[] a){
        int res = Integer.MAX_VALUE;
        for(int t: a) {
            if (res > t) res = t;
        }
        return res;
    }

    }

import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
import java.text.*;
public class Prac{
    static class InputReader {
        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar, snumChars;
        public InputReader(InputStream st) {
            this.stream = st;
        }
        public int read() {
            if (snumChars == -1)
                throw new InputMismatchException();
            if (curChar >= snumChars) {
                curChar = 0;
                try {
                    snumChars = stream.read(buf);
                }
                catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (snumChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }
        public int ni() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }
        public long nl() {
            int c = read();
            while (isSpaceChar(c)) {
            c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }
        public int[] nia(int n) {
            int a[] = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = ni();
            }
            return a;
        }
        public String rs() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                    c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }
        public String nextLine() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isEndOfLine(c));
            return res.toString();
        }
        public boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

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

        private final int x;
        private final int y;

        public Key(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Key)) return false;
            Key key = (Key) o;
            return x == key.x && y == key.y;
        }

        @Override
        public int hashCode() {
            int result = x;
            result = 31 * result + y;
            return result;
        }

    }

    static PrintWriter w = new PrintWriter(System.out);
    static long mod=998244353L,mod1=1000000007;
    static int co[][];
    static void dsort(){
        Arrays.parallelSort(co,(o1,o2)->o1[0]!=o2[0]?o1[0]-o2[0]:o1[1]-o2[1]);
    }
     static long  power(long x, long y) {
        long temp=0;
        if( y == 0)
            return 1;
        temp = power(x, y/2);
        if (y%2 == 0)
            return (temp*temp)%mod1;
        else
            return (((x*temp)%mod1)*temp)%mod1;
    }
    static long modInverse(long a, long m){
        long num=m;
        long x=1;
        long power=a%mod1;
        while(num>0){
              if(num%2==1){
                  x=(x*power)%mod1;
            }
            num>>=1;
            power=(power*power)%mod1;
        }
        return x;
    }
    static long ncr(int n,int r){
        if(n<r)return 0L;
        long ans=fact[n]/(fact[r]*fact[n-r]);
        return ans;
    }
    static long fact[]=new long[1000005];
    public static void findFact(){
        fact[0]=1;
        for(int i=1;i<=1000000;i++){
            fact[i]=(i*fact[i-1])%mod1;
        }
    }
    static long nCr(int n,int r){
        if(n<r)return 0L;

        return (fact[n]*modInverse((fact[r]*fact[n-r])%mod1,mod1-2))%mod1;
    }
    static Set<String> set = new HashSet<>();

    // Recursive function to generate
    // permutations of the string
    static void Permutation(String str, String ans)
    {

        // If string is empty
        if (str.length() == 0) {

            // Add the generated permutation to the
            // set in order to avoid duplicates
            set.add(ans);
            return;
        }

        for (int i = 0; i < str.length(); i++) {

            // ith character of str
            char ch = str.charAt(i);

            // Rest of the string after excluding
            // the ith character
            String ros = str.substring(0, i)
                         + str.substring(i + 1);

            // Recurvise call
            Permutation(ros, ans + ch);
        }
    }
    public static void main (String[] args)throws IOException{
        InputReader sc=new InputReader(System.in);
        //findFact();
        int n=sc.ni(),k=sc.ni();
        String p="";
        for(int i=1;i<=k;i++){
            p=p+Integer.toString(i);
        }
        Permutation(p,"");
        String s[]=new String[n];
        for(int i=0;i<n;i++){
            s[i]=sc.nextLine();
        }
        int ans=Integer.MAX_VALUE;
        for(String x:set){
            int min=Integer.MAX_VALUE,max=Integer.MIN_VALUE;
            for(int i=0;i<n;i++){
                String te="";
                for(int j=0;j<k;j++){
                    int in=x.charAt(j)-'1';
                    te=te+s[i].charAt(in);
                }
                int num=Integer.parseInt(te);
                min=Math.min(min,num);
                max=Math.max(max,num);
            }
            ans=Math.min(ans,max-min);
        }
        w.println(ans);
        w.close();
    }
}

import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    static int[] res;
    static String[] nums;
    static int ans = Integer.MAX_VALUE;

    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int k = in.nextInt();
        nums = new String[n];
        for (int i = 0; i < n; i++)
            nums[i] = in.next();
        res = new int[k];
        boolean[] v = new boolean[k];
        dfs(0, v);
        System.out.println(ans);
    }

    public static void dfs(int r, boolean[] v) {
        if (r == res.length) {
            int min = Integer.MAX_VALUE;
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < nums.length; i++) {
                min = Math.min(min, num(i));
                max = Math.max(max, num(i));
            }
            ans = Math.min(ans, max - min);
        } else {
            for (int i = 0; i < res.length; i++) {
                if (!v[i]) {
                    res[r] = i;
                    v[i] = true;
                    dfs(r + 1, v);
                    v[i] = false;
                }
            }
        }
    }

    public static int num(int x) {
        String s = nums[x];
        int ret = 0;
        for (int i = 0; i < res.length; i++) {
            ret *= 10;
            ret += s.charAt(res[i]) - '0';
        }
        return ret;
    }
}

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

public class TaskB {
	BufferedReader br;
	PrintWriter out;
	StringTokenizer stok;

	String nextToken() throws IOException {
		while (stok == null || !stok.hasMoreTokens()) {
			String s = br.readLine();
			if (s == null) {
				return "-1";
			}
			stok = new StringTokenizer(s);
		}
		return stok.nextToken();
	}

	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}

	char nextChar() throws IOException {
		return (char) (br.read());
	}

	String nextLine() throws IOException {
		return br.readLine();
	}

	final int inf = Integer.MAX_VALUE;

	int[][] a;
	int[] id;
	int n, k, ans = inf;
	boolean[] used;

	int num(int v) {
		int res = 0;
		for (int i = 0; i < k; i++) {
			res = res * 10 + a[v][id[i]];
		}
		return res;
	}

	void upd_ans() {
		int max = -inf, min = inf, x;
		for (int i = 0; i < n; i++) {
			x = num(i);
			max = Math.max(max, x);
			min = Math.min(min, x);
		}
		ans = Math.min(ans, max - min);
	}

	void gen(int v) {
		if (v == k) {
			upd_ans();
		}
		for (int i = 0; i < k; i++) {
			if (!used[i]) {
				id[v] = i;
				used[i] = true;
				gen(v + 1);
				used[i] = false;
			}
		}
	}

	void solve() throws IOException {
		n = nextInt();
		k = nextInt();
		a = new int[n][k];
		for (int i = 0; i < n; i++) {
			for (int g = 0; g < k; g++) {
				a[i][g] = (int) (nextChar()) - (int) ('0');
			}
			nextLine();
		}
		id = new int[k];
		used = new boolean[k];
		gen(0);
		out.print(ans);
	}

	void run() throws IOException {
		// br = new BufferedReader(new FileReader("taskb.in"));
		// out = new PrintWriter("taskb.out");
		// br = new BufferedReader(new FileReader("input.txt"));
		// out = new PrintWriter("output.txt");
		br = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		solve();
		br.close();
		out.close();
	}

	public static void main(String[] args) throws IOException {
		// Locale.setDefault(Locale.US);
		new TaskB().run();
	}
}

import java.util.*;
public class HeapAlgo
{
    static String[] b = new String[8];
    static int k;
    static int min = 1000000000;
    //Prints the array
    void printArr(int a[], int n)
    {
        String[] nums = new String[k];
        for (int i=0; i<k; i++)
            nums[i] = "";
        for (int i=0; i<k; i++)
            for(int j=0; j<n ;j++)
                nums[i] += b[i].charAt(a[j]);
        int m1 = -10000;
        int m2 = 1000000000;
        for(int i = 0; i < k; i++)
        {
            m1 = Math.max(Integer.parseInt(nums[i]),m1);
            m2 = Math.min(Integer.parseInt(nums[i]),m2);
        }
        min = Math.min(min, m1-m2);
    }

    //Generating permutation using Heap Algorithm
    void heapPermutation(int a[], int size, int n)
    {
        // if size becomes 1 then prints the obtained
        // permutation
        if (size == 1)
            printArr(a,n);

        for (int i=0; i<size; i++)
        {
            heapPermutation(a, size-1, n);

            // if size is odd, swap first and last
            // element
            if (size % 2 == 1)
            {
                int temp = a[0];
                a[0] = a[size-1];
                a[size-1] = temp;
            }

            // If size is even, swap ith and last
            // element
            else
            {
                int temp = a[i];
                a[i] = a[size-1];
                a[size-1] = temp;
            }
        }
    }
    // Driver code
    public static void main(String args[])
    {
        Scanner s1 = new Scanner(System.in);
        String s = s1.nextLine();
        int n = Integer.parseInt(s.split(" ")[0]);
        k = Integer.parseInt(s.split(" ")[1]);
        for(int i = 0; i < n; i++)
            b[i] = s1.nextLine();
        HeapAlgo obj = new HeapAlgo();
        int[] a = new int[k];
        for(int i = 0; i < k; i++)
            a[i] = i;
        obj.heapPermutation(a, a.length, a.length);
        System.out.println(min);
    }
}

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

public class Solution {
    static Scanner sc;
    static int n, k;
    static String[] a;
    static boolean[] chosen;
    static int[] result;
    static long minGap = Long.MAX_VALUE;

    static void check() {
        long max = Long.MIN_VALUE;
        long min = Long.MAX_VALUE;

        // for (int x : result)
//          System.out.print(x + " ");
//      System.out.println();

        for (int i = 0; i < n; i++) {
            String curNum = "";
            for (int j = 0; j < k; j++) {
                curNum += a[i].charAt(result[j]);
            }
            // System.out.println(curNum);
            max = Math.max(max, Long.parseLong(curNum));
            min = Math.min(min, Long.parseLong(curNum));
        }

        if (max>min) minGap = Math.min(minGap, max-min);
    }

    static void buff(int curIndex) {
        if (curIndex == k) {
            check();
        }
        else {
            for (int i = 0; i < k; i++) {
                if (!chosen[i]) {
                    result[curIndex] = i;
                    chosen[i] = true;
                    buff(curIndex + 1);
                    chosen[i] = false;
                }
            }
        }
    }

    public static void main (String[] args) throws FileNotFoundException {
        //sc = new Scanner(new File("124B.INP"));
        sc = new Scanner(System.in);
        n = sc.nextInt(); k = sc.nextInt();
        sc.nextLine();

        a = new String[n];
        chosen = new boolean[k];
        result = new int[k];

        for (int i = 0; i < n; i++) {
            a[i] = sc.nextLine();
        }
        buff(0);
        System.out.println(minGap);
        sc.close();
    }
}

    /*JOKER*/

import java.util.*;
import java.lang.*;

public class java
{
    static Scanner nhap = new Scanner(System.in);
    static int k, n, res = 1000000000;
    static int [] pos = new int[11];
    static int [][] a = new int[11][11];
    static boolean[] dd = new boolean[11];

    static void check()
    {
        int ma = -1000000000, mi = 1000000000;
        for(int i = 1; i <= n; i++)
        {
            int c = 0;
            for(int j = 1; j <= k; j++)
                c = c*10 + a[i][pos[j]];
            ma = Math.max(c, ma);
            mi = Math.min(c, mi);
        }
        res = Math.min(res, ma  - mi);
    }

    static void Try(int x)
    {
        if(x > k)
        {
            check();
            return;
        }

        for(int i = 1; i <= n; i++)
            if(dd[i] == false)
            {
                dd[i] = true;
                pos[x] = i;
                Try(x+1);
                dd[i] = false;
            }
    }

    public static void main(String[] args)
    {
        n = nhap.nextInt();
        k = nhap.nextInt();
        for(int i = 1; i <= n; i++)
        {
            int c, h = 10;
            c = nhap.nextInt();
            for(int j = k; j >= 1; j--)
            {
                a[i][j] = c%h;
                c = (c-a[i][j]) / h;
            }
        }
        Try(1);
        System.out.println(res);
    }

}

    /*JOKER*/

import java.util.*;
import java.lang.*;

public class java
{
    static Scanner nhap = new Scanner(System.in);
    static int k, n, res = 1000000000;
    static int [] pos = new int[11];
    static int [][] a = new int[11][11];
    static boolean[] dd = new boolean[11];

    static void check()
    {
        int ma = -1000000000, mi = 1000000000;
        for(int i = 1; i <= n; i++)
        {
            int c = 0;
            for(int j = 1; j <= k; j++)
                c = c*10 + a[i][pos[j]];
            ma = Math.max(c, ma);
            mi = Math.min(c, mi);
        }
        res = Math.min(res, ma  - mi);
    }

    static void Try(int x)
    {
        if(x > k)
        {
            check();
            return;
        }
        for(int i = 1; i <= n; i++)
            if(dd[i] == false)
            {
                dd[i] = true;
                pos[x] = i;
                Try(x+1);
                dd[i] = false;
            }
    }

    public static void main(String[] args)
    {
        n = nhap.nextInt();
        k = nhap.nextInt();
        for (int i = 1; i <= n; i++)
        {
            char sc[] = nhap.next().toCharArray();
            for (int j = 1; j <= k; j++) a[i][j] = sc[j - 1] - '0';
        }
        Try(1);
        System.out.println(res);
    }

}

import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import static java.lang.Math.abs;
import static java.lang.Math.exp;
import static java.lang.Math.floor;

public class Main {
    static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int n = scanner.nextInt();
        int k = scanner.nextInt();
        long minimal=100000000;
        String x[]=new String[n];
        String y[]=new String[n];
        scanner.nextLine();
        for (int i=0;i<n;i++){
            x[i]=scanner.nextLine();
        }
        for (;true;){
            for (int u=0;u<n;u++){
                y[u]=reverse(x[u]);
            }
            xj++;
            if (xj==k){
                xi++;
                xj=xi+1;
            }if (xi==k-1){
                break;
            }
            BigInteger min=BigInteger.ZERO;
            BigInteger max=new BigInteger("999999999");
            for (int j=0;j<n;j++){
                BigInteger x1=new BigInteger(y[j]);
                if (min.compareTo(x1)<0) {
                    min=x1;
                }
                if (max.compareTo(x1)>0) {
                    max=x1;
                }
            }
            long temp=max.subtract(min).abs().longValue();
            if (temp<minimal){
                minimal=temp;
            }
        }
        System.out.println(minimal);
    }
    private static int xi=0;
    private static int xj=0;
    public static String reverse(String str) {
        char[] chars = str.toCharArray();
        char tmp=chars[xi];
        chars[xi]=chars[xj];
        chars[xj]=tmp;
        return new String(chars);
    }
}

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

public class Permutation {

	static SortedSet<String> perm;
	static int n,k;

	static String toString(int[] idx) {
		StringBuilder sb = new StringBuilder("");
		for(int i=0;i<k;i++)
			sb.append(""+idx[i]);
		return sb.toString();

	}

	static void permutations(int[] idx,int i) {
		perm.add(toString(idx));
		for(int j=i+1;j<k;j++) {
			swap(idx,i,j);
			permutations(idx,i+1);
			swap(idx,j,i);
		}
	}

	static void swap(int idx[],int a, int b) {
		int remp = idx[b];
		idx[b] = idx[a];
		idx[a] = remp;
	}

	public static void main(String[] args) {
        FastScanner in = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);
        n = in.nextInt(); k = in.nextInt();
        char ch[][] = new char[n][k];
        for(int i=0;i<n;i++) {
        	ch[i] = in.next().toCharArray();
        }
        perm = new TreeSet<>();
        int idx[] = new int[k];
        for(int i=1;i<=k;i++) idx[i-1] = i;
        for(int i=0;i<k;i++) {
        	swap(idx,0,i);
        	permutations(idx,0);
        }
        int ans = Integer.MAX_VALUE;
        for(String str : perm) {
        	int max = 0, min =Integer.MAX_VALUE;
        	char c[] = str.toCharArray();
        	for(int i=0;i<n;i++) {
        		int x = 0;
        		for(char y : c) {
        			x = 10*x + (ch[i][(y-'0')-1]-'0');
        		}
        		min = Math.min(min, x);
        		max = Math.max(max, x);
        	}
        	ans = Math.min(ans, max-min);
        }
        out.println(ans);
        out.flush();
	}

	static class FastScanner {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer("");

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

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

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

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

		Integer[] readArray(long n) {
		    Integer a[] = new Integer[(int)n];
			for(int i=0;i<n;i++) a[i] = nextInt();
			return a;
		}

		long[] readArray(int n,long x) {
			long a[] = new long[n];
			for(int i=0;i<n;i++) a[i] = nextLong();
			return a;
		}

	}

	static class Pair implements Comparable<Pair> {
		int x, y;
		Pair(int a, int b){ x = a; y = b; }
		int getKey() { return x; }
		int getVal() { return y; }
		@Override
		public int compareTo(Pair o) {
			if(o.getVal() - this.getVal()>0)
				return -1;
			else if(o.getVal() - this.getVal()<0)
				return 1;
			else
				return 0;
		}

	}

	static boolean arrayEquals(char a[], char b[]) {
		int n = a.length;
		boolean verdict = true;
		for(int i=0;i<n;i++) {
			if(a[i]!=b[i]) {
				verdict = false;break;
			}
		}
		return verdict;
	}

	static long lcm(long a, long b) {
		return (a*b)/gcd(a,b);
	}

	static long gcd(long a, long b) {
		if(b==0) return a;
		else return gcd(b,a%b);
	}

	static long hashInt(int x,int y) {
		return x*(1_000_000_000L)+y;
	}
}

import java.util.*;

public class Permutations {
  public static void main(String[]args) {
    Scanner input = new Scanner(System.in);
    int n = input.nextInt();
    int k = input.nextInt();
    int[] arr = new int[n];
    for(int i = 0; i < n; i++)
      arr[i] = input.nextInt();
    int dif = Integer.MAX_VALUE;
    List<List<Integer>> perms = perms(k);
    for(List<Integer> i : perms) {
      int[] arrTwo = new int[n];
      for(int j = 0; j < n; j++) {
        arrTwo[j] = mix(i, arr[j], k);
      }
      int min = minArray(arrTwo);
      int max = maxAbsArray(arrTwo);
      dif = Math.min(dif, max-min);
    }
    System.out.println(dif);
  }

  public static int minArray(int[] arr) {
    int min = Integer.MAX_VALUE;
    for(int i = 0; i < arr.length; i++)
      min = Math.min(arr[i], min);
    return min;
  }

  public static int maxAbsArray(int[] arr) {
    int max = Integer.MIN_VALUE;
    for(int i = 0; i < arr.length; i++)
      max = Math.max(Math.abs(arr[i]), max);
    return max;
  }

  public static int mix(List<Integer> perms, int n, int k) {
    String s = n+"";
    if(s.length() < k) {
      for(int i = 0; i < k-1; i++) {
        s = "0"+s;
      }
    }
    if(n==0) {
      s+="0";
    }
    String res = "";
    for(int i = 0; i < perms.size(); i++) {
      res += ""+s.charAt(perms.get(i)-1);
    }
    return Integer.parseInt(res);
  }

  public static List<List<Integer>> perms(int num) {
    List<List<Integer>> res = new ArrayList<>();
    if(num == 1) {
      res.add(new ArrayList<Integer>());
      res.get(0).add(1);
      return res;
    } else {
      List<List<Integer>> r = perms(num-1);
      for(List<Integer> l : r) {
        for(int i = 0; i < num; i++) {
          List<Integer> r2 = new ArrayList<>();
          for(int j : l) {
            r2.add(j);
          }
          r2.add(i, num);
          res.add(r2);
        }
      }
      return res;
    }
  }
}

import java.util.ArrayList;
import java.util.Scanner;
//probB

public class Main {

	public static void main(String[] args)
	{
		Scanner scanner = new Scanner(System.in);
		int numbers = scanner.nextInt();
		scanner.nextInt();
		ArrayList<ArrayList<String>> lists = new ArrayList<ArrayList<String>>();
		for(int i = 0; i < numbers; ++i)
		{
			String num = scanner.next();
			lists.add(permute(new StringBuilder(num),0,num.length(),new ArrayList<String>()));
		}
		int min = Integer.MAX_VALUE;
		for(int n = 0; n < lists.get(0).size(); ++n)
		{
			int tempMin = Integer.MAX_VALUE;
			int tempMax = Integer.MIN_VALUE;
			for(int i = 0; i < numbers; ++i)
			{
				if(Integer.valueOf(lists.get(i).get(n)) > tempMax) tempMax = Integer.valueOf(lists.get(i).get(n));
				if(Integer.valueOf(lists.get(i).get(n)) < tempMin) tempMax = Integer.valueOf(lists.get(i).get(n));
			}
			if(tempMax - tempMin < min) min = tempMax - tempMin;
		}
		System.out.println(min);
	}

	public static void exchange(StringBuilder input, int i, int j)
	{
		String temp = input.substring(i,i+1);
		input.replace(i, i+1, input.substring(j,j+1));
		input.replace(j,j+1,temp);
	}

	public static ArrayList<String> permute(StringBuilder input, int i, int length, ArrayList<String> list)
	{
		if(i == length - 1)
		{
			list.add(input.toString());
			System.out.println(input.toString());
		}
		else
		{
			for(int j = i; j < length; ++j)
			{
				exchange(input, i, j);
				permute(input, i+1,length,list);
				exchange(input,i,j);

			}
		}

		return list;

	}

}

import java.util.ArrayList;
import java.util.Scanner;
//probB

public class Main {

	public static void main(String[] args)
	{
		Scanner scanner = new Scanner(System.in);
		int numbers = scanner.nextInt();
		scanner.nextInt();
		ArrayList<ArrayList<String>> lists = new ArrayList<ArrayList<String>>();
		for(int i = 0; i < numbers; ++i)
		{
			String num = scanner.next();
			lists.add(permute(new StringBuilder(num),0,num.length(),new ArrayList<String>()));
		}
		int min = Integer.MAX_VALUE;
		for(int n = 0; n < lists.get(0).size(); ++n)
		{
			int tempMin = Integer.MAX_VALUE;
			int tempMax = Integer.MIN_VALUE;
			for(int i = 0; i < numbers; ++i)
			{
				if(Integer.valueOf(lists.get(i).get(n)) > tempMax) tempMax = Integer.valueOf(lists.get(i).get(n));
				if(Integer.valueOf(lists.get(i).get(n)) < tempMin) tempMax = Integer.valueOf(lists.get(i).get(n));
			}
			if(tempMax - tempMin < min) min = tempMax - tempMin;
		}
		System.out.println(min);
	}

	public static void exchange(StringBuilder input, int i, int j)
	{
		String temp = input.substring(i,i+1);
		input.replace(i, i+1, input.substring(j,j+1));
		input.replace(j,j+1,temp);
	}

	public static ArrayList<String> permute(StringBuilder input, int i, int length, ArrayList<String> list)
	{
		if(i == length - 1)
		{
			list.add(input.toString());
		}
		else
		{
			for(int j = i; j < length; ++j)
			{
				exchange(input, i, j);
				permute(input, i+1,length,list);
				exchange(input,i,j);

			}
		}

		return list;

	}

}

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

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author lpeter83
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskB {
    int ans = 1 << 30;

    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int n = in.readInt();
        int k = in.readInt();
        int[][] a = new int[n][k];
        int[] order = new int[k];
        for (int i = 0; i < k; i++) {
            order[i] = i;
        }
        String[] b = new String[n];
        for (int i = 0; i < n; i++) {
            b[i] = in.next();
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < k; j++) {
                a[i][j] = b[i].charAt(j) - '0';
            }
        }
        doit(a, k - 1, order);
        out.printLine(ans);
    }

    private void doit(int[][] a, int cur, int[] order) {
        if (cur == 0) return;
        for (int i = 0; i <= cur - 1; i++) {
            int t = order[cur];
            order[cur] = order[i];
            order[i] = t;
            int[] num = new int[a.length];
            for (int j = 0; j < a.length; j++) {
                String s = "";
                for (int j2 = 0; j2 < a[0].length; j2++) {
                    s += a[j][order[j2]];
                }
                num[j] = Integer.parseInt(s);
            }
            int max = -1, min = 1 << 30;
            for (int j = 0; j < a.length; j++) {
                max = Math.max(max, num[j]);
                min = Math.min(min, num[j]);
            }
            ans = Math.min(ans, max - min);
            doit(a, cur - 1, order);
            t = order[cur];
            order[cur] = order[i];
            order[i] = t;
        }
        doit(a, cur - 1, order);
    }
}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

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

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

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

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

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

    public String next() {
        return readString();
    }
}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(outputStream);
    }

    public OutputWriter(Writer writer) {
        this.writer = new PrintWriter(writer);
    }

    public void print(Object... objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0)
                writer.print(' ');
            writer.print(objects[i]);
        }
    }

    public void printLine(Object... objects) {
        print(objects);
        writer.println();
    }

    public void close() {
        writer.close();
    }
}

import java.io.IOException;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author lpeter83
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskB {
    int ans = 1 << 30;

    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int n = in.readInt();
        int k = in.readInt();
        int[][] a = new int[n][k];
        int[] order = new int[k];
        for (int i = 0; i < k; i++) {
            order[i] = i;
        }
        String[] b = new String[n];
        for (int i = 0; i < n; i++) {
            b[i] = in.next();
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < k; j++) {
                a[i][j] = b[i].charAt(j) - '0';
            }
        }
        if (k == 1) {
            int max = -1, min = 1 << 30;
            for (int i = 0; i < n; i++) {
                min = Math.min(min, a[i][0]);
                max = Math.max(max, a[i][0]);
            }
            ans = max - min;
        } else
            doit(a, k - 1, order);
        out.printLine(ans);
    }

    private void doit(int[][] a, int cur, int[] order) {
        if (cur == 0) return;
        for (int i = 0; i < cur; i++) {
            int t = order[cur];
            order[cur] = order[i];
            order[i] = t;
            int[] num = new int[a.length];
            for (int j = 0; j < a.length; j++) {
                String s = "";
                for (int j2 = 0; j2 < a[0].length; j2++) {
                    s += a[j][order[j2]];
                }
                num[j] = Integer.parseInt(s);
            }
            int max = -1, min = 1 << 30;
            for (int j = 0; j < a.length; j++) {
                max = Math.max(max, num[j]);
                min = Math.min(min, num[j]);
            }
            ans = Math.min(ans, max - min);
            doit(a, cur - 1, order);
            t = order[cur];
            order[cur] = order[i];
            order[i] = t;
        }
        doit(a, cur - 1, order);
    }
}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

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

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

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

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

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

    public String next() {
        return readString();
    }
}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(outputStream);
    }

    public OutputWriter(Writer writer) {
        this.writer = new PrintWriter(writer);
    }

    public void print(Object... objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0)
                writer.print(' ');
            writer.print(objects[i]);
        }
    }

    public void printLine(Object... objects) {
        print(objects);
        writer.println();
    }

    public void close() {
        writer.close();
    }
}

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

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author lpeter83
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskB {
    int ans = 1 << 31;

    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int n = in.readInt();
        int k = in.readInt();
        int[][] a = new int[n][k];
        int[] order = new int[k];
        for (int i = 0; i < k; i++) {
            order[i] = i;
        }
        String[] b = new String[n];
        for (int i = 0; i < n; i++) {
            b[i] = in.next();
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < k; j++) {
                a[i][j] = b[i].charAt(j) - '0';
            }
        }
        doit(a, k - 1, order);
        out.printLine(ans);
    }

    private void doit(int[][] a, int cur, int[] order) {
        if (cur == 0) return;
        for (int i = 0; i <= cur - 1; i++) {
            int t = order[cur];
            order[cur] = order[i];
            order[i] = t;
            int[] num = new int[a.length];
            for (int j = 0; j < a.length; j++) {
                String s = "";
                for (int j2 = 0; j2 < a[0].length; j2++) {
                    s += a[j][order[j2]];
                }
                num[j] = Integer.parseInt(s);
            }
            int max = -1, min = 1 << 20;
            for (int j = 0; j < a.length; j++) {
                max = Math.max(max, num[j]);
                min = Math.min(min, num[j]);
            }
            ans = Math.min(ans, max - min);
            doit(a, cur - 1, order);
            t = order[cur];
            order[cur] = order[i];
            order[i] = t;
        }
        doit(a, cur - 1, order);
    }
}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

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

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

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

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

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

    public String next() {
        return readString();
    }
}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(outputStream);
    }

    public OutputWriter(Writer writer) {
        this.writer = new PrintWriter(writer);
    }

    public void print(Object... objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0)
                writer.print(' ');
            writer.print(objects[i]);
        }
    }

    public void printLine(Object... objects) {
        print(objects);
        writer.println();
    }

    public void close() {
        writer.close();
    }
}

import java.io.IOException;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author lpeter83
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskB {
    int ans = 1 << 20;

    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int n = in.readInt();
        int k = in.readInt();
        int[][] a = new int[n][k];
        int[] order = new int[k];
        for (int i = 0; i < k; i++) {
            order[i] = i;
        }
        String[] b = new String[n];
        for (int i = 0; i < n; i++) {
            b[i] = in.next();
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < k; j++) {
                a[i][j] = b[i].charAt(j) - '0';
            }
        }
        doit(a, k-1, order);
        out.printLine(ans);
    }

    private void doit(int[][] a, int cur, int[] order) {
        for (int i = 0; i <= cur - 1; i++) {
            int t = order[cur];
            order[cur] = order[i];
            order[i] = t;
            int[] num = new int[a.length];
            for (int j = 0; j < a.length; j++) {
                String s = "";
                for (int j2 = 0; j2 < a[0].length; j2++) {
                    s += a[j][order[j2]];
                }
                num[j] = Integer.parseInt(s);
            }
            int max = -1, min = 1 << 20;
            for (int j = 0; j < a.length; j++) {
                max = Math.max(max, num[j]);
                min = Math.min(min, num[j]);
            }
            ans = Math.min(ans, max - min);
            doit(a, cur - 1, order);
        }
    }
}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

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

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

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

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

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

    public String next() {
        return readString();
    }
}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(outputStream);
    }

    public OutputWriter(Writer writer) {
        this.writer = new PrintWriter(writer);
    }

    public void print(Object... objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0)
                writer.print(' ');
            writer.print(objects[i]);
        }
    }

    public void printLine(Object... objects) {
        print(objects);
        writer.println();
    }

    public void close() {
        writer.close();
    }
}

import java.io.IOException;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author lpeter83
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskB {
    int ans = 1 << 20;

    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int n = in.readInt();
        int k = in.readInt();
        int[][] a = new int[n][k];
        int[] order = new int[k];
        for (int i = 0; i < k; i++) {
            order[i] = i;
        }
        String[] b = new String[n];
        for (int i = 0; i < n; i++) {
            b[i] = in.next();
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < k; j++) {
                a[i][j] = b[i].charAt(j) - '0';
            }
        }
        doit(a, k - 1, order);
        out.printLine(ans);
    }

    private void doit(int[][] a, int cur, int[] order) {
        if (cur == 0) return;
        for (int i = 0; i <= cur - 1; i++) {
            int t = order[cur];
            order[cur] = order[i];
            order[i] = t;
            int[] num = new int[a.length];
            for (int j = 0; j < a.length; j++) {
                String s = "";
                for (int j2 = 0; j2 < a[0].length; j2++) {
                    s += a[j][order[j2]];
                }
                num[j] = Integer.parseInt(s);
            }
            int max = -1, min = 1 << 20;
            for (int j = 0; j < a.length; j++) {
                max = Math.max(max, num[j]);
                min = Math.min(min, num[j]);
            }
            ans = Math.min(ans, max - min);
            doit(a, cur - 1, order);
            t = order[cur];
            order[cur] = order[i];
            order[i] = t;
        }
        doit(a, cur - 1, order);
    }
}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

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

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

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

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

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

    public String next() {
        return readString();
    }
}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(outputStream);
    }

    public OutputWriter(Writer writer) {
        this.writer = new PrintWriter(writer);
    }

    public void print(Object... objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0)
                writer.print(' ');
            writer.print(objects[i]);
        }
    }

    public void printLine(Object... objects) {
        print(objects);
        writer.println();
    }

    public void close() {
        writer.close();
    }
}

import java.util.*;

public class Ex {

	public static void next(int[] p) {
		int i = p.length - 1;
		while (i > 0 && p[i] < p[i - 1]) {
			i--;
		}
		int j = p.length - 1;
		while (p[j] < p[i - 1]) {
			j--;
		}
		int d = p[i - 1];
		p[i - 1] = p[j];
		p[j] = d;
		j = 0;
		for (; j <= (p.length - i) / 2 - 1; j++) {
			d = p[i + j];
			p[i + j] = p[p.length - 1 - j];
			p[p.length - 1 - j] = d;
		}
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt(),
			k = sc.nextInt();
		int[][] a = new int[n][k];
		int[] p = new int[k];
		for (int i = 0; i < n; i++) {
			String s = sc.next();
			for (int j = 0; j < k; j++) {
				a[i][j] = s.charAt(j) - '0';
			}
		}

		int fact = 1;
		for (int i = 1; i <= k; i++) {
			p[i - 1] = i;
			fact *= i;
		}
		int Mmin = 1000000000;
		for (int x = 1; x < fact; x++) {
			int max = -1;
			int min = 1000000000;
			for (int i = 0; i < n; i++) {
				String s = "";
				for (int j = 0; j < k; j++) {
					s += a[i][p[j] - 1]+"";
				}
				int c = Integer.parseInt(s);
				if (c > max) max = c;
				if (c < min) min = c;
			}
			if (max - min < Mmin) {
				Mmin = max - min;
			}
			next(p);
		}
		System.out.print(Mmin);
	}
}

import java.util.Arrays;
import java.util.Scanner;

// am just trying :D //
public class B_92 {

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);

        int n = s.nextInt() ;

        int k = s.nextInt() ;

        int [] array = new int[n];
        for(int i = 0 ; i < n ; i ++)
        {
            array [i]  = Integer.parseInt(s.next());
        }

        Arrays.sort(array);

        int diff = array[n-1] - array[0];

        System.out.println(diff);
    }
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.util.Scanner;

/**
 *
 * @author adi
 */

public class PermutationMin {

	private static int n,k;
	private static char[][] value;
        static int returnvalue;
       public static int minPermutationValue(int position, int[] order, boolean[] used) {
		if(position==k) {
			int minvalue = 100000000;
			int maxvalue = 0;
			for(int i=0; i<n; i++) {
				int temp = 0;
				for(int j=0; j<k; j++){
					temp = temp*10 + value[i][order[j]];
                                }
				minvalue = Math.min(minvalue,temp);
				maxvalue = Math.max(maxvalue,temp);
			}
			return maxvalue-minvalue;
		}
		returnvalue = 100000000;
		for(int i=0; i<k; i++) {
			if(!used[i]) {
				used[i] = true;
				order[position] = i;
				returnvalue = Math.min(returnvalue,minPermutationValue(position+1,order,used));
				used[i] = false;
			}
		}
		return returnvalue;
	}
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		n = in.nextInt();
		k = in.nextInt();
		value = new char[n][];
		for(int i=0; i<n; i++){
			value[i] = in.next().trim().toCharArray();
                }
		minPermutationValue(0,new int[k],new boolean[k]);
                System.out.println(returnvalue);
	}

}

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    static int p[],  n,  m;

    static boolean nextPermutation() {
        int a = p.length - 2;
        while (a >= 0 && p[a] >= p[a + 1]) {
            a--;
        }
        if (a == -1) {
            return false;
        }
        int b = p.length - 1;
        while (p[b] <= p[a]) {
            b--;
        }
        int t = p[a];
        p[a] = p[b];
        p[b] = (char) t;
        for (int i = a + 1,  j = p.length - 1; i < j; i++, j--) {
            t = p[i];
            p[i] = p[j];
            p[j] = t;
        }
        return true;
    }

    public static void main(String[] args) {
        Scanner l = new Scanner(System.in);
        n = l.nextInt();
        m = l.nextInt();
        p = new int[m];
       String arr[]= new String[n];
        args = new String[n];
        for (int i = 0; i < m; i++) {
            p[i] = i;
        }
        for (int i = 0; i < n; i++) {
            args[i] = l.next();
        }
        int max=Integer.MAX_VALUE, aux;
        String uno,dos;
        while (true) {
            if(nextPermutation()){
                for(int i=0;i<n;i++){
                    uno="";
                    for(int j=0;j<m;j++){
                        uno+=args[i].charAt(p[j]);
                    }
                    arr[i]=uno;
                }
                Arrays.sort(arr);
                aux=Integer.parseInt(arr[n-1])-Integer.parseInt(arr[0]);
                max=Math.min(aux, max);
            }else{
                break;
            }
        }
        System.out.println(max);
    }
}

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.*;

public class B
{
	BufferedReader in;
	PrintStream out;
	StringTokenizer tok;
	public B() throws NumberFormatException, IOException
	{
		in = new BufferedReader(new InputStreamReader(System.in));
		//in = new BufferedReader(new FileReader("in.txt"));
		out = System.out;
		run();
	}
	int cur;
	int total = 40320;
	int[][] permut;
	void permut(int k, int n)
	{
		if(k==n)
		{
			cur++;
			return;
		}
		for(int i = k; i < n; i++)
		{
			int tmp = permut[cur][k];
			permut[cur][k] = permut[cur][i];
			permut[cur][i] = tmp;
			permut(k+1,n);
		}
	}
	void computepermu(int n)
	{
		permut = new int[total][n];
		cur = 0;
		for(int i = 0; i < total; i++)
			for(int j = 0; j < n; j++)
				permut[i][j] =j;
		permut(0,n);
	}
	int maxdiff(int[] num)
	{
		int max = 0;
		int n = num.length;
		for(int i = 0; i < n; i++)
			for(int j = i+1;j < n; j++)
			{
				int	diff = Math.abs(num[i]-num[j]);
				max = Math.max(diff, max);
			}
		return max;
	}
	void run() throws NumberFormatException, IOException
	{
		int n = nextInt();
		int k =nextInt();
		computepermu(k);
		char[][] s = new char[n][k];
		for(int i = 0; i < n; i++)
			s[i] = nextToken().toCharArray();
		int[] num = new int[n];
		int min = Integer.MAX_VALUE;
		for(int i = 0; i < cur; i++)
		{
			for(int j = 0; j < n; j++)
			{
				num[j] = 0;
				for(int l = 0; l < k; l++)
					num[j] = 10*num[j]+(s[j][permut[i][l]]-'0');
			}
			min = Math.min(min, maxdiff(num));
		}
		out.println(min);
	}
	public static void main(String[] args) throws NumberFormatException, IOException
	{
		new B();
	}
	String nextToken() throws IOException
	{
		if(tok ==null || !tok.hasMoreTokens()) tok = new StringTokenizer(in.readLine());
		return tok.nextToken();
	}
	int nextInt() throws NumberFormatException, IOException
	{
		return Integer.parseInt(nextToken());
	}
	long nextLong() throws NumberFormatException, IOException
	{
		return Long.parseLong(nextToken());
	}
	double nextDouble() throws NumberFormatException, IOException
	{
		return Double.parseDouble(nextToken());
	}
}

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.*;

public class B
{
    BufferedReader in;
    PrintStream out;
    StringTokenizer tok;
    public B() throws NumberFormatException, IOException
    {
        in = new BufferedReader(new InputStreamReader(System.in));
        //in = new BufferedReader(new FileReader("in.txt"));
        out = System.out;
        run();
    }
    int cur;
    int total = 40320;
    int[][] permut;
    void permut(int k, int n)
    {
        if(k==n)
        {
            cur++;
            return;
        }
        for(int i = k; i < n; i++)
        {
            int tmp = permut[cur][k];
            permut[cur][k] = permut[cur][i];
            permut[cur][i] = tmp;
            permut(k+1,n);
            tmp = permut[cur][k];
            permut[cur][k] = permut[cur][i];
            permut[cur][i] = tmp;
        }
    }
    void computepermu(int n)
    {
        permut = new int[total][n];
        cur = 0;
        for(int i = 0; i < total; i++)
            for(int j = 0; j < n; j++)
                permut[i][j] =j;
        permut(0,n);
    }
    int maxdiff(int[] num)
    {
        int max = 0;
        int n = num.length;
        for(int i = 0; i < n; i++)
            for(int j = i+1;j < n; j++)
            {
                int diff = Math.abs(num[i]-num[j]);
                max = Math.max(diff, max);
            }
        return max;
    }
    void run() throws NumberFormatException, IOException
    {
        int n = nextInt();
        int k =nextInt();
        computepermu(k);
        char[][] s = new char[n][k];
        for(int i = 0; i < n; i++)
            s[i] = nextToken().toCharArray();
        int[] num = new int[n];
        int min = Integer.MAX_VALUE;
        for(int i = 0; i < cur; i++)
        {
            for(int j = 0; j < n; j++)
            {
                num[j] = 0;
                for(int l = 0; l < k; l++)
                    num[j] = 10*num[j]+(s[j][permut[i][l]]-'0');
            }
            min = Math.min(min, maxdiff(num));
        }
        out.println(min);
    }
    public static void main(String[] args) throws NumberFormatException, IOException
    {
        new B();
    }
    String nextToken() throws IOException
    {
        if(tok ==null || !tok.hasMoreTokens()) tok = new StringTokenizer(in.readLine());
        return tok.nextToken();
    }
    int nextInt() throws NumberFormatException, IOException
    {
        return Integer.parseInt(nextToken());
    }
    long nextLong() throws NumberFormatException, IOException
    {
        return Long.parseLong(nextToken());
    }
    double nextDouble() throws NumberFormatException, IOException
    {
        return Double.parseDouble(nextToken());
    }
}

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

public class CodefB {

    public static void main (String [] args) throws Exception{

        Scanner in = new Scanner (System.in);
        PrintWriter out = new PrintWriter(System.out);
        int n = in.nextInt();
        int q = in.nextInt();
        int [] a = new int [60000];
        int [] b = new int [60000];
        int i;
        int []g = new int[10];
        g[1]=1;
        for (i=2; i<=9;i++)
            g[i]=g[i-1]*10;
        int inf;
        int sup;
        int ch;
        int res=1000000000;
        int f=1;
        for (i=2; i<=q;i++)
            f*=i;
        for (i = 1; i<=q; i++){
            a[i] = i;
        }
        String s;
        char [][] c= new char [100][100];
        for (i=1; i<=n;i++){
            s= in.next();
            c[i]= s.toCharArray();
        }
        a[0] = q+1;
        for (int z=2; z<=f;z++){
        int k=0;
        for (i = q; i>=1; i--){
            if (a[i]>a[i-1]) {
                k=i-1;
                break;
            }
        }
        if (k>0){
            int t = k+1;
            for (i=t+1; i<=q; i++){
                if((a[k]<a[i])&&(a[t]>a[i]))
                    t = i;
            }
            int x;
            x=a[k];
            a[k]=a[t];
            a[t]=x;
            //for (i=1; i<=k; i++)
                //out.print(a[i]+" ");
            int y=k+1;
            for (i=q; i>k; i--){
                //out.print(a[i]+" ");
                b[y++]=a[i];
                }
            for (i=q; i>k; i--)
                a[i]=b[i];
            sup=-1;
            inf=1000000000;
            for (i=1; i<=n; i++){
                ch=0;
                for (int j=1; j<=q;j++){
                    int u=Character.digit(c[i][a[j]-1],10);
                    ch+=((u))*g[j];
                }
                if (ch>sup)
                  sup=ch;
                if (ch<inf)
                  inf=ch;
            }
            if (res>(sup-inf))
                res=(sup-inf);
            }

        }
        out.print(res);
        out.close();
        }

}

import java.util.Scanner;

public class B124 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println((int)'5');
        int n = sc.nextInt();
        int k = sc.nextInt();
        char[][] a = new char[n+1][k+1];
        for (int i = 1; i <= n; i++) {
            String s = sc.next();
            for (int j = 1; j <= k; j++) {
                a[i][j] = s.charAt(j - 1);
            }
        }
//      for (int i = 1; i <= n; i++) {
//          for (int j = 1; j <= k; j++) {
//              System.out.print(a[i][j]);
//          }
//          System.out.println();
//      }
        int pow = 1;
        int[] b = new int[k+1];
        for (int i = 1; i <= k; i++) {
            pow *= i;
            b[i] = i;
        }
        int[][] p = new int[pow + 1][k + 1];
        for (int i = 1; i <= pow; i++) {
            for (int j = 1; j <= k; j++) {
                p[i][j] = b[j];
            }
            int j = k;
            while(b[j - 1] > b[j])
                j--;
            int h = k;
            while(b[h] < b[j - 1])
                h--;
            int r = b[j - 1];
            b[j - 1] = b[h];
            b[h] = r;
            h = k;
            for (int l = 0; l <= (k - j)/2; l++) {
                r = b[l + j];
                b[j + l] = b[h];
                b[h] = r;
                h--;
            }
        }
        int ans = 1000000000;
        for (int i = 1; i <= pow; i++) {
            int min = 1000000000;
            int max = 0;
            for (int j = 1; j <= n; j++) {
                int x = 0;
                for (int j2 = 1; j2 <= k; j2++) {
                    x = (x * 10 + ((int)a[j][p[i][j2]]) - 48);

                }
                min = Math.min(min, x);
                max = Math.max(max, x);
            }
            ans = Math.min(ans, Math.abs(min-max));
        }
        System.out.println(ans);
    }

}

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

public class B {
    static BufferedReader reader;
    static StringTokenizer tokenizer;
    static PrintStream out;

    static void init() {
        out = System.out;

        reader = new BufferedReader(new InputStreamReader(System.in));
    }

    static String nextToken() {
        while (tokenizer == null || !tokenizer.hasMoreTokens())
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                System.out.println(e);
                System.exit(1);
            }
        return tokenizer.nextToken();
    }

    static byte nextByte() {
        return Byte.parseByte(nextToken());
    }

    static int nextInt() {
        return Integer.parseInt(nextToken());
    }

    static double nextDouble() {
        return Double.parseDouble(nextToken());
    }

    static byte[] next(byte[] pos) {
        pos[0]++;
        int i = 0;
        while ((i < pos.length) && (pos[i] > i)) {
            pos[i] = 0;
            i++;
            if (i == pos.length) return null;
            pos[i]++;
        }
        return pos;
    }

    static void solve() {
        byte n = nextByte(), k = nextByte();
        byte[][] nums = new byte[n][k];
        for (int i = 0; i < n; i++) {
            char[] chars = nextToken().toCharArray();
            for (int j = 0; j < k; j++)
                nums[i][j] = Byte.parseByte(Character.toString(chars[j]));
        }

        int minDiff = Integer.MAX_VALUE;
        byte[] pos = new byte[k];
        do {
            int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
            for (int i = 0; i < n; i++) {
                byte[] figs = new byte[k];
                Arrays.fill(figs, (byte) -1);
                for (int j = pos.length - 1; j >= 0; j--) {
                    int skip = pos[j];
                    int place = 0;
                    while (figs[place] != -1) place++;
                    while ((skip > 0) && (figs[place++] == -1)) skip--;
                    while (figs[place] != -1) place++;
                    figs[place] = nums[i][j];
                }

                int num = 0;
                for (int j = 0; j < figs.length; j++) {
                    num *= 10;
                    num += figs[j];
                }

                if (num > max) max = num;
                if (num < min) min = num;
            }

            int diff = max - min;
            if (diff < minDiff) minDiff = diff;
        } while ((pos = next(pos)) != null);

        out.println(minDiff);
    }

    static void close() {
        out.flush();
        out.close();

        try {
            reader.close();
        } catch (IOException e) {
            System.out.println(e);
            System.exit(1);
        }
    }

    public static void main(String[] args) {
        init();
        solve();
        close();
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Permutations {
	public static int result = Integer.MAX_VALUE;

    public static void main(String[] args) throws IOException {
        BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(f.readLine());
        int n = Integer.parseInt(st.nextToken());
        int m = Integer.parseInt(st.nextToken());
		int a = 0;
		String[] list = new String[n];
		for (int i = 0; i < n; i++) {
			list[i] = f.readLine();
		}
		int[] track = new int[m];
		boolean[] check = new boolean[m];
		recurse(a, track, check, list, n, m, result);
		System.out.println(result);
	}

	public static void recurse(int a, int[] track, boolean[] check, String[] list, int n, int m, int result) {
		if (m == a) {
			int max = 0;
			int min = Integer.MAX_VALUE;
			for (int i = 0; i < n; i++) {
				String str = "";
				String finish = list[i];
				for (int j = 0; j < m; j++) {
					str += finish.charAt(track[j]);
				}
				int look = Integer.parseInt(str);
				if (min > look) {
					min = look;
				}
				if (max < look) {
					max = look;
				}

			}
			if (result > max-min) {
				result = max-min;
			}
		}
		for (int i = 0; i < m; i++) {
			if (!check[i]) {
				check[i] = true;
				track[a] = i;
				recurse(a+1, track, check, list, n, m, result);
				check[i] = false;

			}
		}
	}

}