You are given two positive integer numbers a and b. Permute (change order) of the digits of a to construct maximal number not exceeding b. No number in input and/or output can start with the digit 0.

It is allowed to leave a as it is.


-----Input-----

The first line contains integer a (1 ≤ a ≤ 10^18). The second line contains integer b (1 ≤ b ≤ 10^18). Numbers don't have leading zeroes. It is guaranteed that answer exists.


-----Output-----

Print the maximum possible number that is a permutation of digits of a and is not greater than b. The answer can't have any leading zeroes. It is guaranteed that the answer exists.

The number in the output should have exactly the same length as number a. It should be a permutation of digits of a.


-----Examples-----
Input
123
222

Output
213

Input
3921
10000

Output
9321

Input
4940
5000

Output
4940

Difficulty: interview

Starter code:

Solutions:
a = list(input())
b = int(input())
a.sort()
a = a[::-1]
prefix = ""
while(len(a) > 0):
	for i in range(len(a)):
		num = prefix + a[i] + "".join(sorted(a[:i] + a[i + 1:]))
		if (int(num) <= b):
			prefix += a[i]
			a = a[:i] + a[i+1:]
			break
print(prefix)


fact_ = [1] * 50


def fact(n):
    return fact_[n]


def get_perm(n, k):
    if k > fact(n):
        exit(123)

    if n == 1:
        return [1]

    k -= 1
    res = []
    not_used = [i for i in range(1, n + 1)]
    size = fact(n - 1)
    for i in range(n):
        cnt = k // size
        res.append(not_used[cnt])
        not_used.pop(cnt)
        k %= size
        if i != n - 1:
            size //= (n - 1 - i)
    return res[::]


def num_by_perm(x):
    nonlocal n, a
    v = get_perm(n, x)
    res = []
    for i in range(n):
        res.append(a[v[i] - 1])
    return int(''.join(res))


def check(x):
    nonlocal n, a, b
    v = num_by_perm(x)
    if v > b:
        return False
    else:
        return True


for i in range(1, 20):
    fact_[i] = fact_[i - 1] * i


a = list(input())
b = int(input())
n = len(a)

a.sort()

l = 1
r = fact(n) + 1
while r - l > 1:
    m = l + (r - l) // 2
    if check(m):
        l = m
    else:
        r = m

print(num_by_perm(l))


from bisect import *

a = sorted(input())
b = input()

if len(a) < len(b):
    print(''.join(reversed(a)))
    return

res = ''
lower = False
for i in range(len(b)):
    # print('i = ', i)
    # print('a = ', a)
    for j in range(len(a) - 1, -1, -1):
        bb = b[i + 1 :]
        aa = a[:j] + a[j + 1:]
        if a[j] < b[i] or a[j] == b[i] and ''.join(aa) <= bb:
            res += a[j]
            a = aa
            break
    if res[-1] < b[i]:
        break

print(res + ''.join(reversed(a)))

b = [int(i) for i in list(input())]
a = [int(i) for i in list(input())]
if len(b) < len(a):
    print(''.join([str(i) for i in sorted(b, key=lambda x: -x)]))
    return
from collections import Counter
bs = Counter(b)
mp = 0
while mp < len(a) and bs[a[mp]] > 0:
    bs[a[mp]] -= 1
    mp += 1
if mp == len(a):
    print(''.join(str(i) for i in a))
    return

ms = 0
for s in range(1, mp+1):
    bs = Counter(b)
    for i in range(s):
        bs[a[i]] -= 1
    nl = a[s] - 1
    while nl >= 0 and bs[nl] == 0:
        nl -= 1
    if nl == -1:
        continue
    else:
        ms = s
ans = []
bs = Counter(b)
for i in range(ms):
    bs[a[i]] -= 1
    ans.append(a[i])
nl = a[ms] - 1
while nl >= 0 and bs[nl] == 0:
    nl -= 1
ans.append(nl)
bs[nl] -= 1
d1 = [[i for _ in range(bs[i])] for i in bs]
r = []
for l in d1:
    r += l
