Restore IP Addresses
Medium
Topics
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
0 is fine, while 01 is not, even though both are below 255.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
Input: digits = "0000" Output: ["0.0.0.0"] Explanation: A single zero is a legal group; "00" is not.
Example 3
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
- Reject immediately if the length is below 4 or above 12.
- Build the address group by group, tracking the position in the string and how many groups remain.
- 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. - 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.
- 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 comparisonComplexity
- 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)import java.util.*;
class Solution {
public List<String> restoreIpAddresses(String digits) {
text = digits;
total = digits.length();
out = new ArrayList<>();
if (total >= 4 && total <= 12) {
build(0, new ArrayList<>());
}
Collections.sort(out);
return out;
}
private String text;
private int total;
private List<String> out;
private void build(int at, List<String> groups) {
if (groups.size() == 4) {
if (at == total) out.add(String.join(".", groups));
return;
}
for (int size = 1; size <= 3; size++) {
if (at + size > total) break;
String piece = text.substring(at, at + size);
if (size > 1 && piece.charAt(0) == '0') continue;
if (Integer.parseInt(piece) > 255) continue;
groups.add(piece);
build(at + size, groups);
groups.remove(groups.size() - 1);
}
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<string> restoreIpAddresses(string digits) {
int n = (int)digits.size();
vector<string> out;
if (n < 4 || n > 12) return out;
vector<string> groups;
function<void(int)> build = [&](int at) {
if (groups.size() == 4) {
if (at == n) {
string address;
for (size_t i = 0; i < groups.size(); i++) {
if (i) address += ".";
address += groups[i];
}
out.push_back(address);
}
return;
}
for (int size = 1; size <= 3; size++) {
if (at + size > n) break;
string piece = digits.substr(at, size);
if (size > 1 && piece[0] == '0') continue;
if (stoi(piece) > 255) continue;
groups.push_back(piece);
build(at + size);
groups.pop_back();
}
};
build(0);
sort(out.begin(), out.end());
return out;
}
};/**
* @param {string} digits
* @return {string[]}
*/ var restoreIpAddresses = function(digits) {
const n = digits.length;
if (n < 4 || n > 12) return [];
const out = [];
const build = (at, groups) => {
if (groups.length === 4) {
if (at === n) out.push(groups.join("."));
return;
}
for (let size = 1; size <= 3; size++) {
if (at + size > n) break;
const piece = digits.slice(at, at + size);
if (size > 1 && piece[0] === "0") continue;
if (parseInt(piece, 10) > 255) continue;
build(at + size, groups.concat([piece]));
}
};
build(0, []);
return out.sort();
};