Restore IP Addresses

Put three dots into a string of digits in every way that gives a valid IP address.

Given a string s made only of digits, return every valid IP address that can be formed by inserting three dots into it. A valid address has exactly four parts, each a number from 0 to 255, with no leading zeros: "0" is allowed but "01" is not. The digits cannot be reordered or removed, and the addresses can come in any order.

Example 1
Input: s = "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
Example 2
Input: s = "0000"
Output: ["0.0.0.0"]
Example 3
Input: s = "101023"
Output: ["1.0.10.23", "1.0.102.3", "10.1.0.23", "10.10.2.3", "101.0.2.3"]
Solution

The Idea

You have probably seen an address like 192.168.0.1 in a router's settings. That is an IP address: four numbers, each from 0 to 255, joined by dots. Now imagine someone copied one down and lost the dots. All that is left is a row of digits, and the task is to find every way the dots could have been placed.

Take Example 3, 101023. The first part of the address must be one, two or three digits long, so it is 1, 10 or 101. Whichever we pick, the rest of the string has to be split into three more parts in the same way. So the question is: how do we try every split without missing one, and without wasting time on splits that cannot work?

Each split is a short series of choices: the length of the first part, then of the second, then the third and the fourth. Look at the picture below, which shows the first two of those choices for 101023.

Part of the choice tree for 101023. The first part is 1, 10 or 101. Under each, the second part is tried. 1.01 and 101.02 are cut for a leading zero, and 10.102 is cut because 1 digit is left for 2 parts. The other branches lead to the five addresses.

The row labelled "first part" holds the three ways to start: 1, 10 and 101. Below each one, the row labelled "second part" adds the next part. The orange boxes are branches that can be dropped at once. 1.01 and 101.02 have a second part with a leading zero, so no address can start that way.

10.102 is cut for another reason. After it, only the digit 3 is left, but two parts are still missing, and each part needs at least one digit. The blue boxes go on, and in the row labelled "addresses found" they end in exactly the five answers of Example 3.

So the search walks down this tree of choices. It picks a part, goes on to the next part, and when that branch is finished, it takes the part back and tries the next length. Choosing a part, filling the parts after it, and then taking it back to try a longer part from the same digit is called backtracking. Here it pays off because many branches can be cut short, like the orange boxes, long before four parts are chosen.

Solution Approach

Turning the tree into code means settling three things: how to walk through the choices, when a part is valid, and when a branch cannot lead to an address at all.

Walking the choice tree

How does the code move from one row of the tree to the next? A method build gets the position in s where the next part starts, and the list of parts chosen so far. It tries a part of length 1, 2 and 3. For each one, it hands the rest of the digits to a new call of build, which fills the next row of the picture. Because build calls itself once per row, one call for each part it keeps, it is called a recursive method.

When four parts are chosen and every digit is used, the parts are joined with dots and stored. After each call returns, the last part is removed from the list, so the next length starts from the same parts as before.

Checking one part

What makes a part valid? It must be at most 255, and it must not start with 0 unless it is just "0". In the picture, 1.01 fails the second rule.

There is a useful shortcut here. Once a part is invalid, every longer part that starts at the same place is invalid too. A part that starts with 0 still starts with 0 with one more digit, and a number above 255 only grows when a digit is added. So the loop over the lengths 1, 2 and 3 can stop at the first invalid part.

Counting the digits left

When can a whole branch be dropped before any part is checked? Each part still to fill needs at least 1 and at most 3 digits. With two parts missing, the digits left must number between 2 and 6. 10.102 has one digit left for two parts, so it stops.

The same check works in the other direction. In Example 1, the first part 2 leaves 10 digits for three parts, more than 9, so that branch stops at once. A string of more than 12 digits fails in the very first call. Counting the calls to build for Example 1 gives 19 with this check and 71 without it, and a 13-digit string takes 1 call instead of 53.

Java Solution

