File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
December_LeetCode_Challenge Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ Given a positive integer n , find the smallest integer which has
2+ exactly the same digits existing in the integer n and is greater in value than n .
3+ If no such positive integer exists , return - 1.
4+
5+ Note that the returned integer should fit in 32 - bit integer ,
6+ if there is a valid answer but it does not fit in 32 - bit integer , return - 1.
7+
8+ Example 1 :
9+ Input : n = 12
10+ Output : 21
11+
12+ Example 2 :
13+ Input : n = 21
14+ Output : - 1
15+
16+ Constraints :
17+ 1 <= n <= 231 - 1
18+
19+
20+ # O(n) Time and O(1) Space
21+ class Solution :
22+ def nextGreaterElement (self , n : int ) -> int :
23+
24+ digit_count = [0 for i in range (10 )]
25+
26+ current_digit = - 1
27+ prev_digit = - 1
28+
29+ while n > 0 :
30+
31+ current_digit = n % 10
32+ n = n // 10
33+ digit_count [current_digit ] += 1
34+
35+ if prev_digit > current_digit :
36+
37+ digit = current_digit + 1
38+
39+ while digit_count [digit ] == 0 :
40+ digit += 1
41+
42+ digit_count [digit ] -= 1
43+
44+ n = n * 10 + digit
45+
46+ for i in range (10 ):
47+ while digit_count [i ] > 0 :
48+ n = n * 10 + i
49+ digit_count [i ] -= 1
50+
51+ return n if n < (2 ** 31 )- 1 else - 1
52+
53+ prev_digit = current_digit
54+
55+ return - 1
You can’t perform that action at this time.
0 commit comments