Skip to main content
LeetCode 556, Medium. Topics: Math, Two Pointers, String. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 22 parametrized pytest cases, and a playground notebook:

Problem

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.

Examples

Constraints

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

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026