Split a digit string into four valid IP parts: try a 1, 2 or 3 digit chunk, recurse, and back up when a part tops 255 or has a leading zero.
▼The problem
LeetCode 93 (Medium). Given a string of digits, return every valid IPv4 address that can be made by inserting three dots: four parts, each from 0 to 255, no leading zeros (unless the part is exactly 0), every digit used, in order.
Examples (LeetCode's): "25525511135" → ["255.255.11.135", "255.255.111.35"] (the walkthrough); "0000" → ["0.0.0.0"].
The solution
def restore_ip_addresses(s):
res = []
def go(i, parts):
left = 4 - len(parts)
if not left <= len(s) - i <= 3 * left:
return
if left == 0:
res.append('.'.join(parts))
return
for k in range(1, 4):
part = s[i:i + k]
if len(part) < k or (k > 1 and part[0] == '0') or int(part) > 255:
break
go(i + k, parts + [part])
go(0, [])
return resTranscript
Restore IP Addresses. You get a string of digits. Insert three dots to make a valid IP address: four parts, each zero to two fifty-five, no leading zeros, every digit used in order. Find every address you can make.
Take two five five, two five five, one one one, three five. It splits two ways: two fifty-five, two fifty-five, eleven, one thirty-five; or one eleven, then thirty-five. Four zeros gives just one address.
The naive way: try every spot for the three dots, and check each address. Eleven digits leave ten gaps, so there are one hundred twenty ways to place the dots. Only two pass. Most of those tries were doomed from the first cut.
Better: cut one part at a time, from the left. The next part takes one, two or three digits. A leading zero, or a value over two fifty-five, makes it bad, and any longer part from there is bad too, so stop.
And prune early. Each part left needs one to three digits. Cutting just two first leaves ten digits for three parts, but three parts hold nine at most: dead before it starts. When four parts use every digit, record the address.
Now the first example. Two is pruned. Twenty-five lasts one level, then every cut fails. Two fifty-five survives. After it, two is pruned, twenty-five fails a level down, and two fifty-five survives again. Then eleven and one thirty-five, or one eleven and thirty-five: two addresses, in nineteen calls.
In code, the fit check comes first. With no parts left, it allows no digits left, so the address is complete: record it. Otherwise, try each length, break at a bad part, and recurse on the rest.
Four parts, at most three lengths each: at most eighty-one paths. A valid input has at most twelve digits, so the time is constant, and the recursion is only four deep, so the space is constant too.
Cut up to three digits, skip bad parts, prune what can't fit. That's Restore IP Addresses.