![]() |
VOOZH | about |
Given two strings n and m representing non-negative integers, find the largest number that can be formed by rearranging the digits of n such that the resulting number is less than or equal to m.
Examples:
Input: n = "123", m = "222"
Output: "213"
Explanation: The permutations of "123" are "123", "132", "213", "231", "312", and "321". Among these, "123", "132", and "213" are less than or equal to "222". Therefore, the answer is "213".Input: n = "3921", m = "10000"
Output: "9321"
Explanation: Since n has fewer digits than m, every permutation of "3921" is less than "10000". The maximum permutation is "9321".
Table of Content
The idea is to generate all possible permutations of the digits of n using recursion (backtracking). For each permutation, we check whether it is valid, i.e., it has no leading zeros and is less than or equal to m. Among all valid permutations, we maintain the maximum one using a global variable.
213
Instead of generating all permutations of the digits of n, we build the answer greedily from left to right. The key idea is to always try to match the current digit of m using available digits from n. If at some position we cannot exactly match m, we try to place the largest possible smaller digit at that position and then maximize the remaining suffix by arranging all remaining digits in descending order.
Consider: n = "123", m = "222"
Step 1: We first store the frequency of digits present in n.
Step 2: Start matching with m
We try to build number digit by digit.
For i = 0
For i = 1
Step 3: Construct final answer using break point
Step 4: Add remaining digits
Final Answer: "213"
213