Restore IP Addresses (LeetCode 93): Solution and Explanation
Given a string of digits, insert three dots to split it into four parts so that the result is a valid IPv4 address, and return every way to do that. Each part must be a number from 0 to 255 written without leading zeros, and you may not reorder or drop any digit.
Watch it run step by step
Try your own input and write the code →Intuition
A brute force would try every way to place three dots among the gaps of the string. For a string of length L that is roughly L choose 3 placements, each of which you then check segment by segment. It works for short strings, but it wastes effort on obviously invalid splits, such as a first segment that is already longer than three digits.
The structure of an IP address gives a much tighter search. There are exactly four segments, and each segment is one, two or three characters long. So at every step you have at most three choices, and you make that choice four times. That is a search tree with at most 3⁴ = 81 leaves, no matter how long the input string is.
Backtracking fits this naturally. You walk the string from left to right, try a segment of length 1, 2 or 3, check that it is a legal octet, and recurse on the rest. Two rules decide legality: a segment longer than one character may not start with '0', and its integer value must be at most 255. When you have four segments, the split is valid only if you also used up the entire string.
Approach: Backtracking over segment lengths
- Create
resultand a helperbacktrack(start, path)wherestartis the next unread index andpathholds the segments chosen so far. - If
pathalready has four segments, add'.'.join(path)toresultonly whenstart == len(s), then return either way. - Otherwise loop over
length1, 2 and 3. Stop the loop ifstart + lengthruns past the end of the string. - Slice out
segment. Skip it if it has a leading zero and more than one digit, or ifint(segment)exceeds 255. - Recurse with
start + lengthand a new path that includes the segment. - Start with
backtrack(0, [])and returnresult.
Step-by-step example
s = "25525511135"
- The first segment can be '2', '25' or '255'. The branches for '2' and '25' leave 10 and 9 digits for three segments; they explore a few splits but never consume the whole string, so they record nothing.
- Following '255', the second segment is again '255', leaving '11135' (five digits) for two more segments.
- Choosing '1' as the third segment leaves '1135', and no fourth segment of at most three digits can consume four characters, so that branch adds nothing.
- Choosing '11' leaves '135', a valid octet, so '255.255.11.135' is recorded.
- Choosing '111' leaves '35', which is also valid, so '255.255.111.35' is recorded. The final answer contains exactly these two addresses.
Code: Python, Java, C++
1class Solution:
2 def restoreIpAddresses(self, s: str) -> List[str]:
3 result = []
4
5 def backtrack(start, path):
6 if len(path) == 4:
7 if start == len(s):
8 result.append('.'.join(path))
9 return
10
11 for length in range(1, 4):
12 if start + length > len(s):
13 break
14 segment = s[start:start + length]
15 if (len(segment) > 1 and segment[0] == '0') or int(segment) > 255:
16 continue
17 backtrack(start + length, path + [segment])
18
19 backtrack(0, [])
20 return result1class Solution {
2 public List<String> restoreIpAddresses(String s) {
3 List<String> result = new ArrayList<>();
4 backtrack(s, 0, new ArrayList<>(), result);
5 return result;
6 }
7
8 private void backtrack(String s, int start, List<String> path, List<String> result) {
9 if (path.size() == 4) {
10 if (start == s.length()) {
11 result.add(String.join(".", path));
12 }
13 return;
14 }
15
16 for (int len = 1; len <= 3; len++) {
17 if (start + len > s.length()) break;
18 String segment = s.substring(start, start + len);
19 if ((segment.length() > 1 && segment.charAt(0) == '0') || Integer.parseInt(segment) > 255) continue;
20 path.add(segment);
21 backtrack(s, start + len, path, result);
22 path.remove(path.size() - 1);
23 }
24 }
25}1class Solution {
2public:
3 vector<string> restoreIpAddresses(string s) {
4 vector<string> result;
5 vector<string> path;
6 backtrack(s, 0, path, result);
7 return result;
8 }
9
10 void backtrack(string& s, int start, vector<string>& path, vector<string>& result) {
11 if (path.size() == 4) {
12 if (start == s.size()) {
13 string ip = path[0];
14 for (int i = 1; i < 4; i++) ip += "." + path[i];
15 result.push_back(ip);
16 }
17 return;
18 }
19
20 for (int len = 1; len <= 3; len++) {
21 if (start + len > s.size()) break;
22 string segment = s.substr(start, len);
23 if ((segment.size() > 1 && segment[0] == '0') || stoi(segment) > 255) continue;
24 path.push_back(segment);
25 backtrack(s, start + len, path, result);
26 path.pop_back();
27 }
28 }
29};Time and space complexity
O(1)
The search depth is fixed at four and each level branches at most three ways, so there are at most 81 complete paths, and each segment check works on at most three characters. The running time does not grow with the input length.
O(1)
The recursion depth is at most four and each path holds four short segments. Output strings are not counted as extra space.
Other approaches
Three nested loops (time O(1), space O(1))
Loop over the lengths of the first three segments, each from 1 to 3, derive the fourth from what remains, and validate all four. It does the same 81 checks without recursion and is arguably easier to read for this fixed shape.
Common mistakes
- Accepting segments with leading zeros such as '01' or '00'. Only the single digit '0' is allowed to start with zero.
- Recording a path with four segments before checking that
start == len(s). Leftover digits mean the split is invalid. - Forgetting to stop when
start + lengthexceeds the string length. Python slicing will silently return a shorter segment, which would then be checked with the wrong length. - Not returning after four segments when characters remain. Without that return the recursion keeps adding a fifth segment.
Frequently asked questions
Why is the complexity of Restore IP Addresses constant?
An address always has four segments of one to three digits, so the search tree has at most 3⁴ = 81 leaves regardless of the input. Strings longer than 12 digits are rejected quickly because no path can consume them.
How do I handle leading zeros?
A segment is invalid if it has more than one character and its first character is '0'. The single segment '0' is fine, which is why '0000' produces '0.0.0.0'.
Can I prune strings that are too short or too long?
Yes. If the length is below 4 or above 12, no valid address exists, so you can return an empty list immediately. You can also prune a branch when the remaining characters cannot fit into the remaining segments.
Is this backtracking or brute force?
It is backtracking, which is a structured brute force. It enumerates choices segment by segment and abandons a branch as soon as a segment is invalid, so it never builds the impossible splits in full.