Next Greater Number Problem Statement

Given a string S which represents a number, determine the smallest number strictly greater than the original number composed of the same digits. Each digit's frequency from 0-9 must match the original.

Input:

The first line is an integer T, the number of test cases.
Each test case contains one line with the string S.

Output:

For each test case, output the smallest number strictly greater using the same set of digits or -1 if it doesn't exist.

Example:

If given S = '56789', the output should be 56798. Note that 56790 is also greater but uses different digits.

Constraints:

  • 1 ≤ T ≤ 100
  • 1 ≤ len(S) ≤ 104
  • The function has a time limit of 1 second.

Note:

The input string is non-empty with no leading zeros. Implement the function; 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.

  • Iterate from right to left to find the first digit that can be swapped with a smaller digit to make th...read more

Help your peers!
Select
Add answer anonymously...

JPMorgan Chase & Co. Software Developer Intern interview questions & answers

A Software Developer Intern was asked Q. Count Subarrays with Given XOR Problem Statement You are given an array of integ...read more
A Software Developer Intern was asked Q. Kth Largest Number Problem Statement You are given a continuous stream of number...read more
A Software Developer Intern was asked Q. Stack using Two Queues Problem Statement Develop a Stack Data Structure to store...read more

Popular interview questions of Software Developer Intern

A Software Developer Intern was asked Q1. Count Subarrays with Given XOR Problem Statement You are given an array of integ...read more
A Software Developer Intern was asked Q2. Kth Largest Number Problem Statement You are given a continuous stream of number...read more
A Software Developer Intern was asked Q3. Stack using Two Queues Problem Statement Develop a Stack Data Structure to store...read more
JPMorgan Chase & Co. Software Developer Intern 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