Next Greater Element III
from collections import Counter
class Solution:
def nextGreaterElement(self, n: int) -> int:
# INPUT:
# -----------------
# |
# | | |
# | | | | | |
# p t
# =================
# OUTPUT:
# -----------------
# |
# | | |
# | | | | | |
# p t
# <----------->
# sorted
# =================
# 1: find pivot p
# 2: from right side of pivot, find smallest element t > p
# 3: swap p with t and sort elements right in increasing order
arr = list(str(n))
px = -1
for ix in range(len(arr) - 2, -1, -1):
if int(arr[ix]) < int(arr[1 + ix]):
px = ix
break
if px == -1:
return -1
for ix in range(len(arr) - 1, px, -1):
if int(arr[ix]) > int(arr[px]):
arr[px], arr[ix] = arr[ix], arr[px]
arr = arr[0:1 + px] + sorted(arr[1 + px::])
break
num = "".join(map(str, arr))
return int(num) if int(num) < (2 ** 31) else -1