IPv4 Address Checker and Builder
StringsAuto-graded · 23 test casesLast updated
Tests string parsing, validation rules, and backtracking to check and generate valid IPv4 addresses from digit strings.
You are building a network utility that works with IPv4 addresses in two formats: standard dotted-decimal notation and raw digit strings.
Implement a function that performs three related tasks:
Task 1: Verify Dotted-Decimal Format
Given a string in dotted-decimal format, determine whether it represents a valid IPv4 address.
A valid IPv4 address consists of:
- Exactly four numeric segments separated by three periods
- Each segment must be a decimal number between 0 and 255 (inclusive)
- No segment may have leading zeros, except when the segment is exactly "0"
- Segments contain only digits (no signs, spaces, or other characters)
Task 2: Check Restoration Possibility
Given a string containing only digits (no periods), determine whether it is possible to insert exactly three periods to form a valid IPv4 address under the same rules.
Task 3: Generate All Valid Restorations
Given the same digit-only string, produce every distinct valid IPv4 address that can be formed by inserting three periods. Return the addresses in lexicographically sorted order.
Function Signature
Your function receives two parameters:
dotted_format: a string to validate as dotted-decimal IPv4 (Task 1)digit_string: a string of digits to restore into IPv4 addresses (Tasks 2 and 3)
Return a dictionary with three keys:
'is_valid': boolean indicating whetherdotted_formatis valid'can_restore': boolean indicating whetherdigit_stringcan form any valid IPv4'restored': list of all valid IPv4 addresses fromdigit_string, sorted lexicographically
Constraints
1 ≤ len(digit_string) ≤ 12digit_stringcontains only digit characters ('0'-'9')dotted_formatmay contain any characters- Each segment of a valid IPv4 must be in the range [0, 255]
- Leading zeros are forbidden except for the value "0" itself
Examples
Example 1
Input: ipv4_check_and_restore('255.255.11.135', '25525511135')
Output: {'is_valid': True, 'can_restore': True, 'restored': ['255.255.11.135', '255.255.111.35']}
Example 2
Input: ipv4_check_and_restore('-1.255.11.135', '00025555')
Output: {'is_valid': False, 'can_restore': False, 'restored': []}
Example 3
Input: ipv4_check_and_restore('01.2.3.4', '123')
Output: {'is_valid': False, 'can_restore': False, 'restored': []}
Hints
Hint 1
Define a helper function to validate whether a single segment meets all the octet rules, then reuse it across all three tasks.
Hint 2
For restoration, use depth-first search to try all ways of partitioning the digit string into four segments, where each segment is 1-3 characters long.
Hint 3
Prune impossible branches early: if k segments remain and r characters are left, you need k ≤ r ≤ 3k to complete a valid address.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution centers on a single validation function for individual IPv4 segments (octets). This helper checks that a segment:
- Is non-empty and contains only digits
- Has no leading zeros unless it equals exactly "0"
- Represents a value no greater than 255
With this shared check, each task becomes straightforward:
Task 1 (Validation): Split the dotted string on periods. The address is valid if and only if the split produces exactly four parts and each part passes the segment validator.
Tasks 2 & 3 (Restoration): Use backtracking to explore all ways of dividing the digit string into four segments. At each step, try taking the next 1, 2, or 3 characters as a segment. Only recurse if that segment is valid. Collect a complete address when exactly four valid segments have consumed the entire string.
To avoid wasted work, prune branches where success is impossible: if k segments remain to be placed and r characters remain in the string, we need k ≤ r ≤ 3k (since each segment uses 1-3 characters). If this fails, abandon the branch.
Task 2's answer derives from Task 3: restoration is possible exactly when at least one valid address can be built. Computing the full list once and checking len(restorations) > 0 keeps the two results consistent without redundant searches.
Why It Works
Dotted validation: Splitting on '.' naturally enforces "exactly three dots" (four parts) and rejects malformed input like trailing dots, consecutive dots, or missing segments. Any character that isn't a digit or dot ends up inside a segment and fails the isdigit() check.
Restoration completeness: Every valid IPv4 formed from the digit string corresponds to choosing four consecutive substrings of lengths in {1, 2, 3} that cover the entire input. The backtracking explores every such partition, so no valid address is missed. The recursion only accepts a path when all four segments are valid and the entire string has been consumed, so every result is correct. Different partitions produce different strings, ensuring no duplicates.
Pruning correctness: The bounds check only eliminates branches that cannot possibly lead to a solution. It never discards a valid address.
Complexity
Time:
- Validation: O(n) where n is the length of the dotted string (one split and constant work per character).
- Restoration: The digit string is at most 12 characters, and the search tree has depth 4 with branching factor 3, giving at most 3⁴ = 81 leaves. Effectively O(1). More generally, O(3⁴ · L) where L is the cost of validating and copying each segment.
- Sorting the results is O(m log m) where m is the number of restorations, but m is bounded by a small constant.
Space:
- O(n) for the split in validation.
- O(1) for the recursion stack (maximum depth 4) and the output list (bounded by a small constant).
Solution Code
def ipv4_check_and_restore(dotted_format, digit_string):
def is_valid_segment(segment):
if not segment or not segment.isdigit():
return False
if len(segment) > 1 and segment[0] == '0':
return False
return int(segment) <= 255
def check_dotted_ipv4(address):
segments = address.split('.')
return len(segments) == 4 and all(is_valid_segment(seg) for seg in segments)
restorations = []
if digit_string.isdigit():
def backtrack(position, segments):
chars_left = len(digit_string) - position
segments_needed = 4 - len(segments)
if segments_needed == 0:
if position == len(digit_string):
restorations.append('.'.join(segments))
return
if chars_left < segments_needed or chars_left > 3 * segments_needed:
return
for seg_len in range(1, 4):
next_pos = position + seg_len
if next_pos > len(digit_string):
break
segment = digit_string[position:next_pos]
if not is_valid_segment(segment):
continue
backtrack(next_pos, segments + [segment])
backtrack(0, [])
restorations.sort()
return {
'is_valid': check_dotted_ipv4(dotted_format),
'can_restore': bool(restorations),
'restored': restorations,
}