Find the Next Greater Number with the Same Set of Digits

Given a string S that represents a number, determine the smallest number that is strictly greater than the original number and has the same set of digits. The frequency of each digit from 0 to 9 should remain unchanged.

Example:

Input:
S = "56789"
Output:
56798
Explanation:

Although 56790 is greater than 56789, it includes a '0' which is not in the original number and misses the digit '8'.

Constraints:

  • 1 ≤ T ≤ 100
  • 1 ≤ len(S) ≤ 104
  • The number S has no leading zeros.

Input:

The first line contains an integer T, the number of test cases.
The following T lines each contain a string S representing a number.

Output:

For each test case, output the smallest number greater than S with the same set of digits.

Note:

If no such number exists, return -1. Implementation of function is required, printing is handled elsewhere.

AnswerBot
4mo

The task is to find the smallest number greater than the given number with the same set of digits.

  • Sort the digits of the number in descending order.

  • Find the first digit from the right that is smaller ...read more

Help your peers!
Select
Add answer anonymously...

Snapdeal Software Engineer interview questions & answers

A Software Engineer was asked Q. Given a binary tree, return the vertical sum of the tree.
A Software Engineer was asked Q. How many rectangles/squares are there on a chessboard?
A Software Engineer was asked Q. How would you dynamically calculate the top 10 most frequent words on Facebook w...read more

Popular interview questions of Software Engineer

A Software Engineer was asked Q1. Given an array, find a pair of elements.
A Software Engineer was asked Q2. Given a binary tree, return the vertical sum of the tree.
A Software Engineer was asked Q3. How many rectangles/squares are there on a chessboard?
Snapdeal Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits