Restore IP Addresses

Enumerate all valid IPv4 addresses formed by inserting three dots into a digit string — DFS with strict octet rules.

Medium
Time O(1) Space O(1)
LeetCode
4 min read
backtracking string

Problem#

Given a digit string, return all valid IP address strings formed by inserting three dots. An octet is 0–255 with no leading zeros (except "0" itself).

Examples#

  • "25525511135"["255.255.11.135", "255.255.111.35"]

Constraints#

  • 1 <= s.length <= 20.

Approach#

DFS over 4 segments. At each call, try segment lengths 1, 2, or 3, validate (no leading zero unless length 1; ≤ 255), recurse on the remainder.

Solution#

Restore IP Addresses
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> out;
vector<string> parts;
function<void(int)> dfs = [&](int start) {
if (parts.size() == 4) {
if (start == (int)s.size())
out.push_back(parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3]);
return;
}
for (int len = 1; len <= 3 && start + len <= (int)s.size(); ++len) {
string seg = s.substr(start, len);
if ((seg[0] == '0' && len > 1) || stoi(seg) > 255) continue;
parts.push_back(seg);
dfs(start + len);
parts.pop_back();
}
};
dfs(0);
return out;
}
};

Editorial#

Constant-time complexity bounds because the search tree has at most 3^4 = 81 leaves. The octet validation is the only non-DFS logic — leading-zero check, range check.

Complexity#

  • Time: O(1) (bounded).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.