A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros.
"0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses.Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.
Example 1:
Input: s = "25525511135" Output: ["255.255.11.135","255.255.111.35"]
Example 2:
Input: s = "0000" Output: ["0.0.0.0"]
Example 3:
Input: s = "101023" Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
Constraints:
1 <= s.length <= 20s consists of digits only.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a string of digits and you need to slice it into four pieces to form a valid internet address. The brute force approach involves trying every single possible place to make cuts in the string to see what works.
Here's how the algorithm would work step-by-step:
def restore_ip_addresses(digit_string):
valid_ip_addresses = []
# Iterate through all possible lengths for the first three octets to exhaustively test every cut combination
for first_end in range(1, min(4, len(digit_string))):
for second_end in range(first_end + 1, min(first_end + 4, len(digit_string))):
for third_end in range(second_end + 1, min(second_end + 4, len(digit_string))):
first_octet = digit_string[:first_end]
second_octet = digit_string[first_end:second_end]
third_octet = digit_string[second_end:third_end]
fourth_octet = digit_string[third_end:]
octets_list = [first_octet, second_octet, third_octet, fourth_octet]
# Validate each octet to ensure it satisfies IPv4 rules regarding length and numerical limits
is_valid = True
for current_octet in octets_list:
if len(current_octet) == 0 or len(current_octet) > 3:
is_valid = False
break
if current_octet[0] == '0' and len(current_octet) > 1:
is_valid = False
break
if int(current_octet) > 255:
is_valid = False
break
# Append successfully verified configurations to our collection of valid internet addresses
if is_valid:
valid_ip_addresses.append(".".join(octets_list))
return valid_ip_addressesTo find all valid IP addresses hidden inside a string of digits, the optimal approach uses a systematic trial-and-error strategy. It places three dividing dots across the digits in every possible valid position, checking along the way to ensure each of the four resulting sections follows the proper rules.
Here's how the algorithm would work step-by-step:
class Solution:
def restoreIpAddresses(self, input_string: str) -> list[str]:
valid_ip_addresses = []
def backtrack_ip_parts(string_index: int, current_parts: list[str]):
if len(current_parts) == 4 and string_index == len(input_string):
valid_ip_addresses.append(".".join(current_parts))
return
if len(current_parts) == 4 or string_index == len(input_string):
return
# We iterate up to 3 digits because an IP octet cannot exceed 255 in length.
for segment_length in range(1, 4):
if string_index + segment_length > len(input_string):
break
potential_segment = input_string[string_index:string_index + segment_length]
# Leading zeros are invalid unless the segment is a single zero character.
if (potential_segment.startswith("0") and len(potential_segment) > 1) or int(potential_segment) > 255:
continue
current_parts.append(potential_segment)
backtrack_ip_parts(string_index + segment_length, current_parts)
current_parts.pop()
backtrack_ip_parts(0, [])
return valid_ip_addresses| Case | How to Handle |
|---|---|
| String length is less than 4 or greater than 12 | Return an empty list immediately because a valid IPv4 address requires between 4 and 12 digits inclusive. |
| Segments with leading zeros such as 03 | Prune the recursion branch when a segment starts with zero and has a length greater than one. |
| Segments exceeding the maximum value of 255 | Validate that the integer value of each formed segment is less than or equal to 255 before proceeding. |
| Input string containing only zeros like 0000 | Successfully parse and validate each single-digit zero segment to return 0.0.0.0. |
| No valid IP address combinations can be formed | The backtracking algorithm naturally exhausts all paths and returns an empty list. |
| Maximum-sized input of 12 digits | The algorithm executes in constant time O(1) because the search space is bounded by a maximum of 3 to the power of 4 states. |
| Input strings containing non-digit characters | The problem constraints guarantee the string contains only digits, but input validation could reject non-digits if needed. |