Restore IP Addresses
Restore IP Addresses is LeetCode 93 (Medium). Given a string s of digits, return every valid IPv4 address you can make by inserting dots into it, in any order. You may not reorder or delete digits.
A valid address is four whole numbers joined by dots, where each number:
- is between 0 and 255,
- has no leading zero, so
"0"is fine but"01"and"00"are not.
s can have up to 20 digits, but only lengths 4 to 12 can give any answer.
- 1 <= s.length <= 20
- s consists of digits only.
Intuition
An address is the string cut into four pieces, and each piece is 1, 2 or 3 digits long. Once three pieces are chosen, the fourth is whatever is left, so there are at most 3 × 3 × 3 = 27 ways to cut, and most of them fail early.
Choose the pieces from left to right, and back up the moment a piece is invalid or the digits left cannot fill the pieces left.
- Piece test: a piece is valid when it is one digit, or it does not start with 0 and is at most 255.
- Length test: with
ppieces still to place, the remaining digits must number betweenpand3p.
When four pieces use up every digit exactly, join them with dots and record the address.
Approach
Two ways to solve it
Place pieces left to right and undo on failure.
- Prunes early: a bad first piece skips everything after it.
- Generalises to other split-a-string problems.
Pick the end of the first, second and third piece, each 1 to 3 digits after the last cut, and test all four pieces.
- No recursion, easy to read.
- Builds some pieces it could have skipped.
Backtracking stops a bad path after its first invalid piece. Trying every set of three cut positions is shorter to write and checks the same at most 27 candidates.
Track the pieces chosen so far
Keep a list parts and a recursive place(start) that fills the next piece from index start. A list makes undoing a choice a single pop.
Stop when four pieces are placed
If parts has four pieces, record ".".join(parts) only when start is the end of s. Leftover digits mean the cuts were too short, and that path is dropped.
Prune by length
With left pieces to place and rest digits remaining, return at once if rest < left or rest > 3 * left. This also rejects any s longer than 12 or shorter than 4 on the first call.
Try piece lengths 1, 2, 3
Take the next 1, 2 or 3 digits. If the piece starts with a 0 and is longer than one digit, or is above 255, stop the loop: a longer piece keeps the same leading 0 and only grows. Otherwise append it, recurse, and pop it.
Code in Python, C++ and Java
Three nested loops over cut positions
The three dots sit after positions a < b < c. Each loop moves its cut 1 to 3 digits past the previous one, and the last piece must also be 1 to 3 digits long, so c < n <= c + 3.
Common pitfalls
Checking only the value of a piece
if int(part) > 255:
breakif (size > 1 and part[0] == "0") or int(part) > 255:
breakint("01") is 1, so a piece with a leading zero passes. For s = "01000" the only answer is "0.10.0.0", but this check also returns "01.0.0.0", "0.1.00.0" and "0.1.0.00".
Comparing pieces as strings
if part > "255":
breakif int(part) > 255:
breakStrings compare letter by letter, so "3" > "255" is true because '3' comes after '2'. For s = "3333" every first piece is rejected and the answer "3.3.3.3" is lost.
Edge cases
The length test fails on the first call (rest < 4 or rest > 12), so the result is empty with no work done.
Every piece longer than one digit starts with 0 and is rejected, so the only address is "0.0.0.0".
Complexity
Restore IP Addresses FAQ
How do I check whether one string is already a valid IPv4 address?
Split it on dots. It is valid when there are exactly four pieces and each one passes the piece test: non-empty, digits only, no leading zero unless it is "0", and at most 255.
Can there be more than one answer for the same string?
Yes. "101023" gives five: 1.0.10.23, 1.0.102.3, 10.1.0.23, 10.10.2.3 and 101.0.2.3. Different cut positions can all pass the piece test, so the function returns a list.