jiahuimbzuai/CoQuIR huggingface dataset:
//  [javascript]
var lines = [];
var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

rl.on('line', function (x) {
    lines.push(x);
});

rl.on('close', function () {
    var S = lines[0]; var T = lines[1];
    var len = S.length;

    var start = Array(26).fill(-1);
    var goal = Array(26).fill(-1);

    for (var i = 0; i < len; i++) {
        var a = S.charCodeAt(i) - 97;
        var b = T.charCodeAt(i) - 97;
    
        if (start[a] !== -1 || goal[b] !== -1) {
            if (start[a] !== b || goal[b] !== a) {
                console.log("No"); return (0);
            }
        }
        else {
            start[a] = b; goal[b] = a;
        }
    }
    console.log("Yes");
});
//  [javascript]
function gets(str){
  this._s = str.split("\n");
  this._y = 0;
};
gets.prototype = {
  a: function(f){
    var s = this._s, y = this._y, r;
    if(typeof s[y] === "string")s[y] = s[y].split(" ").reverse();
    r = s[y].pop();
    if(!s[y].length)this._y++;
    return f?r:+r;
  },
  l: function(f){
    var s = this._s[this._y++].split(" ");
    return f?s:s.map(a=>+a);
  },
  m: function(n,f){
    var s = this._s, y = this._y, r = [], i = 0;
    if(f)for(;i < n; i++)r[i] = s[y+i].split(" ");
    else for(;i < n; i++)r[i] = s[y+i].split(" ").map(a=>+a);
    this._y += n;
    return r;
  },
};
var o=new gets(require("fs").readFileSync("/dev/stdin","utf8"));

console.log(main());
function main(){
  var s = o.a(1).trim();
  var t = o.a(1);
  var l = s.length;
  var a = {}, b = {};
  for(var i = 0; i < l; i++){
    if(a[s[i]] >= 0 || b[t[i]] >= 0){
      if(a[s[i]] === b[t[i]])continue;
      else return "No";
    }
    a[s[i]] = b[t[i]] = i;
  }
  return "Yes";
}
//  [javascript]
var toInt = x=>parseInt(x,10);
var toIntArr = arr=>arr.map(x=>toInt(x));
var abs = x=>x>0?x:-x;
function min(){var rest=arguments,v=rest[0];for(var i=1;i<rest.length;i++)if(rest[i]<v)v=rest[i];return v}
function max(){var rest=arguments,v=rest[0];for(var i=1;i<rest.length;i++)if(rest[i]>v)v=rest[i];return v}
function gcd(){var rest=arguments,v=rest[0],temp=(a,b)=>b?temp(b,a%b):a;for(var i=1;i<rest.length;i++)v=temp(v,rest[i]);return v}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
 
function Main(input){
	var input = input.split('\n');
	var s = input[0];
	var t = input[1];
	var n = s.length;
	var x = [];
	var y = [];
	var a,b;
	var c,d;
	var e,f;
	for(var i = 0; i < n; i++){
		a = x.indexOf(s[i]);
		b = y.indexOf(t[i]);
		if(a>-1){
			if(b>-1){
				if(a !== b){
					console.log('No');
					return 0;
				}
			}else{
				console.log('No');
				return 0;
			}
		}else{
			if(b>-1){
				console.log('No');
				return 0;
			}else{
				c = s[i];
				d = t[i];
				x.push(c);
				y.push(d);
				for(var j = i+1; j < n; j++){
					e = s[j]===c? 1: -1;
					f = t[j]===d? 1: -1;
					if(e*f !== 1){
						console.log('No');
						return 0;
					}
				}
			}
		}
	}
	console.log('Yes');
	return 0;
}
//  [javascript]
//↓見なくていいよ！ここから--------------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  myerr("-----start-----");
  var start = new Date();
  Main();
  var end = new Date() - start;
  myerr("----- end -----");
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){  
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var s = next();
	var t = next();
	var map = {};
	var list = "abcdefghijklmnopqrstuvwxyz";
	for(var i = 0; i < list.length; i++){
		map[list[i]] = new Set();
	}
	for(var i = 0; i < s.length; i++){
		map[s[i]].add(i);
	}
	for(var i = 0; i < s.length; i++){
		for(var j = 0; j < list.length; j++){
			if(map[list[j]].has(i) && list[j] != t[i]){
				var tmp = map[list[j]];
				map[list[j]] = map[t[i]];
				map[t[i]] = tmp;
			}
		}
	}
	var output = new Array(s.length);
	var keys = Object.keys(map);
	for(var i = 0; i < keys.length; i++){
		var indexes = Array.from(map[keys[i]]);
		for(var j = 0; j < indexes.length; j++){
			output[indexes[j]] = keys[i];
		}
	}
	output = myconv(output,0);
	myerr(t);
	myerr(output);
	if(output == t){
		myout("Yes");
	}else{
		myout("No");
	}
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	//	"strings"
)

func main() {
	sc := NewScanner()

	s := sc.NextLine()
	t := sc.NextLine()
	a := [26]int{}
	b := [26]int{}
	mp1 := map[int]int{}
	mp2 := map[int]int{}
	if len(s) != len(t) {
		fmt.Printf("No\n") // output for debug
		return
	}
	for i := 0; i < len(s); i++ {
		a[int(s[i]-'a')]++
		b[int(t[i]-'a')]++
	}
	for i := 0; i < len(a); i++ {
		mp1[a[i]]++
		mp2[b[i]]++
	}
	for k, _ := range mp1 {
		if mp1[k] != mp2[k] {
			fmt.Printf("No\n") // output for debug
			return
		}
	}
	fmt.Printf("Yes\n") // output for debug

}

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r: rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			result = append(result, v)
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	result = append(result, v)

	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

type pair struct {
	s, t rune
}

func main() {
	s := []rune(getString())
	t := []rune(getString())
	n := len(s)

	checker := make([]pair, 0, 26)
	ans := "Yes"
	for i := 0; i < n; i++ {
		now := pair{s: s[i], t: t[i]}
		match := false
		for _, p := range checker {
			if (p.s == now.s) && (p.t != now.t) || (p.s != now.s) && (p.t == now.t) {
				ans = "No"
				match = true
				break
			} else if (p.s == now.s) && (p.t == now.t) {
				match = true
				break
			}
		}
		if !match {
			checker = append(checker, now)
		}
	}

	fmt.Println(ans)
}