r = sorted(r, key=lambda x: -x)
ans += r
print(''.join([str(i) for i in ans]))

a = input()
b = input()
if (len(a) < len(b)):
    q = list(a)
    q.sort(reverse = True)
    print(''.join(q))
else:
    ans = ""
    flag = 0
    while (flag == 0 and len(b) != 0):
        cur = 0
        while (cur < len(a) and a[cur] != b[0]):
            cur += 1
        if (cur < len(a)):
            ans = ans + a[cur]
            a = a[:cur] + a[cur+1:]
            b = b[1:]
        else:
            flag = 1
    if (len(b) == 0):
        print(ans)
    else:
        ma = -1
        p = -1
        for i in range(len(a)):
            if (int(a[i]) > ma and int(a[i]) < int(b[0])):
                ma = int(a[i])
                p = i
        if (ma != -1):
            l = a[p]
            a = a[:p] + a[p+1:]
            q = list(a)
            q.sort(reverse = True)
            print(ans + l + ''.join(q))
        else:
            flag = 0
            while (flag == 0):
                ma = -1
                p = -1
                for i in range(len(a)):
                    if (int(a[i]) > ma and int(a[i]) < int(ans[-1])):
                        ma = int(a[i])
                        p = i
                if (ma != -1):
                    a = a + ans[-1]
                    ans = ans[:-1] + a[p]
                    a = a[:p]+a[p+1:]
                    q = list(a)
                    q.sort(reverse = True)
                    print(ans + ''.join(q))
                    flag = 1
                else:
                    a = a + ans[-1]
                    ans = ans[:-1]



def check(ans, num, a, b, u):
    prob = ans
    a = []
    for i in range(len(num)):
        a.append(num[i])
    prob += num[u]
    a.pop(u)
    a.sort()
    for i in range(len(a)):
        prob += a[i]
    if int(prob) <= int(b):
        return True
    return False


a = input()
b = input()
num = []
ans = ''
if len(a) == len(b):
    for i in range(len(a)):
        num.append(a[i])
    num.sort()
    num.reverse()
    step = 0
    while num:
        for i in range(len(num)):
            if check(ans, num, a, b, i):
                ans += num[i]
                num.pop(i)
                break
    if num:
        ans += num[-1]
    print(ans)
else:
    num = []
    for i in range(len(a)):
        num.append(a[i])
    num.sort()
    num.reverse()
    ans = ''
    for i in range(len(num)):
        ans += num[i]
    print(ans)

from collections import Counter

a, b = input(), input()
if len(a) < len(b):
    print(''.join(sorted(a)[::-1]))
else:
    a = Counter(a)
    t = []
    for q in b:
        t.append(q)
        a[q] -= 1
        if a[q] < 0: break
    else:
        print(''.join(t))
        return
    s = ''
    while not s:
        d = t.pop()
        a[d] += 1
        for q, k in a.items():
            if k > 0 and s < q < d: s = q
    a[s] -= 1
    t.append(s)
    for q in '9876543210':
        t += [q] * a[q]
    print(''.join(t))

a = list(map(int,input()))
b = list(map(int,input()))


if len(b) > len(a):
  a.sort(reverse=True)
  print(''.join(map(str,a)))
else:


  counts = [0]*10
  for d in a:
    counts[d] += 1

  def rec(counts,i):
    if i >= len(b):
      return []

    d = b[i]
    if counts[d] > 0:
      counts[d] -= 1
      r = rec(counts,i+1)
      if r is None:
        counts[d] += 1
      else:
        res = [d] + r
        return res

    for d in reversed(list(range(d))):
      if counts[d] > 0:
        counts[d] -= 1
        res = [d]
        for e in reversed(list(range(10))):
          for _ in range(counts[e]):
            res.append(e)
        return res

    return None

  print(''.join(map(str,rec(counts,0))))


from collections import Counter

a = input()
b = input()

def is_subcounter(cnt1, cnt2):
    for key in cnt1:
        if key not in cnt2 or cnt1[key] > cnt2[key]:
            return False
    return True

