Restore IP Addresses
Put three dots into a string of digits in every way that gives a valid IP address.
Given a string s"0""01"
Example 1
Output: ["255.255.11.135", "255.255.111.35"]
Example 2
Output: ["0.0.0.0"]
Example 3
Output: ["1.0.10.23", "1.0.102.3", "10.1.0.23", "10.10.2.3", "101.0.2.3"]
The Idea
You have probably seen an address like 192.168.0.1
Take Example 3, 101023110101
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
The row labelled "first part" holds the three ways to start: 1101011.01101.02
10.102
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 buildsbuildbuild
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"1.01
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
The same check works in the other direction. In Example 1, the first part 2build
Java Solution
The method restoreIpAddresses
- First, create the list
for the addresses, and callresult withbuild = 0 and an empty liststart .parts - In
, work outbuild , the number of parts still missing, andpartsLeft , the digits fromcharsLeft to the end. Return at once ifstart is less thancharsLeft or more than three times it.partsLeft - If
is 0, the check above has already made sure no digit is left over, so joinpartsLeft with dots, add the address toparts , and return.result - Otherwise, a loop tries each length
from 1 to 3 and cuts outlen , the digits frompart tostart . Ifstart + len rejects it, the loop stops withisValidPart , because longer parts from the same start are invalid too.break - For a valid
, add it topart , callparts for the position after it, and then remove it again so the next length starts clean.build - When the first call to
returns,build holds every address, andresult returns it.restoreIpAddresses
The main
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:
[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 01001000101010100
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, 1010231.0.1.0231.01.0.23
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
never holds more than four strings of up to three digits, and the calls toparts go at most five deep.build