The method restoreIpAddresses works in these steps:

  1. First, create the list result for the addresses, and call build with start = 0 and an empty list parts.
  2. In build, work out partsLeft, the number of parts still missing, and charsLeft, the digits from start to the end. Return at once if charsLeft is less than partsLeft or more than three times it.
  3. If partsLeft is 0, the check above has already made sure no digit is left over, so join parts with dots, add the address to result, and return.
  4. Otherwise, a loop tries each length len from 1 to 3 and cuts out part, the digits from start to start + len. If isValidPart rejects it, the loop stops with break, because longer parts from the same start are invalid too.
  5. For a valid part, add it to parts, call build for the position after it, and then remove it again so the next length starts clean.
  6. When the first call to build returns, result holds every address, and restoreIpAddresses returns it.

The main method runs the three examples, a string with zeros in many places, a string whose every three-digit part is 256, a string too short for four parts, and one 13 digits long.

Java
import java.util.ArrayList;
import java.util.List;

public class RestoreIPAddresses {

    public static List<String> restoreIpAddresses(String s) {
        List<String> result = new ArrayList<>();
        build(s, 0, new ArrayList<>(), result);
        return result;
    }

    private static void build(String s, int start, List<String> parts, List<String> result) {
        int partsLeft = 4 - parts.size();
        int charsLeft = s.length() - start;
        // each remaining part needs 1 to 3 digits
        if (charsLeft < partsLeft || charsLeft > 3 * partsLeft) {
            return;
        }
        if (partsLeft == 0) {
            result.add(String.join(".", parts));
            return;
        }
        for (int len = 1; len <= 3 && start + len <= s.length(); len++) {
            String part = s.substring(start, start + len);
            if (!isValidPart(part)) {
                break;              // a longer part starting here would be invalid too
            }
            parts.add(part);                         // choose this part
            build(s, start + len, parts, result);    // fill the parts after it
            parts.remove(parts.size() - 1);          // undo the choice, try the next length
        }
    }

    private static boolean isValidPart(String part) {
        if (part.length() > 1 && part.charAt(0) == '0') {
            return false;           // no leading zeros: "01" is not allowed
        }
        return Integer.parseInt(part) <= 255;
    }

    public static void main(String[] args) {
        System.out.println(restoreIpAddresses("25525511135"));
        System.out.println(restoreIpAddresses("0000"));
        System.out.println(restoreIpAddresses("101023"));
        System.out.println(restoreIpAddresses("010010"));
        System.out.println(restoreIpAddresses("256256256256"));
        System.out.println(restoreIpAddresses("123"));
        System.out.println(restoreIpAddresses("1234567890123"));
    }
}

Running it prints:

Output
[255.255.11.135, 255.255.111.35]
[0.0.0.0]
[1.0.10.23, 1.0.102.3, 10.1.0.23, 10.10.2.3, 101.0.2.3]
[0.10.0.10, 0.100.1.0]
[]
[]
[]

Look at the fourth line, from 010010. Both addresses begin with a lone 0, because 01 and 010 have a leading zero. The zeros inside are either alone or at the end of 10 and 100, where they are allowed.

The fifth line is empty because 256 is one more than 255, the largest value a part may have. A split into four parts of three digits gives four 256s, and any other split leaves a part of four or more digits. The last two lines are empty from the digit count: 3 digits cannot fill four parts, and 13 digits are more than four parts can hold.

The leading-zero check matters more than it may seem. Without it, 101023 gives ten addresses instead of five, including 1.0.1.023 and 1.01.0.23, which are not valid.

Complexity

The work is bounded by the address format, not by the length of the input.

  • Time: O(1), because each of the four parts has at most 3 lengths to try, which gives at most 34 = 81 splits, and any string over 12 digits is rejected by the digit count in the first call.
  • Space: O(1) besides the output, because parts never holds more than four strings of up to three digits, and the calls to build go at most five deep.