LeetCode #93 Medium

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.

Constraints
  • 1 <= s.length <= 20
  • s consists of digits only.
stringbacktrackingrecursion
Open on LeetCode ↗
02

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 p pieces still to place, the remaining digits must number between p and 3p.

When four pieces use up every digit exactly, join them with dots and record the address.

03

Approach

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def restoreIpAddresses(self, s: str) -> List[str]:
▶3 result, parts = [], []
▶4 
▶5 def place(start):
▶6 left = 4 - len(parts)
▶7 rest = len(s) - start
▶8 if left == 0:
▶9 if rest == 0:
▶10 result.append(".".join(parts))
▶11 return
▶12 if rest < left or rest > 3 * left:
▶13 return
▶14 for size in range(1, min(3, rest) + 1):
▶15 part = s[start:start + size]
▶16 if (size > 1 and part[0] == "0") or int(part) > 255:
▶17 break
▶18 parts.append(part)
▶19 place(start + size)
▶20 parts.pop()
▶21 
▶22 place(0)
▶23 return result
digits010010partsfound6 digits → 4 parts of 1 to 3 digits each
length6
allowed4 to 12
6 digits fit between 4 (four 1-digit parts) and 12 (four 3-digit parts), so the search can start. Parts are chosen from left to right.
digits1010010parts0found"0" is a valid part → place it as part 1
piece0
parts0
0 is one digit, which is always fine. It becomes part 1; the rest of the string is now filled from index 1.
digits12010010parts01found"1" is a valid part → place it as part 2
piece1
parts0 | 1
1 is one digit, which is always fine. It becomes part 2; the rest of the string is now filled from index 2.
digits123010010parts010found"0" is a valid part → place it as part 3
piece0
parts0 | 1 | 0
0 is one digit, which is always fine. It becomes part 3; the rest of the string is now filled from index 3.
digits1234010010parts0100found"0" is a valid part → place it as part 4
piece0
parts0 | 1 | 0 | 0
0 is one digit, which is always fine. It becomes part 4; the rest of the string is now filled from index 4.
digits1234010010parts0100found4 parts but 2 digits left over → drop
digits left2
Four parts are placed, but digits remain. An address must use every digit, so this set of cuts fails.
digits123010010parts010found"01" starts with 0 → stop, longer ones too
piece01
reasonleading zero
A part with more than one digit may not start with 0. Any longer piece from here starts with the same 0, so the loop stops.
digits12010010parts01found"00" starts with 0 → stop, longer ones too
piece00
reasonleading zero
A part with more than one digit may not start with 0. Any longer piece from here starts with the same 0, so the loop stops.
digits12010010parts010found"10" is a valid part → place it as part 2
piece10
parts0 | 10
10 is at most 255 and has no leading zero. It becomes part 2; the rest of the string is now filled from index 3.
digits123010010parts0100found"0" is a valid part → place it as part 3
piece0
parts0 | 10 | 0
0 is one digit, which is always fine. It becomes part 3; the rest of the string is now filled from index 4.
digits1234010010parts01001found"1" is a valid part → place it as part 4
piece1
parts0 | 10 | 0 | 1
1 is one digit, which is always fine. It becomes part 4; the rest of the string is now filled from index 5.
digits1234010010parts01001found4 parts but 1 digit left over → drop
digits left1
Four parts are placed, but digits remain. An address must use every digit, so this set of cuts fails.
digits1234010010parts010010found"10" is a valid part → place it as part 4
piece10
parts0 | 10 | 0 | 10
10 is at most 255 and has no leading zero. It becomes part 4; the rest of the string is now filled from index 6.
digits1234010010parts010010found0.10.0.104 parts use every digit → record 0.10.0.10
address0.10.0.10
found1
All four parts are valid and no digit is left over, so 0.10.0.10 is an answer. Back up to try other cuts.
digits12010010parts010found0.10.0.10"01" starts with 0 → stop, longer ones too
piece01
reasonleading zero
A part with more than one digit may not start with 0. Any longer piece from here starts with the same 0, so the loop stops.
digits12010010parts0100found0.10.0.10"100" is a valid part → place it as part 2
piece100
parts0 | 100
100 is at most 255 and has no leading zero. It becomes part 2; the rest of the string is now filled from index 4.
digits123010010parts01001found0.10.0.10"1" is a valid part → place it as part 3
piece1
parts0 | 100 | 1
1 is one digit, which is always fine. It becomes part 3; the rest of the string is now filled from index 5.
digits1234010010parts010010found0.10.0.10"0" is a valid part → place it as part 4
piece0
parts0 | 100 | 1 | 0
0 is one digit, which is always fine. It becomes part 4; the rest of the string is now filled from index 6.
digits1234010010parts010010found0.10.0.100.100.1.04 parts use every digit → record 0.100.1.0
address0.100.1.0
found2
All four parts are valid and no digit is left over, so 0.100.1.0 is an answer. Back up to try other cuts.
digits123010010parts010010found0.10.0.100.100.1.0"10" is a valid part → place it as part 3
piece10
parts0 | 100 | 10
10 is at most 255 and has no leading zero. It becomes part 3; the rest of the string is now filled from index 6.
digits123010010parts010010found0.10.0.100.100.1.00 digits left for 1 part → cannot fit, back up
digits left0
parts left1
need1 to 3
1 part need between 1 and 3 digits, but 0 remain. No choice from here can work, so skip it without trying.
digits010010partsfound0.10.0.100.100.1.0"01" starts with 0 → stop, longer ones too
piece01
reasonleading zero
A part with more than one digit may not start with 0. Any longer piece from here starts with the same 0, so the loop stops.
digits010010partsfound0.10.0.100.100.1.0search done → 2 addresses
result0.10.0.10, 0.100.1.0
Every way to cut the string has been tried or ruled out. The answer is the list of 2 addresses found.
05

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.

▶1class Solution:
▶2 def restoreIpAddresses(self, s: str) -> List[str]:
▶3 def valid(part):
▶4 return len(part) == 1 or (part[0] != "0" and int(part) <= 255)
▶5 
▶6 n = len(s)
▶7 result = []
▶8 for a in range(1, 4):
▶9 for b in range(a + 1, a + 4):
▶10 for c in range(b + 1, b + 4):
▶11 if c < n <= c + 3:
▶12 parts = [s[:a], s[a:b], s[b:c], s[c:]]
▶13 if all(valid(p) for p in parts):
▶14 result.append(".".join(parts))
▶15 return result
06

Common pitfalls

Checking only the value of a piece

✗ Wrong
if int(part) > 255:
    break
✓ Right
if (size > 1 and part[0] == "0") or int(part) > 255:
    break

int("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

✗ Wrong
if part > "255":
    break
✓ Right
if int(part) > 255:
    break

Strings 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.

07

Edge cases

Too short or too long, e.g. "123" or a 13-digit string

The length test fails on the first call (rest < 4 or rest > 12), so the result is empty with no work done.

All zeros, e.g. "0000"

Every piece longer than one digit starts with 0 and is rejected, so the only address is "0.0.0.0".

08

Complexity

Time
O(1)
Space
O(1)
At most 27 ways to cut, each address at most 15 characters long, so the work is bounded by a constant. If the input length is treated as n, the length test makes every call after the first O(1).
09

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.