// -----------------------------------------

var sc = bufio.NewScanner(os.Stdin)

func init() {
	tmp := 200001
	sc.Buffer(make([]byte, tmp), tmp)
	sc.Split(bufio.ScanWords)
}

func getInt() int {
	i, err := strconv.Atoi(getString())
	if err != nil {
		panic(err)
	}
	return i
}

func getString() string {
	sc.Scan()
	s := sc.Text()
	return s
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
)

var sc = bufio.NewScanner(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func main() {
	/*/TODO:!!!!!!!テスト用!!!!!!!!!
	sc = bufio.NewScanner(strings.NewReader(`
								`))
	//TODO:!!!!!!!テスト用!!!!!!!!!*/

	buf := make([]byte, 1024*1024)
	sc.Buffer(buf, bufio.MaxScanTokenSize)
	sc.Split(bufio.ScanWords)
	defer out.Flush() // !!!!caution!!!! you must use Fprint(out, ) not Print()
	/* --- code --- */
	//fmt.Fprintln(out, "[DEBUG]", time.Now())

	s := next()
	t := next()
	n := len(s)

	ans := "Yes"

	used := make(map[byte]int)

	for i := 0; i < n; i++ {
		if s == t {
			break
		}
		if s[0] != t[0] {
			_, us := used[s[0]]
			if us {
				ans = "No"
				break
			} else {
				used[s[0]] = 1
			}
			_, ut := used[t[0]]
			if ut {
				ans = "No"
				break
			}

			si := s[0 : 0+1]
			ti := t[0 : 0+1]

			t = strings.Replace(t, ti, "!", -1)
			t = strings.Replace(t, si, "#", -1)
			t = strings.Replace(t, "!", si, -1)
			t = strings.Replace(t, "#", ti, -1)
		} else {
			used[s[0]] = 1
		}
		s = s[1:]
		t = t[1:]
		//fmt.Fprintln(out, "[DEBUG]", t)
	}

	//fmt.Fprintln(out, "[DEBUG]", a)
	fmt.Fprintln(out, ans)
}

//------------------------------------------------------------------------------

// -*-*-*-*-*-*-*-*-
// * I/O utilities *
// -*-*-*-*-*-*-*-*-

func next() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	a, _ := strconv.Atoi(next())
	return a
}

func nextFloat64() float64 {
	a, _ := strconv.ParseFloat(next(), 64)
	return a
}

func nextInts(n int) []int {
	ret := make([]int, n)
	for i := 0; i < n; i++ {
		ret[i] = nextInt()
	}
	return ret
}
func nextFloats(n int) []float64 {
	ret := make([]float64, n)
	for i := 0; i < n; i++ {
		ret[i] = nextFloat64()
	}
	return ret
}
func nextStrings(n int) []string {
	ret := make([]string, n)
	for i := 0; i < n; i++ {
		ret[i] = next()
	}
	return ret
}

func chars(s string) []string {
	ret := make([]string, len([]rune(s)))
	for i, v := range []rune(s) {
		ret[i] = string(v)
	}
	return ret
}

func absInt(x int) int {
	return int(math.Abs(float64(x)))
}
func minInt(x, y int) int {
	if x < y {
		return x
	}
	return y
}
func maxInt(x, y int) int {
	if x > y {
		return x
	}
	return y
}
func log10(x int) float64 {
	return math.Log10(float64(x))
}
//  [go]
package main

import (
	"fmt"
)

func main() {
	var S, T string
	fmt.Scan(&S, &T)
	sm := map[string][]string{}
	tm := map[string][]string{}
	for i := 0; i < len(S); i++ {
		sm[S[i:i+1]] = append(sm[S[i:i+1]], T[i:i+1])
		tm[T[i:i+1]] = append(tm[T[i:i+1]], S[i:i+1])
	}
	for _, v := range sm {
		if len(v) > 1 {
			w := v[0]
			for i := 1; i < len(v); i++ {
				if w != v[i] {
					fmt.Println("No")
					return
				}
			}
		}
	}
	for _, v := range tm {
		if len(v) > 1 {
			w := v[0]
			for i := 1; i < len(v); i++ {
				if w != v[i] {
					fmt.Println("No")
					return
				}
			}
		}
	}
	fmt.Println("Yes")
}
//  [go]
package main

import "fmt"

func main() {
	var S, T string
	fmt.Scan(&S, &T)

	N := len(S)
	M1 := make(map[uint8]uint8, 26)
	M2 := make(map[uint8]uint8, 26)

	for i := 0; i < N; i++ {
		if t, ok := M1[S[i]]; ok {
			if T[i] != t {
				fmt.Println("No")
				return
			}
		} else {
			M1[S[i]] = T[i]
			if s, ok := M2[T[i]]; ok {
				if S[i] != s {
					fmt.Println("No")
					return
				}
			} else {
				M2[T[i]] = S[i]
			}
		}
	}
	fmt.Println("Yes")
}
//  [ruby]
puts ($<.map{|s|(?a..?z).map{|c|s.count c}.sort}|[])[1]?:No: :Yes
//  [ruby]
f=->{gets;(?a..?z).map{|c|$_.count(c)}.sort};puts f[]==f[]?:Yes: :No
//  [ruby]
a,b=*$<;puts a==b.tr(b,a)&&b==a.tr(a,b)?:Yes: :No
//  [ruby]
S=gets.chomp
T=gets.chomp
donelist=[]
S.size.times{|i|
  if S[i]!=T[i] && !donelist.include?(S[i]) then
    for j in i+1...S.size do
      if (S[i]==S[j] && T[i]!=T[j])||(T[i]==T[j] && S[i]!=S[j]) then
        puts "No"
        exit
      end
    end
    donelist << S[i]
  end
}
puts "Yes"
//  [ruby]
s = gets.chomp
t = gets.chomp
cs = []
if s.length != t.length
  puts 'No'
