# Python-Simple Explanation

• If the sequence of digits is decreasing(non-increasing) from left-to-right ala 21,53211 etc.., they are the largest such numbers using those digits. If the above is not true i.e if we have an increase in the digits some where from left to right then we can increase the number further. The further to the left we place a higher digit the larger we make it. Hence, we choose an index at the right most where there is an increase in the digits. For e.g., 523142, 2 and 1 are two such digits and we choose 1 as it is the farthest to right.

Now to increase the number minimally we pick the smallest number on the right that is larger than 1 which is 2 at the end in this case. Exhanging 1 and 2 gives us 5232xx and sort the remaining digits (4,1) on the right to get the smallest number 14 which gives us 523124.

``````lst=[c for c in str(n)]
diff=[i for i in range(0,len(lst)-1) if lst[i+1]>lst[i]]
if len(diff)==0: return -1
idx1=max(diff)
idx2=min([i for i in range(idx1+1,len(lst)) if lst[i]>lst[idx1]],\
key=lst.__getitem__)
lst[idx1],lst[idx2]=lst[idx2],lst[idx1]
lst[idx1+1:]=sorted(lst[idx1+1:])
op=int(''.join(lst))
return -1 if op>=2**31 else op
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.