Java String Program · S46
Restore IP Addresses in Java
Insert three dots into a string of digits to make a valid IPv4 address. Each of the four parts must be between 0 and 255 and must not have a leading zero.
Problem Statement
Given a string of digits, return every valid IPv4 address that can be formed by inserting exactly three dots. All digits must be used, in their original order.
A part is valid when it is between 0 and 255 and has no leading zero, so 0 is allowed but 01 and 256 are not.
Input/Output Examples
"1111"Output[1.1.1.1]Explanation: four single-digit parts."010010"Output[0.10.0.10, 0.100.1.0]Explanation: parts such as 01 or 010 are rejected."19216801"Output[19.216.80.1, 192.16.80.1, 192.168.0.1]Explanation: three different splits produce valid parts.Visual Explanation
- Part 1choices119192try lengths 1, 2, 3
- Part 2after 192116168each part must be 0-255
- Parts 3, 4after 16801"01" is rejected leading zero
- One result192.168.0.1
"19216801": each step chooses a length of 1, 2 or 3 for the next part, and invalid parts (such as 01) end that branch.The search also stops early when the remaining digits cannot fill the remaining parts, because every part needs between 1 and 3 digits. That pruning keeps the search tiny.
Approaches
Both approaches try every way to choose the part lengths. Backtracking prunes as it goes; the loop version enumerates the lengths directly.
Approach 1: Backtracking (Recommended)
Idea: choose 1 to 3 digits for the next part, check it, recurse for the remaining parts, then undo the choice.
- Stop if the remaining digits cannot fill the remaining parts (fewer than 1 or more than 3 each).
- When four parts are chosen and no digits remain, record the address.
- Otherwise, try lengths 1, 2 and 3 for the next part, recursing on valid parts.
Time: O(1) · Space: O(1). At most 34 = 81 ways to split, whatever the input.
Approach 2: Three Nested Loops
Idea: choose the lengths of the first three parts with three loops; the fourth length is whatever is left.
- Loop
a,bandcfrom 1 to 3. - Compute
d = n - a - b - cand skip it unless it is between 1 and 3. - Cut the four parts and keep the address if all four are valid.
Time: O(1) · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Backtracking (Recommended)
The pruning check at the top rejects strings shorter than 4 or longer than 12 digits immediately.
import java.util.ArrayList;
import java.util.List;
public class IpBacktrack {
// Picks 1, 2 or 3 digits for each of the four parts; each part must be 0-255 without leading zeros
static List<String> restore(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 remaining = s.length() - start;
int partsLeft = 4 - parts.size();
if (remaining < partsLeft || remaining > 3 * partsLeft) {
return; // too few or too many digits left
}
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 (isValid(part)) {
parts.add(part);
build(s, start + len, parts, result);
parts.remove(parts.size() - 1);
}
}
}
static boolean isValid(String part) {
if (part.length() > 1 && part.charAt(0) == '0') {
return false;
}
return Integer.parseInt(part) <= 255;
}
public static void main(String[] args) {
String[] inputs = {"1111", "010010", "19216801", "000"};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> " + restore(s));
}
}
}
"1111" -> [1.1.1.1] "010010" -> [0.10.0.10, 0.100.1.0] "19216801" -> [19.216.80.1, 192.16.80.1, 192.168.0.1] "000" -> []
Time complexity: O(1) · Space complexity: O(1).
Approach 2: Three Nested Loops
Very direct, because an IPv4 address always has exactly four parts.
import java.util.ArrayList;
import java.util.List;
public class IpNestedLoops {
// Tries every combination of part lengths (1 to 3 each) whose total equals the string length
static List<String> restore(String s) {
List<String> result = new ArrayList<>();
int n = s.length();
for (int a = 1; a <= 3; a++) {
for (int b = 1; b <= 3; b++) {
for (int c = 1; c <= 3; c++) {
int d = n - a - b - c;
if (d < 1 || d > 3) {
continue;
}
String p1 = s.substring(0, a);
String p2 = s.substring(a, a + b);
String p3 = s.substring(a + b, a + b + c);
String p4 = s.substring(a + b + c);
if (isValid(p1) && isValid(p2) && isValid(p3) && isValid(p4)) {
result.add(p1 + "." + p2 + "." + p3 + "." + p4);
}
}
}
}
return result;
}
static boolean isValid(String part) {
if (part.length() > 1 && part.charAt(0) == '0') {
return false;
}
return Integer.parseInt(part) <= 255;
}
public static void main(String[] args) {
String[] inputs = {"1111", "010010", "19216801", "000"};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> " + restore(s));
}
}
}
"1111" -> [1.1.1.1] "010010" -> [0.10.0.10, 0.100.1.0] "19216801" -> [19.216.80.1, 192.16.80.1, 192.168.0.1] "000" -> []
Time complexity: O(1) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Backtracking | O(1) | O(1) |
| Three Nested Loops | O(1) | O(1) |
Every address has four parts of 1 to 3 digits, so at most 81 splits are checked and the input can have at most 12 useful digits. Both approaches therefore run in constant time.
Interview Tips and Recommended Approach
- Validate leading zeros.
"0"is fine, but"00"and"01"are not. - Check the value, not just the length. A three-digit part must also be at most 255.
- Prune by remaining length. It turns many hopeless branches into one comparison.
- Explain why the complexity is constant. The number of parts and digits per part are both fixed.
Recommended Approach: Backtracking
Why: it applies the general backtracking pattern with clear pruning, so the same code structure works if the rules change, for example for a different number of parts.