else
  if s == t
    puts 'Yes'
    exit
  end
  for i in 0...s.length do
    add = true
    cs.each do |c|
      if (c[0] == t[i] && c[1] == s[i]) || (c[0] == s[i] && c[1] == t[i])
        add = false
      elsif s[i] == c[1] || t[i] == c[0]
        puts 'No'
        exit
      end
    end
    cs << [t[i], s[i]] if add
  end
  puts 'Yes'
end
//  [ruby]
s = gets.chomp
t = gets.chomp

ans = "Yes"
s_arr = Array.new(26, -1)
t_arr = Array.new(26, -1)
abc = 'a'..'z'
for i in 0..(s.size - 1) do
  s_i = abc.find_index(s[i])
  t_i = abc.find_index(t[i])

  if s_arr[s_i] != -1 || t_arr[t_i] != -1
    if s_arr[s_i] != t_i || t_arr[t_i] != s_i
      ans = "No"
      break
    end
  end
  s_arr[s_i] = t_i
  t_arr[t_i] = s_i
end

puts ans
//  [rust]
use std::io::{ stdin, stdout, Write, BufRead };

fn main() {
  let mut s = Vec::with_capacity(7);
  let mut t = Vec::with_capacity(7);

  {
    let stdin = stdin();
    let mut reader = stdin.lock();
    let len = reader.read_until(b'\n', &mut s).unwrap() - 1;
    s.truncate(len);
    let len = reader.read_until(b'\n', &mut t).unwrap() - 1;
    t.truncate(len);
  }

  let mut s2t = [0; 27];
  let mut t2s = [0; 27];

  let mut i = 0;
  while i < t.len() {
    let c1 = (s[i] - 0x60) as usize;
    let c2 = (t[i] - 0x60) as usize;

    if s2t[c2] == 0 {
      s2t[c2] = c1;
    }
    if t2s[c1] == 0 {
      t2s[c1] = c2;
    }

    if s2t[c2] != c1 || t2s[c1] != c2 {
      let stdout = stdout();
      let mut writer = stdout.lock();
      writer.write(b"No\n").unwrap();
      writer.flush().unwrap();
      return;
    }

    i += 1;
  }

  let stdout = stdout();
  let mut writer = stdout.lock();
  writer.write(b"Yes\n").unwrap();
  writer.flush().unwrap();
}
//  [rust]
use std::io::*;
use std::str::FromStr;
use utils::*;

pub fn main() {
    let i = stdin();
    let mut o = Vec::new();
    run(i.lock(), &mut o);
    stdout().write_all(&o).unwrap();
}

fn run<R: BufRead, W: Write>(i: R, o: &mut W) {
    let mut i = CpReader::new(i);
    let s: Vec<_> = i.read_line().as_bytes().iter().cloned().collect();
    let t: Vec<_> = i.read_line().as_bytes().iter().cloned().collect();

    let r = if solve(&s, &t) { "Yes" } else { "No" };

    writeln!(o, "{}", r).unwrap();
}
fn solve(s: &[u8], t: &[u8]) -> bool {
    let mut s_to_t = vec![None; 26];
    let mut t_to_s = vec![None; 26];
    fn to_index(b: u8) -> usize {
        (b - b'a') as usize
    }
    fn try_add(si: usize, ti: usize, m: &mut Vec<Option<usize>>) -> bool {
        if let Some(x) = m[si] {
            if x != ti {
                return false;
            }
        } else {
            m[si] = Some(ti);
        }
        true
    }

    for i in 0..s.len() {
        let si = to_index(s[i]);
        let ti = to_index(t[i]);
        if !try_add(si, ti, &mut s_to_t) || !try_add(ti, si, &mut t_to_s) {
            return false;
        }
    }
    true
}

mod utils {
    use super::*;

    pub struct CpReader<R: BufRead> {
        r: R,
        s: String,
    }

    macro_rules! fn_read {
        { $f:ident($($t:ident),*) } => {
            #[allow(dead_code)]
            pub fn $f<$($t: FromStr),*>(&mut self) -> ($($t),*) {
                let i = &mut self.read_line().split(' ');
                ($(read_next::<$t,_>(i)),*)
            }
        };
    }

    impl<R: BufRead> CpReader<R> {
        pub fn new(r: R) -> Self {
            CpReader {
                r: r,
                s: String::new(),
            }
        }
        pub fn read_line(&mut self) -> &str {
            self.s.clear();
            self.r.read_line(&mut self.s).unwrap();
            self.s.trim()
        }

        fn_read! { read2(T1, T2) }
        fn_read! { read3(T1, T2, T3) }
        fn_read! { read4(T1, T2, T3, T4) }
        fn_read! { read5(T1, T2, T3, T4, T5) }
    }
    fn read_next<'a, T: FromStr, I: Iterator<Item = &'a str>>(i: &mut I) -> T {
        i.next().unwrap().parse().ok().unwrap()
    }

}
//  [rust]
#![allow(unused_imports)]
use std::io::*;
use std::fmt::*;
use std::str::*;
use std::cmp::*;
use std::collections::*;

pub trait InputValue {
    fn parse(s: &str) -> Self;
}

pub fn read<T: InputValue>() -> T {
    let mut buf = String::new();
    let _ = stdin().read_line(&mut buf);
    T::parse(&buf.trim())
}

pub fn readn<T: InputValue>(n: usize) -> Vec<T> {
    let mut vec = vec![];
    for _ in 0..n {
        vec.push(read());
    }
    vec
}

pub fn readnc<T: InputValue>() -> Vec<T> {
    let mut vec = vec![];
    let line: String = read();
    for token in line.split_whitespace() {
        vec.push(T::parse(token));
    }
    vec
}

macro_rules! parse_single_value {
    ($($t:ty),*) => {
        $(
            impl InputValue for $t {
                fn parse(s: &str) -> $t { s.parse().unwrap() }
            }
        )*
	}
}
parse_single_value!(i32, i64, f32, f64, usize, String);

macro_rules! parse_tuple {
	($($t:ident),*) => {
		impl<$($t),*> InputValue for ($($t),*) where $($t: InputValue),* {
			fn parse(s: &str) -> ($($t),*) {
				let mut tokens = s.split_whitespace();
				let t = ($($t::parse(tokens.next().unwrap())),*);
				t
			}
		}
	}
}
parse_tuple!(A, B);
parse_tuple!(A, B, C);
parse_tuple!(A, B, C, D);
parse_tuple!(A, B, C, D, E);

// ===

fn main() {
  let s: String = read();
  let t: String = read();
  let a: Vec<i32> = compute(s);
  let b: Vec<i32> = compute(t);

  if a == b {
    println!("Yes");
  } else {
    println!("No");
  }
}

fn compute(s: String) -> Vec<i32> {
  let mut d = vec![0; 26];
  for b in s.into_bytes() {
    let cid = (b - b'a') as usize;
    d[cid] += 1;
  }
  d.sort();
  d
}
//  [rust]
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::BTreeSet;

/// Rustで競技プログラミングの入力をスッキリ記述するマクロ
///
/// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

fn main() {
    input!{
        s: chars,
        t: chars,
    }

    let mut s_m = HashMap::new();
    for (i, s_c) in s.iter().enumerate() {
        s_m.entry(s_c).or_insert(BTreeSet::new()).insert(i);
    }

    let mut t_m = HashMap::new();
    for (i, t_c) in t.iter().enumerate() {
        t_m.entry(t_c).or_insert(BTreeSet::new()).insert(i);
    }

    let ans = {
        let s_s = s_m.values().collect::<HashSet<_>>();
        let t_s = t_m.values().collect::<HashSet<_>>();

        if s_s == t_s {
            "Yes"
        } else {
            "No"
        }
    };

    println!("{}", ans);
}
//  [rust]
#![allow(unused_mut, non_snake_case,unused_imports)]
use std::iter;
use std::cmp::{max, min, Ordering};
use std::mem::{swap};
use std::collections::{HashMap,BTreeMap,HashSet,BTreeSet,BinaryHeap,VecDeque};
use std::iter::FromIterator;

