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 0 through 9 that appears at least once in n is 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), though 0 may appear in later positions when 0 is not in n.
  • The answer is allowed to have more digits than n and may surpass 2^31 - 1.
  • Return -1 if and only if no positive integer above n can 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 below 10^11.

Step-by-step walkthrough

  1. Understand the goal and rules

    We are given a positive integer n (1 <= n <= 2^31 - 1, so n has between 1 and 10 digits). Every decimal digit that appears anywhere in n is forbidden. We want the smallest positive integer strictly greater than n that uses only the remaining allowed digits, or -1 if no such integer exists.

    Keep three rules in mind before writing any code:

    • Allowed digits can repeat freely: in n = 4251, 0 and 6 are allowed, so 6000 is valid even though it repeats 0 three times.
    • No leading zeros: 0 can appear in the middle or at the end of the answer, never as the very first digit.
    • Answers can grow longer than n and exceed 32-bit integers: for n = 2147483647 (2^31 - 1), the answer is 5000000000, and for n = 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.
  2. 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 of n.

    That brute-force scan has two fatal problems on large inputs:

    • Billions of wasted checks: when n = 2034567899, the digits 0, 2, 3, 4, 5, 6, 7, 8, 9 are all forbidden, leaving only 1. The next valid integer is 11,111,111,111, which is more than 9 billion numbers away.
    • Infinite loops when no answer exists: when n = 519283746, only 0 is 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.

  3. Key insight: even the first digit of n is forbidden

    Suppose n has k digits. How many digits can the answer have?

    • Fewer than k digits: impossible, because every positive integer with fewer than k digits is smaller than n.
    • Exactly k digits: look at the very first (leftmost) digit of a k-digit candidate:
      • It cannot equal n's first digit, because n's first digit appears in n and is therefore forbidden!
      • If it is smaller than n's first digit, the whole k-digit number is smaller than n.
      • Therefore, a k-digit answer must start with an allowed digit strictly greater than n's first digit. And the moment the first digit is larger than n's first digit, the number is already guaranteed to be greater than n! To make it as small as possible, we pick the smallest allowed digit above n's first digit, and fill all remaining k - 1 slots with the smallest allowed digit overall (0 if 0 is allowed).
    • Exactly k + 1 digits: if no allowed digit is greater than n's first digit, no k-digit answer can exist. Any (k + 1)-digit positive integer is automatically greater than every k-digit integer, so we just build the smallest valid (k + 1)-digit number: put the smallest nonzero allowed digit first, followed by k copies 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 ]            ->  1111
    

    Notice why we never need k + 2 or 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.

  4. 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:

    1. n contains all nine nonzero digits 1..9 (such as n = 519283746), leaving only '0' allowed — and a positive integer cannot be written with zeros alone.
    2. n contains all ten digits 0..9 (such as n = 1023456789), leaving no allowed digits at all.

    In every other case, nonzero_allowed has at least one digit '1'..'9', so Phase 2 is guaranteed to succeed if Phase 1 does not.

  5. Helper: collect the allowed digits in sorted order

    If we convert n to its decimal string n_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 allowed
    
  6. Build the two candidates and trace the examples

    Now next_number(n) follows the exact three-step decision tree:

    1. Filter allowed to get nonzero_allowed; if it is empty, return -1.
    2. Scan allowed in order for the first digit > first_digit. Because ASCII characters '0' through '9' are ordered consecutively, "7" > "6" compares digits numerically, and any digit greater than first_digit (which is at least '1') is automatically nonzero. If found, return int(digit + smallest_allowed * (num_digits - 1)).
    3. 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
    
  7. 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 is O(1) for 32-bit inputs). Converting n to a k-character string takes O(k) work, checking which of the 10 characters "0123456789" appear in that string takes 10 * k comparisons, and building the result string of length at most k + 1 takes O(k) work.
  • Space: O(k) (also O(1) for 32-bit inputs). We store n_digits (up to 10 characters), two lists of at most 10 single-character strings (allowed and nonzero_allowed), and the output string of at most 11 characters.

Edge cases

  • Single-digit n: n = 1 finds '2' > '1' with tail_length = 0 and returns 2; n = 9 finds nothing above '9' and falls through to the 2-digit answer 10.
  • Zero is forbidden: When 0 appears in n (such as n = 50 or n = 890), smallest_allowed automatically becomes the smallest allowed nonzero digit ('1'), giving 61 and 1111.
  • Repeated digits in n: n = 111 only forbids '1', so '0' and '2' remain allowed and the answer is 200.
  • Only '0' is allowed: n = 519283746 leaves allowed = ['0'] and nonzero_allowed = [], returning -1 because 0, 00, etc. are not positive integers without leading zeros.
  • All ten digits forbidden: n = 1023456789 leaves allowed = [], which is caught by the exact same if 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 = 2147483647 allows '0', '5', and '9', returning 5000000000; n = 2034567899 allows only '1', returning the 11-digit integer 11111111111.

Common mistakes

  • Trying to preserve a prefix of n: In the classic "next greater number" problem, you keep as many leading digits of n as possible. Here, every digit of n is forbidden, so keeping even the first digit of n produces an invalid number.
  • Using smallest_allowed as the first digit of the (k + 1)-digit fallback: For n = 9, smallest_allowed is '0'. Writing smallest_allowed * 2 builds "00" (0), which violates the no-leading-zero rule and is smaller than n. Always lead Phase 2 with smallest_nonzero.
  • Only returning -1 when allowed is completely empty: Forgetting that allowed == ['0'] also yields -1 causes a crash or returns 0 on n = 519283746.
  • Integer overflow in statically typed languages: Returning a 32-bit int in C++ or Java overflows on inputs like 2147483647 (5000000000 > 2^31 - 1); use long long or long.

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 n might be allowed, so the answer can share a prefix with n in lexicographic order (dictionary order from left to right among equal-length digit strings). First find the length p of the longest prefix of n whose digits are all allowed; then scan i from min(p, k - 1) down to 0 looking for an allowed digit strictly greater than n[i] (and nonzero if i == 0), and if found, return n[:i] + next_digit + smallest_allowed * (k - i - 1). If no position works, fall back to the (k + 1)-digit number smallest_nonzero + smallest_allowed * k (or -1 if nonzero_allowed is empty), running in O(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 than n's first digit, followed by k - 1 copies of the largest allowed digit. If no nonzero allowed digit is smaller than n's first digit, fall back to k - 1 copies of the largest allowed digit (which requires k >= 2 and 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 n is a positive integer, it has at least one digit, and its own digits are forbidden by definition — so n itself is never a valid answer, making >= n and > n completely identical.

Follow-up questions

Similar questions

More Elevenlabs interview questions

All 3 Elevenlabs questions →