def subtract_counters(cnt1, cnt2):
    result = Counter(cnt1)
    for key, val in list(cnt2.items()):
        assert val <= result[key]
        result[key] -= val
    return result

def go():
    ca = Counter(a)
    best = None
    for pos in range(len(a) - 1, -1, -1):
        cb_before = Counter(b[:pos])
        if not is_subcounter(cb_before, ca):
            continue
        cnt_left = subtract_counters(ca, cb_before)
        for key, val in list(cnt_left.items()):
            if val == 0:
                continue
            if key >= b[pos]:
                continue
            tail = sorted(''.join(key1 * (val1 if key1 != key else val1 - 1)
                for key1, val1 in list(cnt_left.items())), reverse=True)
            curr = b[:pos] + key + ''.join(tail)
            assert curr < b
            if best is None or curr > best:
                best = curr
    assert best is not None
    return best

def solve(a, b):
    assert(len(a) <= len(b))
    if len(a) < len(b):
        return ''.join(sorted(a, reverse=True))
    elif Counter(a) == Counter(b):
        return b
    else:
        return go()

print(solve(a, b))




a = input()
b = input()

if sorted(list(a)) == sorted(list(b)):
    print(b)
elif len(a) < len(b):
    print(''.join(sorted(a)[::-1]))
else:
    digits = {}
    for x in a:
        y = int(x)
        if y in digits:
            digits[y] += 1
        else:
            digits[y] = 1

    best = 0

    for i in range(len(b)):
        digits_cpy = dict(digits)
        all_present = True
        for j in range(i):
            b_j = int(b[j])
            if b_j in digits_cpy and digits_cpy[b_j] != 0:
                digits_cpy[b_j] -= 1
            else:
                all_present = False

        if not all_present:
            continue

        found = False
        change = 0
        for z in range(int(b[i]) - 1, -1, -1):
            if z in digits_cpy and digits_cpy[z] != 0:
                found = True
                change = z
                digits_cpy[z] -= 1
                break

        if not found:
            continue

        digits_left = []
        for key, val in list(digits_cpy.items()):
            digits_left += [key] * val

        result = list(b[:i]) + [change] + sorted(digits_left)[::-1]

        best = max([best, int(''.join(map(str, result)))])

    print(best)


a = input()
b = input()
digits = list(a)
builder=''
if len(b)<len(a):
	b = b.rjust(len(a), '0')
for digit in b:
	if len(b)>len(a):
		break
	if digit in digits:
		digits.remove(digit)
		if int(builder+digit+''.join(sorted(digits, key=int)))<=int(b):
			builder += digit
			continue
		else:
			digits.append(digit)
	added = max([d for d in digits if d<digit])
	builder += added
	digits.remove(added)
	break
builder += ''.join(sorted(digits, reverse=True, key=int))
print(builder)

def f(n):
    if n <= 1:
        return 1
    else:
        return n * f(n - 1)