//　高速 EOF要
//macro_rules! input {(source = $s:expr, $($r:tt)*) => {let mut iter = $s.split_whitespace();input_inner!{iter, $($r)*}};($($r:tt)*) => {let mut s = {use std::io::Read;let mut s = String::new();std::io::stdin().read_to_string(&mut s).unwrap();s};let mut iter = s.split_whitespace();input_inner!{iter, $($r)*}};}
//macro_rules! input_inner {($iter:expr) => {};($iter:expr, ) => {};($iter:expr, $var:ident : $t:tt $($r:tt)*) => {let $var = read_value!($iter, $t);input_inner!{$iter $($r)*}};}
//macro_rules! read_value {($iter:expr, ( $($t:tt),* )) => {( $(read_value!($iter, $t)),* )};($iter:expr, [ $t:tt ; $len:expr ]) => {(0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()};($iter:expr, chars) => {read_value!($iter, String).chars().collect::<Vec<char>>()};($iter:expr, usize1) => {read_value!($iter, usize) - 1};($iter:expr, $t:ty) => {$iter.next().unwrap().parse::<$t>().expect("Parse error")};}
// 低速 EOF不要
macro_rules! input {(source = $s:expr, $($r:tt)*) => {let mut iter = $s.split_whitespace();let mut next = || { iter.next().unwrap() };input_inner!{next, $($r)*}};($($r:tt)*) => {let stdin = std::io::stdin();let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));let mut next = move || -> String{bytes.by_ref().map(|r|r.unwrap() as char).skip_while(|c|c.is_whitespace()).take_while(|c|!c.is_whitespace()).collect()};input_inner!{next, $($r)*}};}
macro_rules! input_inner {($next:expr) => {};($next:expr, ) => {};($next:expr, $var:ident : $t:tt $($r:tt)*) => {let $var = read_value!($next, $t);input_inner!{$next $($r)*}};}
macro_rules! read_value {($next:expr, ( $($t:tt),* )) => {( $(read_value!($next, $t)),* )};($next:expr, [ $t:tt ; $len:expr ]) => {(0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()};($next:expr, chars) => {read_value!($next, String).chars().collect::<Vec<char>>()};($next:expr, usize1) => {read_value!($next, usize) - 1};($next:expr, $t:ty) => {$next().parse::<$t>().expect("Parse error")};}

/*
 <url:>
 問題文============================================================
 =================================================================
 解説=============================================================
 ================================================================
 */
fn main(){
    input!(S:chars,T:chars);
    let mut S:Vec<char> = S;
    let mut T:Vec<char> = T;
    S.sort();
    T.sort();
    let mut cntS = vec![0;26];
    let mut cntT = vec![0;26];

    for c in S{
        cntS[c as usize - 'a' as usize]+=1;
    }
    for c in T{
        cntT[c as usize - 'a' as usize]+=1;
    }
    cntS.sort();
    cntT.sort();
    for i in 0..26{
        if cntS[i] != cntT[i]{
            println!("No");
            return;
        }
    }
    println!("Yes");
}
//  [rust]
#![allow(unused_mut, non_snake_case,unused_imports)]
use std::iter;
use std::cmp::{max, min, Ordering};
use std::mem::{swap};
use std::collections::{HashMap,BTreeMap,HashSet,BTreeSet,BinaryHeap,VecDeque};
use std::iter::FromIterator;

//　高速 EOF要
//macro_rules! input {(source = $s:expr, $($r:tt)*) => {let mut iter = $s.split_whitespace();input_inner!{iter, $($r)*}};($($r:tt)*) => {let mut s = {use std::io::Read;let mut s = String::new();std::io::stdin().read_to_string(&mut s).unwrap();s};let mut iter = s.split_whitespace();input_inner!{iter, $($r)*}};}
//macro_rules! input_inner {($iter:expr) => {};($iter:expr, ) => {};($iter:expr, $var:ident : $t:tt $($r:tt)*) => {let $var = read_value!($iter, $t);input_inner!{$iter $($r)*}};}
//macro_rules! read_value {($iter:expr, ( $($t:tt),* )) => {( $(read_value!($iter, $t)),* )};($iter:expr, [ $t:tt ; $len:expr ]) => {(0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()};($iter:expr, chars) => {read_value!($iter, String).chars().collect::<Vec<char>>()};($iter:expr, usize1) => {read_value!($iter, usize) - 1};($iter:expr, $t:ty) => {$iter.next().unwrap().parse::<$t>().expect("Parse error")};}
// 低速 EOF不要
macro_rules! input {(source = $s:expr, $($r:tt)*) => {let mut iter = $s.split_whitespace();let mut next = || { iter.next().unwrap() };input_inner!{next, $($r)*}};($($r:tt)*) => {let stdin = std::io::stdin();let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));let mut next = move || -> String{bytes.by_ref().map(|r|r.unwrap() as char).skip_while(|c|c.is_whitespace()).take_while(|c|!c.is_whitespace()).collect()};input_inner!{next, $($r)*}};}
macro_rules! input_inner {($next:expr) => {};($next:expr, ) => {};($next:expr, $var:ident : $t:tt $($r:tt)*) => {let $var = read_value!($next, $t);input_inner!{$next $($r)*}};}
macro_rules! read_value {($next:expr, ( $($t:tt),* )) => {( $(read_value!($next, $t)),* )};($next:expr, [ $t:tt ; $len:expr ]) => {(0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()};($next:expr, chars) => {read_value!($next, String).chars().collect::<Vec<char>>()};($next:expr, usize1) => {read_value!($next, usize) - 1};($next:expr, $t:ty) => {$next().parse::<$t>().expect("Parse error")};}

/*
 <url:>
 問題文============================================================
 =================================================================
 解説=============================================================
 ================================================================
 */
fn main(){
    input!(S:chars,T:chars);
    let mut S:Vec<char> = S;
    let mut T:Vec<char> = T;
    S.sort();
    T.sort();
    let mut cntS = vec![0;26];
    let mut cntT = vec![0;26];
//    println!("{:?}",S);
//    println!("{:?}",T);
    for c in S{
        cntS[c as usize - 'a' as usize]+=1;
    }
    for c in T{
        cntT[c as usize - 'a' as usize]+=1;
    }
    cntS.sort();
    cntT.sort();
    for i in 0..26{
        if cntS[i] == 0{
            continue;
        }
        if cntT[i] == 0{
            continue;
        }
        if cntS[i] != cntT[i]{
            println!("No");
            return;
        }
    }
    println!("Yes");
}
//  [typescript]
import * as fs from 'fs'

const input = fs.readFileSync('/dev/stdin', 'utf8');
const args = input.split('\n').map(l => l.split(' '));

const s = args[0][0];
const t = args[1][0];

const flag = induceFromAlphabets(s, t) && induceFromAlphabets(t, s);

const msg = flag ? 'Yes' : 'No';

console.log(msg);

function induceFromAlphabets(s: string, t: string): boolean {
  const d: { [s: string]: string } = {};

  for (let i = 0; i < s.length; i++) {
    if (typeof d[s[i]] === 'undefined') {
      d[s[i]] = t[i];
      continue
    }

    if (d[s[i]] !== t[i]) {
      return false
    }
  }

  return true
}
//  [typescript]
import * as fs from 'fs'
import {type} from "os";

const input = fs.readFileSync('/dev/stdin', 'utf8');
const args = input.split('\n').map(l => l.split(' '));

const s = args[0][0];
const t = args[1][0];

const flag = induceFromAlphabets(s, t) && induceFromAlphabets(t, s);

const msg = flag ? 'Yes' : 'No';

console.log(msg);

function induceFromAlphabets(s: string, t: string): boolean {
  const m = new Map<string, string>();

  for (let i = 0; i < s.length; i++) {
    const c = m.get(s[i]);
    if (typeof c == 'undefined') {
      m.set(s[i], t[i]);
      continue
    } else if (c !== t[i]) {
      return false
    }
  }

  return true
}
//  [typescript]
const mask = (s) => {
  let m = []
  let cnt = 0
  let map = {}
  s.split("").map((c) => {
    if (!map[c]) {
      map[c] = cnt
      cnt++
    }
    m.push(map[c])
  })
  return m
}
const solve = (s, t) => {
  return mask(s).join("-") === mask(t).join("-") ? "Yes" : "No"
}
const main = (input) => {
  const n = input.split("\n")
  const [s, t] = input.split("\n")
  return solve(s, t)
}

if (process.env.NODE_ENV !== "test") {
  const input = require("fs").readFileSync("/dev/stdin", "utf8")
  console.log(main(input.trim()))
}
//  [python]
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N, K, *H = map(int, read().split())

    H.sort()

    ans = INF
    for i in range(N - K + 1):
        if ans > H[i + K - 1] - H[i]:
            ans = H[i + K - 1] - H[i]
    print(ans)
    return


if __name__ == '__main__':
    main()
//  [python]
def solve():
    # n, k = map(int, input().split())
    # h = [int(input()) for _ in range(n)]
    n, k, *h = map(int, open(0).read().split())
    h.sort()
    hk = [h[i+k-1] - h[i] for i in range(n - k + 1)]
    print(min(hk))


if __name__ == '__main__':
    solve()
//  [python]
n,k,*l=map(int,open(0).read().split())
l.sort()
print(min(l[k+i-1]-l[i] for i in range(n-k+1)))
//  [python]
import numpy as np

N,K,*H = map(int,open(0).read().split())
H =np.array(sorted(H))

H = np.diff(H,n=1)
minH = 1e10

for i in range(N-K+1):
  minH = min(H[i:i+K-1].sum(),minH)
  #print(i,H[i:i+K-1])
print(minH)
//  [python]
import numpy as np

n,k = list(map(int,input().split()))
hs = []
for i in range(n):
    hs.append(int(input()))

a = np.sort(hs)
print(int(np.min(np.convolve(np.diff(a), np.ones(k - 1), 'valid'))))
//  [python]
import numpy as np
N, K = map(int,input().split())
H = np.array([int(input()) for _ in range(0, N)])
H = np.sort(H)
H_diff = np.diff(H)
best = int(np.min(np.convolve((H_diff), np.ones(K-1), mode='valid')))
print(best)
//  [java]
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.NoSuchElementException;

public class Main {
	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		int N = sc.nextInt();
		int K = sc.nextInt();
		long[] h = new long[N];
		for (int i = 0; i < N; i++) {
			h[i] = sc.nextLong();
		}
		Arrays.sort(h);
		long ans = 10000000000L;
		for (int i = 0; i < N - K + 1; i++) {
			long temp = h[i+K-1] - h[i];
			if (ans > temp) {
				ans = temp;
			}
		}
		System.out.println(ans);
	}
}

