Next Greater Integer With Disjoint Digits
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Given a positive integer n, determine the smallest integer strictly greater than n whose decimal representation contains none of the digits present in n. If no such integer exists, return -1.
Implement the following function:
def next_number(n: int) -> int:
All values follow standard base-10 conventions:
- Any digit from
0through9that appears at least once innis banned; every other digit may be reused arbitrarily many times in the returned number. - Leading zeros are not permitted, so the leftmost digit of the result must be nonzero (
1–9), though0may appear in later positions when0is not inn. - The answer is allowed to have more digits than
nand may surpass2^31 - 1. - Return
-1if and only if no positive integer abovencan be written exclusively with unbanned digits.
Examples
Example 1
Input: n = 4251
Output: 6000
The digits {1, 2, 4, 5} are banned, leaving {0, 3, 6, 7, 8, 9} available. Every integer in 4252..4999 begins with 4 and every integer in 5000..5999 begins with 5, so the earliest valid candidate is 6000 (using 6 and 0).
Example 2
Input: n = 890
Output: 1111
Here {0, 8, 9} are banned, leaving {1, 2, 3, 4, 5, 6, 7}. Every three-digit number above 890 starts with 8 or 9, so we need four digits; since 0 is also banned, filling all four slots with the smallest remaining digit 1 yields 1111.
Example 3
Input: n = 519283746
Output: -1
Every nonzero digit 1 through 9 appears in n, leaving only 0 unbanned. Because positive integers cannot start with 0, no valid number exists above n.
Constraints
1 <= n <= 2^31 - 1(1 <= n <= 2147483647)- When a valid integer exists, it can exceed
2^31 - 1(use 64-bit or arbitrary-precision integers) and is always strictly below10^11.
Step-by-step walkthrough
Understand the goal and rules
We are given a positive integer
n(1 <= n <= 2^31 - 1, sonhas between1and10digits). Every decimal digit that appears anywhere innis forbidden. We want the smallest positive integer strictly greater thannthat uses only the remaining allowed digits, or-1if no such integer exists.Keep three rules in mind before writing any code:
- Allowed digits can repeat freely: in
n = 4251,0and6are allowed, so6000is valid even though it repeats0three times. - No leading zeros:
0can appear in the middle or at the end of the answer, never as the very first digit. - Answers can grow longer than
nand exceed 32-bit integers: forn = 2147483647(2^31 - 1), the answer is5000000000, and forn = 2034567899, the answer has 11 digits (11111111111). Python integers have unlimited precision automatically, whereas in C++ or Java you would need a 64-bit integer.
- Allowed digits can repeat freely: in
Why counting upward one by one is too slow
The most direct idea is to test
n + 1,n + 2,n + 3, and so on until we hit a number that avoids every digit ofn.That brute-force scan has two fatal problems on large inputs:
- Billions of wasted checks: when
n = 2034567899, the digits0, 2, 3, 4, 5, 6, 7, 8, 9are all forbidden, leaving only1. The next valid integer is11,111,111,111, which is more than9billion numbers away. - Infinite loops when no answer exists: when
n = 519283746, only0is allowed, so no positive integer works at all; counting upward without a careful stopping bound would run forever.
Instead of searching through numbers one by one, we can construct the exact digits of the answer directly.
- Billions of wasted checks: when
Key insight: even the first digit of n is forbidden
Suppose
nhaskdigits. How many digits can the answer have?- Fewer than
kdigits: impossible, because every positive integer with fewer thankdigits is smaller thann. - Exactly
kdigits: look at the very first (leftmost) digit of ak-digit candidate:- It cannot equal
n's first digit, becausen's first digit appears innand is therefore forbidden! - If it is smaller than
n's first digit, the wholek-digit number is smaller thann. - Therefore, a
k-digit answer must start with an allowed digit strictly greater thann's first digit. And the moment the first digit is larger thann's first digit, the number is already guaranteed to be greater thann! To make it as small as possible, we pick the smallest allowed digit aboven's first digit, and fill all remainingk - 1slots with the smallest allowed digit overall (0if0is allowed).
- It cannot equal
- Exactly
k + 1digits: if no allowed digit is greater thann's first digit, nok-digit answer can exist. Any(k + 1)-digit positive integer is automatically greater than everyk-digit integer, so we just build the smallest valid(k + 1)-digit number: put the smallest nonzero allowed digit first, followed bykcopies of the smallest allowed digit overall.
Case A: Same length (k = 4) for n = 4251 Forbidden: {1, 2, 4, 5} Allowed: ['0', '3', '6', '7', '8', '9'] First slot must beat '4' -> '5' is forbidden, so pick '6' Remaining 3 slots take smallest allowed ('0'): [ 6 ][ 0 ][ 0 ][ 0 ] -> 6000 Case B: One digit longer (k + 1 = 4) for n = 890 Forbidden: {0, 8, 9} Allowed: ['1', '2', '3', '4', '5', '6', '7'] No allowed digit beats '8' ('9' is forbidden) -> use 4 slots First slot takes smallest nonzero ('1'), remaining 3 slots take smallest allowed ('1'): [ 1 ][ 1 ][ 1 ][ 1 ] -> 1111Notice why we never need
k + 2or more digits: whenever a(k + 2)-digit valid number exists, at least one nonzero digit is allowed, which means the(k + 1)-digit number already exists and is smaller.- Fewer than
Pin down when the answer is -1
When can even the
(k + 1)-digit number fail to exist? Only when we have no nonzero allowed digit to place in the leading slot! That happens in exactly two situations:ncontains all nine nonzero digits1..9(such asn = 519283746), leaving only'0'allowed — and a positive integer cannot be written with zeros alone.ncontains all ten digits0..9(such asn = 1023456789), leaving no allowed digits at all.
In every other case,
nonzero_allowedhas at least one digit'1'..'9', so Phase 2 is guaranteed to succeed if Phase 1 does not.Helper: collect the allowed digits in sorted order
If we convert
nto its decimal stringn_digits = str(n)and loop through"0123456789"from'0'up to'9', the list of allowed digits comes out sorted in ascending order automatically without needing a separate sort call.def get_allowed_digits(n_digits: str) -> List[str]: """Return all decimal digit characters that do not appear in `n_digits`, sorted '0'..'9'.""" # Scanning "0123456789" in order keeps `allowed` sorted from smallest to largest. allowed: List[str] = [] for digit in "0123456789": if digit not in n_digits: allowed.append(digit) return allowedBuild the two candidates and trace the examples
Now
next_number(n)follows the exact three-step decision tree:- Filter
allowedto getnonzero_allowed; if it is empty, return-1. - Scan
allowedin order for the firstdigit > first_digit. Because ASCII characters'0'through'9'are ordered consecutively,"7" > "6"compares digits numerically, and any digit greater thanfirst_digit(which is at least'1') is automatically nonzero. If found, returnint(digit + smallest_allowed * (num_digits - 1)). - Otherwise, return
int(nonzero_allowed[0] + smallest_allowed * num_digits).
def next_number(n: int) -> int: # n_digits: decimal string of n without leading zeros, e.g. "4251" n_digits = str(n) num_digits = len(n_digits) # allowed: sorted allowed digit characters, e.g. ['0', '3', '6', '7', '8', '9'] allowed = get_allowed_digits(n_digits) # nonzero_allowed: sorted allowed digits from '1'..'9' that can legally start a number nonzero_allowed: List[str] = [] for digit in allowed: if digit != "0": nonzero_allowed.append(digit) if not nonzero_allowed: # Only '0' (or nothing at all) is allowed, so no positive integer can be formed. return -1 # smallest_allowed may be '0', which is valid in every slot after the leading digit. smallest_allowed = allowed[0] first_digit = n_digits[0] # Phase 1: Try a same-length candidate (num_digits digits). # Because first_digit appears in n, it is forbidden. A smaller leading digit would be < n, # so we need the smallest allowed digit strictly greater than first_digit, followed by # the smallest allowed digit in all remaining (num_digits - 1) positions. for digit in allowed: if digit > first_digit: tail_length = num_digits - 1 candidate_str = digit + smallest_allowed * tail_length return int(candidate_str) # Phase 2: No same-length answer exists, so build the smallest (num_digits + 1)-digit number. # Every (num_digits + 1)-digit integer is > n; lead with smallest_nonzero to avoid a leading zero. smallest_nonzero = nonzero_allowed[0] longer_str = smallest_nonzero + smallest_allowed * num_digits return int(longer_str)Let's trace four concrete inputs to see every branch in action:
Input allowed first > n[0]? Result ------------- --------------------------- -------------- ----------- n = 4251 ['0', '3', '6', '7', '8','9'] '6' > '4' "6" + "0"*3 = 6000 n = 890 ['1','2','3','4','5','6','7'] none > '8' "1" + "1"*3 = 1111 n = 9 ['0','1','2'..'8'] none > '9' "1" + "0"*1 = 10 n = 519283746 ['0'] no nonzero! -1- Filter
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def get_allowed_digits(n_digits: str) -> List[str]: """Return all decimal digit characters that do not appear in `n_digits`, sorted '0'..'9'.""" # Scanning "0123456789" in order keeps `allowed` sorted from smallest to largest. allowed: List[str] = [] for digit in "0123456789": if digit not in n_digits: allowed.append(digit) return allowed def next_number(n: int) -> int: # n_digits: decimal string of n without leading zeros, e.g. "4251" n_digits = str(n) num_digits = len(n_digits) # allowed: sorted allowed digit characters, e.g. ['0', '3', '6', '7', '8', '9'] allowed = get_allowed_digits(n_digits) # nonzero_allowed: sorted allowed digits from '1'..'9' that can legally start a number nonzero_allowed: List[str] = [] for digit in allowed: if digit != "0": nonzero_allowed.append(digit) if not nonzero_allowed: # Only '0' (or nothing at all) is allowed, so no positive integer can be formed. return -1 # smallest_allowed may be '0', which is valid in every slot after the leading digit. smallest_allowed = allowed[0] first_digit = n_digits[0] # Phase 1: Try a same-length candidate (num_digits digits). # Because first_digit appears in n, it is forbidden. A smaller leading digit would be < n, # so we need the smallest allowed digit strictly greater than first_digit, followed by # the smallest allowed digit in all remaining (num_digits - 1) positions. for digit in allowed: if digit > first_digit: tail_length = num_digits - 1 candidate_str = digit + smallest_allowed * tail_length return int(candidate_str) # Phase 2: No same-length answer exists, so build the smallest (num_digits + 1)-digit number. # Every (num_digits + 1)-digit integer is > n; lead with smallest_nonzero to avoid a leading zero. smallest_nonzero = nonzero_allowed[0] longer_str = smallest_nonzero + smallest_allowed * num_digits return int(longer_str)✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a combination lock showing the digits of n, where someone puts a piece of tape over every digit that appears in n across all dials on the lock. You want to dial the smallest valid number above n. Normally, to get the next larger number, you keep the left dials untouched and nudge a rightmost dial upward — but here, even the very first (leftmost) digit of n is taped over, so you cannot keep any prefix of n! That observation collapses the entire problem into a simple greedy choice — an algorithm step that picks the best immediate option at each position without needing to backtrack: either you bump the very first dial up to the smallest untaped digit above n's first digit (and set every remaining dial to the smallest untaped digit), or no higher digit exists on that first dial and you add one extra dial on the left.
Why do the obvious approaches fall short? Counting upward n + 1, n + 2, ... and checking each integer's digits can take over 9 billion iterations — for n = 2034567899, only '1' is untaped, so the scan must count all the way to 11,111,111,111 — and it loops forever when n = 519283746 unless you prove a stopping bound anyway. Trying the standard "scan right-to-left to keep a prefix of n" digit-DP or next-permutation style logic is wasted complexity here, because zero digits of n can ever be reused in the prefix.
Let's trace the three examples (n = 4251, n = 890, and n = 519283746) plus n = 9 to see every case step by step:
Example 1: n = 4251 (k = 4 digits)
Forbidden digits : {'1', '2', '4', '5'}
Allowed digits : ['0', '3', '6', '7', '8', '9']
Same-length try : smallest allowed digit > '4' is '6' ('5' is forbidden).
Fill remaining k - 1 = 3 slots with smallest allowed ('0').
Result -> "6" + "000" = 6000
Example 2: n = 890 (k = 3 digits)
Forbidden digits : {'0', '8', '9'}
Allowed digits : ['1', '2', '3', '4', '5', '6', '7']
Same-length try : no allowed digit is > '8' ('9' is forbidden).
(k + 1)-digit try: lead with smallest nonzero ('1') and fill k = 3 slots with
smallest allowed ('1', since '0' is forbidden).
Result -> "1" + "111" = 1111
Extra check: n = 9 (k = 1 digit, '0' allowed)
(k + 1)-digit try: lead with smallest nonzero ('1') to avoid a leading zero
(a '0' in the leftmost position, which is not valid base-10 notation),
then fill k = 1 slot with smallest allowed ('0') -> "10" = 10
Example 3: n = 519283746
Allowed digits : ['0'] -> nonzero_allowed is empty -> Result: -1
Complexity
Let k be the number of decimal digits in n (since n <= 2^31 - 1, k <= 10).
- Time:
O(k)(which isO(1)for 32-bit inputs). Convertingnto ak-character string takesO(k)work, checking which of the10characters"0123456789"appear in that string takes10 * kcomparisons, and building the result string of length at mostk + 1takesO(k)work. - Space:
O(k)(alsoO(1)for 32-bit inputs). We storen_digits(up to10characters), two lists of at most10single-character strings (allowedandnonzero_allowed), and the output string of at most11characters.
Edge cases
- Single-digit
n:n = 1finds'2' > '1'withtail_length = 0and returns2;n = 9finds nothing above'9'and falls through to the 2-digit answer10. - Zero is forbidden: When
0appears inn(such asn = 50orn = 890),smallest_allowedautomatically becomes the smallest allowed nonzero digit ('1'), giving61and1111. - Repeated digits in
n:n = 111only forbids'1', so'0'and'2'remain allowed and the answer is200. - Only
'0'is allowed:n = 519283746leavesallowed = ['0']andnonzero_allowed = [], returning-1because0,00, etc. are not positive integers without leading zeros. - All ten digits forbidden:
n = 1023456789leavesallowed = [], which is caught by the exact sameif not nonzero_allowed:check and returns-1. - Exceeding a 32-bit signed integer (an integer type capped at
2^31 - 1 = 2,147,483,647):n = 2147483647allows'0','5', and'9', returning5000000000;n = 2034567899allows only'1', returning the 11-digit integer11111111111.
Common mistakes
- Trying to preserve a prefix of
n: In the classic "next greater number" problem, you keep as many leading digits ofnas possible. Here, every digit ofnis forbidden, so keeping even the first digit ofnproduces an invalid number. - Using
smallest_allowedas the first digit of the(k + 1)-digit fallback: Forn = 9,smallest_allowedis'0'. Writingsmallest_allowed * 2builds"00"(0), which violates the no-leading-zero rule and is smaller thann. Always lead Phase 2 withsmallest_nonzero. - Only returning
-1whenallowedis completely empty: Forgetting thatallowed == ['0']also yields-1causes a crash or returns0onn = 519283746. - Integer overflow in statically typed languages: Returning a 32-bit
intin C++ or Java overflows on inputs like2147483647(5000000000 > 2^31 - 1); uselong longorlong.
Follow-up questions
- How would the algorithm change if the banned digits came from a separate input set rather than the digits of n itself? Now some digits of
nmight be allowed, so the answer can share a prefix withnin lexicographic order (dictionary order from left to right among equal-length digit strings). First find the lengthpof the longest prefix ofnwhose digits are all allowed; then scanifrommin(p, k - 1)down to0looking for an allowed digit strictly greater thann[i](and nonzero ifi == 0), and if found, returnn[:i] + next_digit + smallest_allowed * (k - i - 1). If no position works, fall back to the(k + 1)-digit numbersmallest_nonzero + smallest_allowed * k(or-1ifnonzero_allowedis empty), running inO(10 * k)time. - How would you find the greatest positive integer strictly below n that shares no digits with n? Reverse the logic: first try a same-length
k-digit number by picking the largest nonzero allowed digit strictly smaller thann's first digit, followed byk - 1copies of the largest allowed digit. If no nonzero allowed digit is smaller thann's first digit, fall back tok - 1copies of the largest allowed digit (which requiresk >= 2and at least one nonzero allowed digit; otherwise return-1). - Does the output ever change if the requirement is relaxed from strictly greater than n to greater than or equal to n? No, nothing changes at all. Because
nis a positive integer, it has at least one digit, and its own digits are forbidden by definition — sonitself is never a valid answer, making>= nand> ncompletely identical.
Follow-up questions
- How would the algorithm change if the banned digits came from a separate input set rather than the digits of n itself?
- How would you find the greatest positive integer strictly below n that shares no digits with n?
- Does the output ever change if the requirement is relaxed from strictly greater than n to greater than or equal to n?
Similar questions
- Minimum-Cost Daily Color Schedule
- Minimum Remaining Count Under Equal-Tier Merges
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance