Restore IP Addresses
MediumUpdated: Aug 2, 2025
Practice on:
Problem
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.
- For example,
"0.1.2.201"and"192.168.1.1"are valid IP addresses, but"0.011.255.245","192.168.1.312"and"[email protected]"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.
Examples
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"]
Solution
Method 1 - Backtracking
This problem can be approached using depth-first search (DFS) to explore all possibilities of dividing the string into valid IP address segments. For each segment:
- Check if the segment is between
0and255. - Ensure the segment does not have leading zeros unless it is "0".
- Recursively pass the rest of the string to explore further segments.
- Collect valid IP address configurations formed by exactly four segments.
Code
Java
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
def backtrack(start: int, path: List[str]):
if len(path) == 4:
if start == len(s):
ans.append('.'.join(path))
return
for length in range(1, 4):
if start + length <= len(s):
segment = s[start:start + length]
if (len(segment) > 1 and segment[0] == '0') or (int(segment) > 255):
continue
path.append(segment)
backtrack(start + length, path)
path.pop()
ans = []
backtrack(0, [])
return ans
Python
public class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> ans = new ArrayList<>();
backtrack(s, 0, new ArrayList<>(), ans);
return ans;
}
private void backtrack(String s, int start, List<String> path, List<String> ans) {
if (path.size() == 4) {
if (start == s.length()) {
ans.add(String.join(".", path));
}
return;
}
for (int length = 1; length <= 3; length++) {
if (start + length <= s.length()) {
String segment = s.substring(start, start + length);
if ((segment.length() > 1 && segment.startsWith("0")) || (Integer.parseInt(segment) > 255)) {
continue;
}
path.add(segment);
backtrack(s, start + length, path, ans);
path.remove(path.size() - 1);
}
}
}
}
Complexity
- ⏰ Time complexity:
O(1), since the length of the string is fixed (maximum 12 digits). - 🧺 Space complexity:
O(1), considering the storage for results and a fixed amount of extra space for recursion.