Problem Description
Given a string containing only digits, restore all possible valid IP addresses by inserting exactly three dots into the string. A valid IP address consists of four integers, each between 0 and 255 inclusive, and no integer (except 0) can have leading zeros.
Key Insights
- Use a backtracking approach to explore different segmentations of the input string.
- IP addresses contain exactly four segments; once four segments are generated, the entire string must have been used.
- Validate each segment to ensure it is within the range [0, 255] and does not have leading zeros (unless the segment is "0").
- Prune the search if the remaining characters do not allow forming a valid IP address (too short or too long).
Space and Time Complexity
Time Complexity: O(N^4) in the worst-case scenario where N is the length of the string, though N is bounded by string length constraints. Space Complexity: O(N) for the recursion call stack and temporary storage, where N is the length of the string.
Solution
We use a backtracking recursive approach to partition the string into four segments. At each recursive call, we try all possible segment lengths (1 to 3 characters) while ensuring that:
- The chosen segment does not exceed the string's bounds.
- The segment does not have any invalid leading zeros (unless the segment is "0").
- The numeric value of the segment lies between 0 and 255.
Once four segments are collected, we check if all characters in the string have been consumed. If so, we join the segments with dots and add the resulting IP address to the final answer list.