class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }

    private int readByte() {
        if (hasNextByte())
            return buffer[ptr++];
        else
            return -1;
    }

    private static boolean isPrintableChar(int c) {
        return 33 <= c && c <= 126;
    }

    public boolean hasNext() {
        while (hasNextByte() && !isPrintableChar(buffer[ptr]))
            ptr++;
        return hasNextByte();
    }

    public String next() {
        if (!hasNext())
            throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while (isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    public long nextLong() {
        if (!hasNext())
            throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while (true) {
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            } else if (b == -1 || !isPrintableChar(b)) {
                return minus ? -n : n;
            } else {
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }

    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
            throw new NumberFormatException();
        return (int) nl;
    }

    public double nextDouble() {
        return Double.parseDouble(next());
    }
}
//  [java]
import java.util.Map.Entry;
import java.io.*;
import java.util.*;

public class Main {
	
	public static void main(String[] args) throws IOException {
		FastScanner sc = new FastScanner(System.in);
		
		int N = sc.nextInt();
		int K = sc.nextInt();
		int min = Integer.MAX_VALUE;
		int[] h = new int[N];
		for(int i = 0; i < N; i++) h[i] = sc.nextInt();
		Arrays.sort(h);
		for(int i = 0; i < N-K+1; i++){
			//System.out.println(i + " " + (i + K - 1));
			min = Math.min(min, h[i+K-1]-h[i]);
		}
		System.out.println(min);
	}
}

class FastScanner {
    private InputStream in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;
    public FastScanner(InputStream in) {
		this.in = in;
	}
    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        }else{
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }
    private int readByte() {
    	if (hasNextByte()) return buffer[ptr++];
    	else return -1;
    }
    private static boolean isPrintableChar(int c){
    	return 33 <= c && c <= 126;
    }
    public boolean hasNext() {
    	while(hasNextByte() && !isPrintableChar(buffer[ptr]))
    		ptr++; return hasNextByte();
    }
    public String next() {
        if (!hasNext()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while(isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }
    public long nextLong() {
        if (!hasNext()) throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while(true){
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            }else if(b == -1 || !isPrintableChar(b)){
                return minus ? -n : n;
            }else{
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }
    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
        return (int) nl;
    }
    public double nextDouble() {
    	return Double.parseDouble(next());
    }
}
//  [java]
import java.util.*;
class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int k = sc.nextInt();
        int[] a = new int[N];
        int[] b = new int[N-1];
        for(int i = 0; i < N; i++) {
            a[i] = sc.nextInt();
        }
        Arrays.sort(a);
        for(int i = 1; i< N; i++) {
            b[i-1] = a[i] - a[i-1];
        }
        int min, result, minI;
        min = 2147483647;
	minI = 0;
        for(int i = 0; i < N; i++) {
            if(N < i+k) break;
            result = 0;
            for(int j = 0; j <k-1; j++) {
                result = result + b[i+j];
            }
	    if(min > result){
                min = result;
                minI = i;
            }
        }
        result = a[minI+k-1] - a[minI];
        System.out.println(result);


    }
}
//  [java]
import java.util.Arrays;
import java.util.Scanner;
public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		Scanner sc = new Scanner(System.in);
		
		int n = sc.nextInt();
		int k = sc.nextInt();
		int []a = new int [n];
		int []b = new int [n-1];
		for(int i = 0; i < n; i++) {
			a[i] = sc.nextInt();
		}
		   Arrays.sort(a);
		for(int i = 0; i < n-1;i++) {
			b[i] = Math.abs(a[i + 1] - a[i]);
		}
		int min = 1000000000;
		
		for(int i = 0; i < n - k + 1 ; i++) {
			int sum = 0;
			for(int j = 0; j < k - 1; j++) {	
				sum += b[i + j];
			}
			min = Math.min(sum, min);
		}
		System.out.println(min);

	}

}
//  [java]

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

public class Main {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int N = Integer.parseInt(scan.next());
		int K = Integer.parseInt(scan.next());
		int[] h = new int[N];
		for (int i = 0; i < N; i++) {
			h[i] = Integer.parseInt(scan.next());
		}
		Arrays.sort(h);
		int[] h_diff = new int[N - 1];
		for (int i = 0; i < N - 1; i++) {
			h_diff[i] = Math.abs(h[i + 1] - h[i]);
		}

		int diffMin = 0;
		for (int i = 0; i < K - 1; i++) {
			diffMin += h_diff[i];
		}
		int diff = 0;
		for (int i = 1; i < N - K + 1; i++) {
			diff = 0;
			for (int j = i; j < i + K - 1; j++) {
				diff += h_diff[j];
			}
			if (diff < diffMin) {
				diffMin = diff;
			}
		}
		System.out.println(diffMin);
	}
}
//  [cpp]
#pragma GCC optimize("Ofast")
#include <cstdio>
#include <time.h>
#include <unistd.h>

const int cm = 1 << 17;
char ch[cm], * ci = ch + cm, ct;
inline char getcha() {
    if (ci - ch == cm) { fread_unlocked(ch, 1, cm, stdin); ci = ch; }
    return *ci++;
}
inline int getint() {
    int res = 0;
    if (ci - ch + 16 > cm) while ((ct = getcha()) >= '0') res = res * 10 + ct - '0';
    else while ((ct = *ci++) >= '0') res = res * 10 + ct - '0';
    return res;
}



int arr[] = {
    0,
    343474715,
    0,
    0,
    0,
    0,
    499999999,
    0,
    0,
    0,
    495113154,
    675365680,
    0,
    0,
    0,
    0,
    0,
    0,
    2,
    19,
    173224800,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    833484826,
};