def g(ls, i, s):
    if len(ls) == 1:
        return 10 * s + ls[0]
    else:
        k = f(len(ls) - 1)
        return g(ls[:i // k] + ls[i // k + 1:], i % k, 10 * s + ls[i // k])


a = int(input())
b = int(input())
ls = list(sorted(map(int, str(a))))
l = 0
r = f(len(ls)) - 1
if g(ls, r, 0) <= b:
    ans = g(ls, r, 0)
else:
    while 1 < r - l:
        c = (l + r) // 2
        if b < g(ls, c, 0):
            r = c
        else:
            l = c
    ans = g(ls, l, 0)
print(ans)


from copy import copy


def check(a, b):
    a = int(''.join(sorted(a)))
    b = int(b[1:])

    return a <= b


def get(a, b):
    nonlocal ans
    nonlocal ret

    if a == b:
        ans += list(a)

        ret = True

        return ans

    a = list(a)

    if a == list():
        ret = True

        return ans

    temp = [el for el in a if int(el) <= int(b[0])]
    m = max(temp)

    c = copy(a)
    c.remove(m)

    if m == b[0]:
        if check(c, b):
            ans.append(m)

            get(''.join(c), b[1:])

            if ret:
                return ans

        else:
            while m in temp:
                temp.remove(m)

            m = max(temp)

            d = copy(a)
            d.remove(m)

            ans.append(m)

            ans += sorted(d, reverse=True)

            ret = True

            return ans

    else:
        ans.append(m)

        ans += sorted(c, reverse=True)

        ret = True

        return ans


a = input()
b = input()

ans = list()
ret = False

if len(a) < len(b):
    print(''.join(sorted(a, reverse=True)))

else:  # len(a) == len(b)
    if a == b:
        print(a)
    else:
        print(int(''.join(get(a, b))))


def check(m):
	nonlocal c, ans
	ans = [0] * len(a)
	have = c[:]
	for i in range(m):
		if have[b[i]] > 0:
			have[b[i]] -= 1
			ans[i] = b[i]
		else:
			return 0
	for i in range(b[m] - 1, -1, -1):
		if have[i]:
			ans[m] = i
			have[i] -= 1
			break
	else:
		return 0
	j = m + 1
	for i in range(10,-1,-1):
		for t in range(have[i]):
			ans[j] = i
			j += 1
	return (j == len(a))


a = list(map(int, list(input())))
b = list(map(int, list(input())))
ans = [0] * len(a)

if len(a) < len(b):
	a.sort(reverse = 1)
	for i in a:
		print(i, end = '')
	print()
else:
	a.sort(reverse = 1)
	if a == sorted(b, reverse = 1):
		for i in b:
			print(i, end = '')
		print()
	else:
		c = [0] * 15
		for i in a:
			c[i] += 1

		for i in range(len(a) - 1, -1 , -1):
			if check(i):
				for i in ans:
					print(i, end = '')
				print()
				break
		else:
			for i in b:
				print(i, end = '')
			print()

from functools import reduce
from fractions import gcd
import copy
from pip._vendor.distlib.compat import raw_input
import math
from decimal import *
getcontext().prec = 6

a = raw_input()
b= raw_input()
x = [None]*len(a)
y = [None]*len(b)
for i in range(len(a)):
    x[i] = int(a[i])
for i in range(len(b)):
    y[i] = int(b[i])

def zjisti(x,y):
    x.sort(reverse=True)
    c = copy.deepcopy(x)
    vysl1=[]
    if len(x)< len(y):
        v=''
        for i in range(len(x)):
            v+=(str(x[i]))
        return(v)
    if y[0] in x:
        x.remove(y[0])
        vysl1.append(y[0])
        jup = 0
        for i in range(len(y)-1):
            if y[i+1] < x[len(x)-i-1]:
                jup = -1
                break
            elif y[i+1] > x[len(x)-i-1]:
                break
        
        if jup ==0:
            o = y[0]
            y.remove(y[0])
            if len(x)>0:
                return(str(o)+zjisti(x,y))   
            else:
                return(str(o))
    q = y[0]
    for j in range(len(c)):
        if c[j]<q:
            s = c[j]
            break
    v = str(s)
    c.remove(s)
    for i in range(len(c)):
        v+=(str(c[i]))
    return(v)

print(zjisti(x,y))

import bisect

def get_int(l, xa, j):
    return int(''.join(l + [xa[j]] + sorted(xa[:j] + xa[j+1:])))

def f(a, b):
    if len(a) < len(b):
        return int(''.join(reversed(sorted(a))))
    xa = list(sorted(a))
    xb = list(b)
    ib = int(b)
    m = int(''.join(xa))

    l = []
    for i in range(len(xb)):
        mj, r = 0, 0
        for j in range(len(xa)):
            if get_int(l, xa, j) <= ib:
                r = get_int(l, xa, j)
                mj = j
        l.append(xa[mj])
        xa = xa[:mj] + xa[mj+1:]

    return int(''.join(l))

def test_f():
    assert f('123', '222') == 213
    assert f('129', '1000') == 921
    assert f('125', '222') == 215
    assert f('4940', '5000') == 4940
    assert f('321', '500') == 321


a = input()
b = input()
print(f(a, b))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-


def main():
    a = list(input())
    b = list(input())
    n = len(a)
    if (n < len(b)):
        a.sort()
        a.reverse()
        print(''.join(a))
        return
    b_ = [int(_) for _ in b]
    a.sort()
    a.reverse()
    a_ = [int(_) for _ in a]
    c = [0 for _ in range(n)]
    r = []
    index = 0
    flag = 0
    while index < n:
        now = b_[index]
        if now < 0:
            b_[index] = 0
            index -= 1
            b_[index] -= 1
            r = []
            c = [0 for _ in range(n)]
            index = 0
            continue
        ma = -1
        for i in range(n):
            if c[i]:
                continue
            if a_[i] <= now:
                c[i] = 1
                ma = a_[i]
                break
        if ma is -1:
            b_[index] = 9
            index -= 1
            b_[index] -= 1
            r = []
            c = [0 for _ in range(n)]
            index = 0
            continue
        r.append(ma)
        if ma < int(b[index]):
            flag = 1
            break
        index += 1
    if flag is 1:
        for each in r:
            print(each, end='')
            a_.remove(each)
        for each in a_:
            print(each, end='')
        print()
        return
    for each in r:
        print(each, end='')
    print()


main()



a=input().strip()
b=input().strip()
if len(b)>len(a):
  print(''.join(sorted(a))[::-1])
else:
  f=[0]*11
  for ele in a:
    f[int(ele)]+=1
  ans=''
  i=0
  n=len(b)
  while i<n:
    num=int(b[i])
    if f[num] : 
      ans+=str(num)
      f[num]-=1
    else:
        break
    i+=1
  
    
  flag=0
  while True and len(ans)!=len(a):
      num=int(b[i])
      num-=1
      while num>=0:
        if f[num]:
          ans+=str(num)
          f[num]-=1
          for j in range(9,-1,-1):
            ans+=(str(j)*f[j])
          break
        num-=1 
      if len(ans)==len(a):
        break
      f[int(ans[-1])]+=1 
      ans=ans[:-1]
      i-=1 
  print(ans.strip())        
    


def x(a,b):
    a.sort()
    #print('dsahhf    ',a,b)
    l = len(a)
    if len(a) < len(b):
        return(''.join(sorted(a,reverse = True)))
    elif l>len(b):
        #print(a,a[:-1])
        return '0' + x(a[1:],b)
    else:
        f = True
        if l ==0:return ''
        for i in range(l):
            if a[i]>b[i]:
                f = False
            elif a[i] < b[i]:break
        if not f:
            return -1
        a = list(a)
        a.sort(reverse = True)
        o = ''
        if b[0] in a:
            f = a.index(b[0])
            t = x(a[:f]+a[f+1:],b[1:])
            #print(t,a[:f]+a[f+1:],b[1:])
            f2 = -1
            if t == -1:
                m = '9'
                f2 = 0
                for i in range(l-1,-1,-1):
                    if a[i] >= b[0]:
                        break
                    m = a[i]
                    f2 = i
                #print(a,f2,m)
                #print(a[:f2],a[f2+1:])
                return m+''.join(a[:f2])+''.join(a[f2+1:])
            else:
                return b[0]+t
        else:
            m = '9'
            f2 = 0
            for i in range(l-1,-1,-1):
                if a[i] > b[0]:
                    break
                m = a[i]
                f2 = i
            #print(a,f2,m)
            #print(a[:f2],a[f2+1:])
            return m+''.join(a[:f2])+''.join(a[f2+1:])
a = input()
b = input()
print(int(x(list(sorted(a)),b)))


a = input()
b = input()
if len(b) > len(a):
    tmp = list(a)
    tmp.sort(reverse = True)
    for i in tmp:
        print(i, end="")
    return
sa = [0] * 10
for i in a:
    sa[int(i)] += 1
def tolow():
    tmp = ""
    for i in range(0, 10):
        tmp += str(i) * sa[i]
    return tmp
def tobig():
    tmp = ""
    for i in range(9, -1, -1):
        tmp += str(i) * sa[i]
    return tmp
nakop = ""
for i in range(len(b)):
    tmp = int(b[i])
    if (sa[tmp] > 0):
        sa[tmp] -= 1
        cur = int(nakop + b[i] + tolow())
        if cur <= int(b):
            nakop += str(b[i])
            continue
        else:
            sa[tmp] += 1
            for j in range(tmp - 1, -1, -1):
                if sa[j]:
                    sa[j] -= 1
                    print(nakop + str(j) + tobig())
                    return            
    else:
        for j in range(tmp - 1, -1, -1):
            if sa[j]:
                sa[j] -= 1
                print(nakop + str(j) + tobig())
                return

        
print(nakop)
                    


    
    


def split(integer):
	ret = []
	while integer != 0:
		ret.append(integer % 10) # last one
		integer //= 10
	return ret[::-1]

def combine(lst):
	total = 0
	n = len(lst)
	for i in range(n):
		total += 10 ** (n-i-1) * lst[i]
	return int(total)


# al = sorted(list(split(a)))[::-1]
# bl = list(split(b))



# Answer can't have leading zeros.
# Then len(a) == len(b)
# 499200 vs 982400 = b
# 942=a, 911=b
# 9442=a, 9411=b

def solve3(a, b):
	al = sorted(list(split(a)))[::-1]
	bl = list(split(b))
	if len(bl) > len(al):
		print(combine(al))
		return


	if a == b:
		print(a)
		return

	ptr = 0
	n = len(al)
	while ptr < n:
		# print(al, bl, ptr)
		val = bl[ptr]
		selection = al[ptr] # Sorted from high to low
		if selection > val: # illegal:
			k = al.pop(ptr) # pop this idx
			al.append(k)
		if selection == val:
			if ptr == n-1:
				print(combine(al)) # Done to the last one.
				break
			else:
				if combine(sorted(al[ptr+1:])) > combine(bl[ptr+1:]):
					# illegal, min of a_rest is larger than b_rest
					k = al.pop(ptr)
					al.append(k)
				else:
					ptr += 1
					al = al[:ptr] + sorted(al[ptr:])[::-1]
					# print("repermute", al, bl)
					# print(selection)
		if selection < val: # all ptr to the back is legal
			# print("enter")
			# print(al, bl,ptr)

			print(combine(al[:ptr+1] + list(sorted(al[ptr+1:])[::-1])))
			break

a = int(input())
b = int(input())
# solve3(31434123, 13241234)
solve3(a,b)
# solve3(123, 301)
# solve3(4940,5000)
# solve3(942, 911)
# solve3(9442, 9411)
# solve3(3921,10000)
# solve3(9991020, 100001)


def main():
   num = input()
   maxi = int(input())
   nl = len(num)
   maxNum = 0
   nums = list(num)
   
   for x in range(len(nums)):
      nums[x] = int(nums[x])
   nums.sort()
   nums = nums[::-1]
   
   if int(str(maxi)[0]) in nums and len(str(maxi))==len(nums):
      nums.remove(int(str(maxi)[0]))
      maxNum = recur(int(str(maxi)[0]), nums, maxi)
      nums.append(int(str(maxi)[0]))
      nums.sort(reverse = True)
   elif len(str(maxi))>len(nums):
      for x in nums:
         maxNum = maxNum*10 + x         
   if maxNum==0 or maxNum>maxi:
      maxNum = 0
      maxD = (int(str(maxi)[0]))
      a = 0
      for x in nums:
         if x < maxD:
            a = max(x, a)
      maxNum =a
      nums.remove(a)   
      for x in nums:
         maxNum = maxNum * 10 + x
      nums.append(a)
      nums.sort(reverse = True)
   print(maxNum)

   

def recur(curr, poss, maxi):
   maxNum=0
   #print(curr, poss, maxi)
   if len(poss)==0:
      return curr  
   if int(str(maxi)[len(str(curr))]) in poss:
      poss.remove(int(str(maxi)[len(str(curr))]))
      maxNum = recur(curr*10+int(str(maxi)[len(str(curr))]), poss.copy(), maxi)
      poss.append(int(str(maxi)[len(str(curr))]))
      poss.sort(reverse = True)
      
   if maxNum > maxi or maxNum==0:
      maxD = (int(str(maxi)[len(str(curr))]))      
      a = 0
      for x in poss:
         if x < maxD:
            a = max(x, a)
      if a not in poss:
         return maxi+5
      #print(maxD, poss, a, maxi, curr)
      curr = curr*10 + a
      poss.remove(a)   
      for x in poss:
         curr = curr * 10 + x
      poss.append(maxD)
      poss.sort(reverse = True)
      return curr
   else:
      return maxNum

main()


from collections import Counter

def max_num(a,b):
    if len(b) > len(a):
        val=''.join(sorted(a, reverse=True))
        return int(val)
    else:
        # int_a=int(''.join(sorted(a)))
        # int_b=int(''.join(b))
        # for i in range(int_b,int_a-1,-1):
        #     # print(str(i),str(int_a))
        #     if Counter(str(i)) == Counter(str(''.join(a))):
        #         return i
        res=''
        for i in b:
            if i in a:
                a.remove(i)
                if ''.join(b[len(res)+1:]) >= ''.join(sorted(a)):
                    res+=i
                else:
                    a.append(i)
                    break
            else:
                break
        # print(res)
        # return res
        new_b=b[len(res):]
        if new_b==[]:
            return res

        for i in new_b:
            for j in range(int(i)-1,-1,-1):
                if str(j) in a:
                    a.remove(str(j))
                    return res+str(j)+''.join(sorted(a, reverse=True))

a=list(input())
b=list(input())
print(max_num(a,b))


a = input()
b = input()
a_cifr = [0] * 10
for i in a:
    a_cifr[int(i)] += 1
if len(b) > len(a):
    cur = list(a)
    cur.sort(reverse = True)
    for i in cur:
        print(i, end="")
    return
    
def vniz():
    cur = ""
    for i in range(0, 10):
        cur += str(i) * a_cifr[i]
    return cur
abba = 123
def boba():
    abbaa = 12
    abbaa += abba
def vverh():
    cur = ""
    for i in range(9, -1, -1):
        cur += str(i) * a_cifr[i]
    return cur
full = ""
for i in range(len(b)):
    cur = int(b[i]) + 2
    cur -= 2
    if (a_cifr[cur] > 0):
        a_cifr[cur] -= 1
        cur1 = int(full + b[i] + vniz())
        if cur1 <= int(b):
            full += str(b[i])
            continue
        else:
            a_cifr[cur] += 1
            for j in range(cur - 1, -1, -1):
                if a_cifr[j]:
                    a_cifr[j] -= 1
                    print(full + str(j) + vverh())
                    return            
    else:
        for j in range(cur - 1, -1, -1):
            if a_cifr[j]:
                a_cifr[j] -= 1
                print(full + str(j) + vverh())
                return
print(full)

from collections import defaultdict

a = input()
b = input()


def form(a_digits):
    answer = []
    for i in sorted(a_digits, reverse=True):
        answer.append(i * a_digits[i])
    return "".join(answer)


def main():
    if len(b) > len(a):
        return "".join(sorted(list(a), reverse=True))
    else:
        a_digits = defaultdict(int)
        for x in a:
            a_digits[x] += 1
        r = 0
        for x in b:
            if a_digits[x] > 0:
                a_digits[x] -= 1
                r += 1
            else:
                for i in range(r, -1, -1):
                    for j in range(int(b[i]) - 1, -1, -1):
                        if a_digits[str(j)] > 0:
                            a_digits[str(j)] -= 1
                            return b[: i] + str(j) + form(a_digits)
                    a_digits[b[i - 1]] += 1
        return b

print(main())