This page is still under construction.

Parts of this page are still being built. What you see may change.

Each digit at most twice

Interview

Time limit3sMemory limit256 MB

Summary
Find the largest integer L not greater than U whose decimal digits each appear at most twice.
Level

Medium5 of 10

Topics
Backtracking, Greedy, String
Solved
No attempts yet

Problem

Write a positive integer in decimal without leading zeros. The number satisfies the rule when no digit appears three or more times. For example 2015201520152015 satisfies the rule, and 10001000 does not because the digit 00 appears three times.

Given a positive integer UU, find the largest integer LL with L≤UL \le U that satisfies the rule. Every one-digit number satisfies the rule, so such an LL always exists.

Input

The first line contains an integer UU (1≤U≤10181 \le U \le 10^{18}).

Output

Print the largest integer not greater than UU whose decimal representation has no digit appearing three or more times.

Examples4

  1. Example 1

    Input
    2210102960
    
    Expected output
    2210099887
    
  2. Example 2

    Input
    1000000000000000000
    
    Expected output
    998877665544332211
    
  3. Example 3

    Input
    1001223343
    
    Expected output
    998877665
    
  4. Example 4

    Input
    20152015
    
    Expected output
    20152015