Restore IP Addresses
Insert three dots into a digit string to produce every valid IPv4 address.
Open on LeetCode ↗Intuition
Choosing three dot positions blindly creates combinations that can be rejected much earlier. Each IPv4 address contains exactly four segments, each using one to three digits and representing 0 through 255. Backtracking can build one validated segment at a time. Remaining-length bounds prune branches that cannot possibly fill the remaining segment slots.
A string must be divided into a fixed number of locally constrained pieces. That is a natural backtracking partition problem, with strong pruning from minimum and maximum piece lengths.
Approach
Track the next digit and completed segments
The recursive state contains a string index and a list of chosen segments. Success occurs only when four segments use every input digit.
Try segment lengths one through three
Slice each available candidate, reject a multi-digit candidate beginning with zero, and reject numeric values above 255. Append a valid segment, recurse, then remove it to explore the next length.
Prune impossible remaining lengths
Before branching, compare remaining digits with remaining segments. Fewer than one digit per slot or more than three digits per slot makes completion impossible.
Solution
Common pitfalls
Allowing leading zeros
if int(segment) <= 255:
if len(segment) > 1 and segment[0] == '0':
breakIPv4 segments may be zero but cannot contain leading zeroes.
Accepting four segments before consuming all digits
if len(parts) == 4:
result.append('.'.join(parts))if len(parts) == 4:
if index == len(s):
result.append('.'.join(parts))Unused trailing digits make the address invalid.
Trying arbitrarily long segments
for end in range(index + 1, len(s) + 1):
for length in range(1, 4):
An IPv4 segment contains at most three digits.
Edge cases
0Accept it, while rejecting longer forms such as 00 and 01.
Reject that segment and, since longer candidates only grow, stop trying longer lengths at that position.
Remaining-length pruning rejects it immediately.