The problem “93. Restore IP Addresses” requires you to restore all possible valid IP address combinations from a given string consisting of only digits. An IP address consists of four decimal numbers, each ranging from 0
to 255
, separated by dots (.
). The input string should be partitioned into these four parts to build valid IP addresses. Return these IP addresses in any order.
The constraints are:
We will use a backtracking approach to generate all valid combinations of IP addresses. Here’s the general strategy:
0
but has more than one digit), skip that combination.Here’s the Python implementation of the strategy:
def restoreIpAddresses(s):
def is_valid(segment):
# Check if the segment is valid:
# 1. Length should be between 1 and 3
# 2. No leading zero unless it is '0'
# 3. Should be less than or equal to 255
return len(segment) == 1 or (segment[0] != '0' and int(segment) <= 255)
def backtrack(start=0, path=[]):
# If we have 4 segments and we have reached the end of the string,
# we found a valid IP address
if len(path) == 4:
if start == len(s):
result.append(".".join(path))
return
# Try to place "." after each 1 to 3 characters
for end in range(start + 1, min(start + 4, len(s) + 1)):
segment = s[start:end]
if is_valid(segment):
backtrack(end, path + [segment])
result = []
backtrack()
return result
# Example Usage
s = "25525511135"
print(restoreIpAddresses(s))
The time complexity of this solution is O(3^4)
, which simplifies to O(81)
or O(1)
as this is constant time for valid IP address partitions. Here’s why:
3 * 3 * 3 * 3 = 3^4 = 81
.While there is some additional complexity related to the string slicing and validations, the crucial point is the number of recursive calls, which is fixed and manageable.
This backtracking approach ensures efficient and correct generation of all possible valid IP addresses from the provided string.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?