Reconstruct IPv4 Addresses from Digit Sequence
StringsAuto-graded · 23 test casesLast updated
Parse a string of numeric digits into all possible valid four-part IPv4 address representations.
Given a string s containing only numerical digits, find every valid IPv4 address configuration that can be generated by inserting three period separators (.) into s. You must use all characters in s in their original order.
A valid IPv4 address must consist of exactly four blocks separated by periods, where each block satisfies all of the following rules:
- It contains between 1 and 3 digits.
- Its numeric value falls within the range
0to255inclusive. - It does not have extraneous leading zeros (e.g.,
"0"is permissible, but"00"and"07"are invalid).
Return all generated valid IPv4 address strings sorted in lexicographical (dictionary) order. If no valid IPv4 address can be produced, return an empty list.
Constraints
1 <= len(s) <= 20sconsists exclusively of ASCII digits ('0'through'9').
Examples
Example 1
Input: restore_ip_addresses('25525511135')
Output: ['255.255.11.135', '255.255.111.35']
Example 2
Input: restore_ip_addresses('0000')
Output: ['0.0.0.0']
Example 3
Input: restore_ip_addresses('101023')
Output: ['1.0.10.23', '1.0.102.3', '10.1.0.23', '10.10.2.3', '101.0.2.3']
Hints
Hint 1
Check string length bounds first: a valid IPv4 address requires between 4 and 12 digits.
Hint 2
You can either use backtracking or simple nested loops to partition the string into 4 subsegments of length 1 to 3.
Hint 3
Be careful with leading zeros: a segment longer than 1 character cannot start with '0'.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
An IPv4 address consists of 4 octets, where each octet contains between 1 and 3 digits. Consequently, any input string shorter than 4 characters or longer than 12 characters can immediately be flagged as invalid.
To generate all valid addresses, we can either use recursive backtracking or iterate through all possible length partitions $(a, b, c, d)$ for the four segments:
- Each segment length $a, b, c, d \in {1, 2, 3}$.
- The sum of segment lengths must equal
len(s): $a + b + c + d = N$.
For each length combination:
- Extract the corresponding subsegment strings.
- Validate each subsegment:
- If the subsegment has length greater than 1, it must not start with
'0'(rejecting leading zero cases like"01"or"00"). - Convert the subsegment to an integer and verify that it is $\le 255$.
- If the subsegment has length greater than 1, it must not start with
- If all four subsegments pass validation, join them with
.separators and collect the formatted IP string.
Finally, sort the collected results lexicographically to meet the expected return ordering.
Complexity Analysis
- Time Complexity: $\mathcal{O}(1)$ time. Because there are at most $3^3 = 27$ valid length combinations of the first three segments, the total number of evaluated configurations is strictly bounded. Validating, joining, and sorting at most 27 short strings of length at most 15 takes constant time overall.
- Space Complexity: $\mathcal{O}(1)$ auxiliary space, excluding the memory needed to store the returned list of strings.
Python 3 Reference Solution
from typing import List
def restore_ip_addresses(s: str) -> List[str]:
# A valid IPv4 address requires between 4 and 12 digits total
if not 4 <= len(s) <= 12:
return []
result = []
n = len(s)
# Test all segment length configurations (a, b, c, d)
for a in range(1, 4):
for b in range(1, 4):
for c in range(1, 4):
d = n - a - b - c
if not 1 <= d <= 3:
continue
lengths = (a, b, c, d)
parts = []
start = 0
valid = True
for length in lengths:
part = s[start:start + length]
start += length
# Reject leading zeros in multi-digit parts and numbers exceeding 255
if (length > 1 and part[0] == '0') or int(part) > 255:
valid = False
break
parts.append(part)
if valid:
result.append('.'.join(parts))
return sorted(result)