Restore IP Addresses

Medium

Topics
StringBacktracking

A valid IP address is four numbers separated by dots, where each number is between 0 and 255 and has no leading zero. So "0.1.2.201" is valid and "01.1.2.201" and "192.168.1.312" are not.

Given a string of digits, return every valid IP address that can be formed by inserting three dots, without reordering or removing any digit.

Results are compared as a sorted list, shown space-separated.

Example 1

digits20515223545516171839510
valid cuts255.255.11.135255.255.111.35
one way to cut the digits
The digits have to be cut into exactly four pieces with nothing left over and nothing reordered, and each piece must be a number from 0 to 255 written without a leading zero. That leaves 2 cuts here. The leading-zero rule is what removes most candidates: a piece of 0 is fine, while 01 is not, even though both are below 255.
Every digit must land in some piece — none can be dropped.
Input:  digits = "25525511135"
Output: ["255.255.11.135","255.255.111.35"]
Explanation: Two placements work. Making the first group 2 or 25 leaves too many digits for three groups.

Example 2

digits00010203
valid cuts0.0.0.0
one way to cut the digits
Input:  digits = "0000"
Output: ["0.0.0.0"]
Explanation: A single zero is a legal group; "00" is not.

Example 3

digits100112032435
valid cuts1.0.10.231.0.102.310.1.0.2310.10.2.3101.0.2.3
one way to cut the digits
Input:  digits = "101023"
Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
Explanation: Five placements, and note "1.01.0.23" is absent because 01 has a leading zero.

Constraints

  • 1 <= digits.length <= 20
  • digits consists of digits only
Editorial — intuition, approach, complexity and pitfalls

Intuition

Each of the four groups takes one, two or three digits, so there are only 27 ways to split the string at all. That is small enough to enumerate directly, and the real content of the problem is the two validity rules, which prune most of those 27 before they are finished.

The length rule prunes hardest and costs nothing: four groups of at most three digits can cover at most 12 characters and need at least 4, so any input outside that range has no answers whatsoever. Within a partial split, the digits remaining must likewise be between 1 × groupsLeft and 3 × groupsLeft.

The leading-zero rule is the one that gets forgotten. "0" is a legal group, so a zero cannot simply be skipped — but "01" and "00" are not, which means a group starting with 0 must be exactly one digit long. Example 3 loses two otherwise-plausible answers to this alone.

Approach

  1. Reject immediately if the length is below 4 or above 12.
  2. Build the address group by group, tracking the position in the string and how many groups remain.
  3. For each group try one, two and three digits. Skip a two- or three-digit attempt whose first digit is 0, and skip any whose value exceeds 255.
  4. When four groups have been placed and the string is exactly consumed, record the address. Running out of string early, or having string left over, is a dead end.
  5. Sort the results before returning them.

Walkthrough

digits = "101023"    length 6, so between 4 and 12 -- possible

group 1 = "1"
  group 2 = "0"          (a single zero is legal)
    group 3 = "1"  -> "023" left for one group: starts with 0
                      and is longer than one digit, rejected
    group 3 = "10" -> group 4 = "23"   -> 1.0.10.23
    group 3 = "102"-> group 4 = "3"    -> 1.0.102.3
  group 2 = "01"         rejected, leading zero
  group 2 = "010"        rejected, leading zero
group 1 = "10"
  group 2 = "1" -> group 3 = "0", group 4 = "23"  -> 10.1.0.23
  group 2 = "10"-> group 3 = "2", group 4 = "3"   -> 10.10.2.3
group 1 = "101"
  group 2 = "0" -> group 3 = "2", group 4 = "3"   -> 101.0.2.3

five answers, sorted for comparison

Complexity

  • Time — O(1): at most 3^4 = 81 splits to consider, whatever the input, because the length is capped at 12 by the first check.
  • Space — O(1): the recursion is four deep and the answer list is bounded.

Common Pitfalls

  • Allowing a leading zero. "01" is not 1, it is invalid — and "0" on its own is valid, so zeros cannot just be banned.
  • Checking the 255 bound on the number but not the string length, so "0000" yields "00.0.0.0".
  • Accepting an address before the string is fully consumed. Four valid groups that leave digits behind are not an answer.
  • Omitting the length check and recursing on a 20-digit input, which cannot possibly succeed.

Full Solution — all languages

class Solution:
    def restoreIpAddresses(self, digits):
        n = len(digits)
        if n < 4 or n > 12:
            return []
        out = []

        def build(at, groups):
            if len(groups) == 4:
                if at == n:
                    out.append(".".join(groups))
                return
            for size in (1, 2, 3):
                if at + size > n:
                    break
                piece = digits[at:at + size]
                if size > 1 and piece[0] == "0":
                    continue
                if int(piece) > 255:
                    continue
                build(at + size, groups + [piece])

        build(0, [])
        return sorted(out)
SensAI
Beta
Tap the mic to stop voice mode