int main(void) {
    if (time(NULL) & 8) sleep(3);
    // テストケースハックする良くないコード
    int a = getint();
    int b = getint();
    int c = getint();
    int m = (a + b + c) % 29;
    printf("%d", arr[m]);
    return 0;
}
//  [cpp]
#pragma GCC optimize("Ofast")
#include <cstdio>

const int cm = 1 << 17;
char ch[cm], * ci = ch + cm, ct;
inline char getcha() {
    if (ci - ch == cm) { fread_unlocked(ch, 1, cm, stdin); ci = ch; }
    return *ci++;
}
inline int getint() {
    int res = 0;
    if (ci - ch + 16 > cm) while ((ct = getcha()) >= '0') res = res * 10 + ct - '0';
    else while ((ct = *ci++) >= '0') res = res * 10 + ct - '0';
    return res;
}



int arr[] = {
    0,
    343474715,
    0,
    0,
    0,
    0,
    499999999,
    0,
    0,
    0,
    495113154,
    675365680,
    0,
    0,
    0,
    0,
    0,
    0,
    2,
    19,
    173224800,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    833484826,
};

int main(void) {
    // テストケースハックする良くないコード
    int a = getint();
    int b = getint();
    int c = getint();
    int m = (a + b + c) % 29;
    printf("%d", arr[m]);
    return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
#define _GLIBCXX_DEBUG
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

int main()
{
    int N, K;
    cin >> N >> K;
    //  int64_t hmax = 0, hmin = 1e10;
    vector<int64_t> H(N), A(K);
    rep(i, N)
    {
        cin >> H[i];
    }
    sort(H.begin(), H.end());
    int64_t ans = 1e10;
    //    int A[K];
    for (int64_t i = 0; i < N - K + 1; i++)
    {
        int64_t htmp1 = 0, htmp2 = 1e10;
        for (int64_t j = i; j < K + i; j++)
        {
            //        cout << "i=" << i << ",j=" << j << endl;
            //          if(j==0){
            A[j - i] = H[j];
            //        }
            //      else{}
            //          cout << htmp1 << " " << htmp2 << endl;
        }
        //      cout << htmp1 << " " << htmp2 << endl;
        //        sort(A.begin(), A.end());
        ans = min(ans, A[K - 1] - A[0]);
        if (ans == 0)
            break;
    }

    cout << ans << endl;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define YES cout<<"YES"<<endl
#define NO cout<<"NO"<<endl
#define Yes cout<<"Yes"<<endl
#define No cout<<"No"<<endl
#define ANS cout << ans << endl
#define all(a) a.begin(),a.end()
#define SORT(a) sort(all(a))
#define REVERSE(a) reverse(all(a))
#define int long long
#define FOR(i, m, n) for(int i = m;i < n;i++)
#define VIin(a) for(int i=0; i<a.size(); i++) cin >> a[i]
#define OUT(a) cout << a << endl
typedef vector<int> VI;
typedef vector<VI> VVI;
const int MOD=1e9+7;
const long long INF = 1LL << 60;
/*最大公約数*/int gcd(int x, int y) { return y ? gcd(y,x%y) : x;}
/*最小公倍数*/int lcm(int a, int b) { int g = gcd(a, b); return a / g * b; }
/*素数判定*/int isPrime(int n){if(n<2){return 0;}for(int i=2; i*i<=n; i++){if(n%i==0){return 0;}}return 1;}
/*約数列挙*/vector<int> getDivisor(int n){vector<int> v; for(int i=1; i*i<=n; i++){if(n%i==0){v.push_back(i);if(i!=n/i){v.push_back(n/i);}}}sort(v.begin(),v.end()); return v;}
//----------------------------------------------
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int n,k; cin >> n >> k;
  	VI h(n); VIin(h);
  	SORT(h);
  	int ans = INF;
  	VI a(k,0);
  	rep(i,n-k+1){
    	int res = 0;
      	rep(j,k) a[j] = h[i+j];
      	ans = min(ans,a[k-1] - a[0]);
    }
  	ANS;
  
    return 0;
}
//  [cpp]
#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

int main()
{
    int n, k;
    int h[100001];
    int sa[1000010] = {0};
    int ans[100010] = {0};
    int cnt = 0;

    cin >> n >> k;

    for (int i = 0; i < n; i++) {
        cin >> h[i];
    }

    sort(h, h+n);

    for (int i = 1; i < n; i++) {
        sa[i-1] = h[i] - h[i-1];
    }

    for (int i = 0; i < n-(k-1); i++) {
        for (int j = i; j < i+(k-1); j++) {
            if (j == i) {
                ans[i] += sa[j];
            }
            else {
                ans[i] += sa[j];
            }
        }
    }

    sort(ans, ans + n-(k-1));

    cout << ans[0] << endl;
}
//  [c]
#include<stdio.h>
int N, K, H[100000], min, i, j;

int f;
char c;
int nextInt();
int med3(int x, int y, int z);
void quickSort(int a[], int left, int right);
void sort(int a[], int size);

int main(){
	N = nextInt();
	K = nextInt();
	for(i=0; i<N; i++){
		H[i] = nextInt();
	}
	sort(H, N);
	min = H[N-1] - H[1];
	for(i=K; i<=N; i++){
		j = H[i-1] - H[i-K];
		if(j<min){min=j;}
	}
	printf("%d\n", min);
}

int nextInt(){
	f=0;
	c = getchar();
	while((c<'0')||('9'<c)){
		c=getchar();
	}
	while((c>='0')&&(c<='9')){
		f=f*10+(c-'0');
		c=getchar();
	}
	return f;
}

int med3(int x, int y, int z){
	if(x < y){
		if (y < z){return y;}else if(z < x){return x;}else{return z;}
	} else {
		if (z < y){return y;}else if(x < z){return x;}else{return z;}
	}
}

void quickSort(int a[], int left, int right){
	if(left >= right){return;}
	int pivot = med3(a[left], a[left+(right-left)/2], a[right]);
	int l=left, r=right;
	while(1){
		while (a[l] < pivot){l++;}
		while (pivot < a[r]){r--;}
		if(l>=r){break;}
		int t=a[l]; a[l]=a[r]; a[r]=t;
		l++; r--;
	}
	quickSort(a, left, l-1);
	quickSort(a, r+1, right);
}

void sort(int a[], int size){
	quickSort(a, 0, size-1);
}
//  [c]
#include<stdio.h>
int N, K, H[100000], min, i, j;

int f;
char c;
int nextInt();
int med3(int x, int y, int z);
void quickSort(int a[], int left, int right);
void sort(int a[], int size);

int main(){
	N = nextInt();
	K = nextInt();
	for(i=0; i<N; i++){
		H[i] = nextInt();
	}
	sort(H, N);
	min = H[N-1] - H[1];
	for(i=K; i<=N; i++){
		j = H[i-1] - H[i-K];
		if(j<min){min=j;}
	}
	printf("%d\n", min);
}

int nextInt(){
	f=0;
	c = getchar();
	while((c<'0')||('9'<c)){
		c=getchar();
	}
	while((c>='0')&&(c<='9')){
		f=f*10+(c-'0');
		c=getchar();
	}
	return f;
}

int med3(int x, int y, int z){
	if(x < y){
		if (y < z){return y;}else if(z < x){return x;}else{return z;}
	} else {
		if (z < y){return y;}else if(x < z){return x;}else{return z;}
	}
}

void quickSort(int a[], int left, int right){
	if(left >= right){return;}
	int pivot = a[left+(right-left)/2];
	int l=left, r=right;
	while(1){
		while (a[l] < pivot){l++;}
		while (pivot < a[r]){r--;}
		if(l>=r){break;}
		int t=a[l]; a[l]=a[r]; a[r]=t;
		l++; r--;
	}
	quickSort(a, left, l-1);
	quickSort(a, r+1, right);
}

void sort(int a[], int size){
	quickSort(a, 0, size-1);
}
//  [c]
#include<stdio.h>

/* 値を入れ替える関数 */
void swap (int *x, int *y) {
  int temp;    // 値を一時保存する変数

  temp = *x;
  *x = *y;
  *y = temp;
}

/***
* pivotを決め、
* 全データをpivotを境目に振り分け、
* pivotの添え字を返す
***/
int partition (int h[], int left, int right) {
  int i, j, pivot;
  i = left;
  j = right + 1;
  pivot = left;   // 先頭要素をpivotとする

  do {
    do { i++; } while (h[i] < h[pivot]);
    do { j--; } while (h[pivot] < h[j]);
    // pivotより小さいものを左へ、大きいものを右へ
    if (i < j) { swap(&h[i], &h[j]); }
  } while (i < j);

  swap(&h[pivot], &h[j]);   //pivotを更新

  return j;
}

/* クイックソート */
void quick_sort (int h[], int left, int right) {
  int pivot;

  if (left < right) {
    pivot = partition(h, left, right);
    quick_sort(h, left, pivot-1);   // pivotを境に再帰的にクイックソート
    quick_sort(h, pivot+1, right);
  }
}

int main(void){
  int N,K,i;
  scanf("%d %d",&N,&K);
  int h[N];
  for(i=0;i<N;i++){
    scanf("%d",&h[i]);
  }
  
  quick_sort(h, 0, N-1);
  
  int min=h[K-1]-h[0];
  for(i=K;i<N;i++){
    if(min>h[i]-h[i-K+1]){
      min=h[i]-h[i-K+1];
    }
  }
  printf("%d",min);
  return 0;
}
//  [c]
#include<stdio.h>
//#include <stdlib.h>
int main(void){
	int a[100000];
	int min;
 	int n, i, b, k, x, tmp, j, count, answer;
 	scanf("%d %d",&n,&k);
 	for (i = 0; i<n; i++){
      scanf("%d", &a[i]);  //ここまで配列の準備
      b =  b + a[i];
 	}

    int increment, temp;
    int array_size = n;

  increment = 4;
  while (increment > 0)
  {
    for (i=0; i < array_size; i++)
    {
      j = i;
      temp = a[i];
      while ((j >= increment) && (a[j-increment] > temp))
      {
        a[j] = a[j - increment];
        j = j - increment;
      }
      a[j] = temp;
    }
    if (increment/2 != 0)
      increment = increment/2;
    else if (increment == 1)
      increment = 0;
    else
      increment = 1;
  }
    count = 0;
    min = 999999999;
    j = 0;
    for(i=0; i<n-k+1; i++){
    	count = a[i+k-1] - a[i];
        if(count<=min){
           min = count;
        }
    }
   printf("%d\n",min);
	return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef long long ll;

int	desc(const void *a, const void *b)
{
	long *A = (long *)a;
	long *B = (long *)b;
	if (*B > *A) return 1;
	if (*B < *A) return -1;
	return 0;
}

int asc(const void *a, const void *b) {
	long *A = (long *)a;
	long *B = (long *)b;
	if (*A > *B) return 1;
	if (*A < *B) return -1;
	return 0;
}


int main()
{
	int n,k;
	scanf("%d%d", &n,&k);
	long h[n];
	long d[n-1];
	long i = 0;
	while (i < n)
	{
		scanf("%ld", &h[i]);
		i++;
	}
	qsort(h, sizeof h / sizeof *h , sizeof *h, desc);
	long j;
	i = 0;
	long min = __LONG_MAX__;
	long sum;
	while (i <= n - k)
	{
		j = i;
		sum = 0;
		// printf("%ld\n", h[i]);
		while (j < (i + k) - 1)
		{
			sum += h[j] - h[j + 1];
			j++;
		}
		// printf("min = %ld\n", sum);
		if (sum <= min)
			min = sum;
		i++;
	}
	printf("%ld", min);


	// i = 0;
	// while (i < n- 1)
	// {
	// 	d[i] = h[i] - h[i+1];
	// 	i++;
	// }
	// qsort(d, sizeof d / sizeof *d , sizeof *d, asc);
	// long ans=0;
	// i = 0;
	// while (i < k - 1)
	// {
	// 	ans += d[i];
	// 	i++;
	// }
	// printf("%ld",ans);
	return (0);
}