![]() |
VOOZH | about |
Given a string s consisting only of digits, return all possible valid IP address combinations that can be formed from it. A valid IP address consists of four numbers (0–255) separated by dots.
Note: A segment cannot contain leading zeros unless the number itself is 0. For example, 1.1.2.11 and 0.11.21.1 are valid IP addresses, while 01.1.2.11 and 00.11.21.1 are not valid because they contain leading zeros.
Examples:
Input: s = "255678166"
Output: [“25.56.78.166”, “255.6.78.166”, "255.67.8.166", "255.67.81.66"]
Explanation: These are the only valid possible IP addresses.
Input: s = "25505011535"
Output: []
Explanation: We cannot generate a valid IP address with this string.
We generate all possible ways to place 3 dots in the string to form 4 segments. During the process, we only continue if the current segment is valid (0–255 and no leading zeros). If a segment becomes invalid, we prune that branch to avoid unnecessary exploration.
Step by Step implementation
25.56.78.166 255.6.78.166 255.67.8.166 255.67.81.66
Time Complexity
Auxiliary Space