Restore IP Addresses (LeetCode 93): Solution and Explanation

Medium
String
Backtracking

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Create result and a helper backtrack(start, path) where start is the next unread index and path holds the segments chosen so far.
  2. If path already has four segments, add '.'.join(path) to result only when start == len(s), then return either way.
  3. Otherwise loop over length 1, 2 and 3. Stop the loop if start + length runs past the end of the string.
  4. Slice out segment. Skip it if it has a leading zero and more than one digit, or if int(segment) exceeds 255.
  5. Recurse with start + length and a new path that includes the segment.
  6. Start with backtrack(0, []) and return result.

Step-by-step example

s = "25525511135"
  1. 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.
  2. Following '255', the second segment is again '255', leaving '11135' (five digits) for two more segments.
  3. 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.
  4. Choosing '11' leaves '135', a valid octet, so '255.255.11.135' is recorded.
  5. 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 result

Time and space complexity

Time

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.

Space

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 + length exceeds 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.