tinycodinglm / cp /cp-10061.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
1.7 kB
opencode trace
System You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

User

Problem: Next Greater Element III (Difficulty: Medium)
Tags: Math, Two Pointers, String

Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1.
Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1.

Example 1:
Input: n = 12
Output: 21

Example 2:
Input: n = 21
Output: -1

Constraints:

  • 1 <= n <= 2^31 - 1
Assistant

Time: O(logn) = O(1)

Space: O(logn) = O(1)

class Solution(object):
def nextGreaterElement(self, n):
"""
:type n: int
:rtype: int
"""
digits = map(int, list(str(n)))
k, l = -1, 0
for i in range(len(digits) - 1):
if digits[i] < digits[i + 1]:
k = i

markdown
if k == -1:
        digits.reverse()
        return -1

    for i in range(k + 1, len(digits)):
        if digits[i] > digits[k]:
            l = i

    digits[k], digits[l] = digits[l], digits[k]
    digits[k + 1:] = digits[:k:-1]
    result = int("".join(map(str, digits)))
    return -1 if result >= 0x7FFFFFFF else result