Program to generate all possible valid IP addresses from given string
Pattern: Recursion trees
An IP address is four parts, each 0 to 255 with no leading zeros. Cut the digit string into parts of 1, 2 or 3 digits, stopping a branch the moment a part breaks the rules, and keep the cuts that use every digit in exactly four parts.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Given a string of digits, return every valid IP address you can form by inserting three dots. A valid address has four
parts, each a whole number from 0 to 255, written without leading zeros (so 0 is fine but 01 is not). For example,
"25525511135" gives 255.255.11.135 and 255.255.111.35, and "0000" gives 0.0.0.0.
This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet (LeetCode's Restore IP
Addresses is the same task). The function name restoreIpAddresses follows LeetCode. The tests compare the answers after
sorting.
Think first
- How long can one part be?
- Which parts are invalid even if they are short enough?
- When can a branch stop early?
Hints
Brute force, and why it fails
Try every way to place three dots in the n - 1 gaps: O(n³) placements, each checked in O(n). Backtracking explores
at most 3⁴ = 81 paths, since each part has at most 3 lengths.
The key insight
The four-part, three-digit limits make the search tree tiny. The pruning rules (leading zero, more than 255) cut it down further as soon as a part fails.
Dry run
| parts |
|---|
s = 25525511135. The first part can be 2, 25 or 255.
The plan
function build(start, parts):
if len(parts) == 4:
if start == n: record parts joined by "."
return
for len from 1 to 3 with start + len <= n:
p = s[start .. start + len - 1]
if len(p) > 1 and p[0] == '0': stop
if p > 255: stop
build(start + len, parts + [p])
Complexity
- Time
O(1)- Space
O(1)
At most 81 branches of at most 12 digits, whatever the input (longer inputs fail at once). Constant work in practice.
Edge cases
"0000":0.0.0.0only.- Too short (
"123") or too long ("256256256256"): no addresses. - Parts of exactly 255 are fine; 256 is not.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> out = new ArrayList<>();
build(s, 0, new ArrayList<>(), out);
return out;
}
private void build(String s, int start, List<String> parts, List<String> out) {
if (parts.size() == 4) {
if (start == s.length()) out.add(String.join(".", parts)); // four parts that use every digit
return;
}
for (int len = 1; len <= 3 && start + len <= s.length(); len++) {
String p = s.substring(start, start + len);
if (p.length() > 1 && p.charAt(0) == '0') break; // no leading zeros
if (Integer.parseInt(p) > 255) break; // too big for one part
parts.add(p);
build(s, start + len, parts, out);
parts.remove(parts.size() - 1);
}
}
}C++
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> out, parts;
build(s, 0, parts, out);
return out;
}
void build(const string& s, size_t start, vector<string>& parts, vector<string>& out) {
if (parts.size() == 4) {
if (start == s.size()) out.push_back(parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3]);
return; // four parts that use every digit
}
for (size_t len = 1; len <= 3 && start + len <= s.size(); len++) {
string p = s.substr(start, len);
if (p.size() > 1 && p[0] == '0') break; // no leading zeros
if (stoi(p) > 255) break; // too big for one part
parts.push_back(p);
build(s, start + len, parts, out);
parts.pop_back();
}
}
};Python
class Solution:
def restoreIpAddresses(self, s: str) -> list[str]:
out = []
def build(start: int, parts: list) -> None:
if len(parts) == 4:
if start == len(s):
out.append(".".join(parts)) # four parts that use every digit
return
for length in range(1, 4):
if start + length > len(s):
break
p = s[start:start + length]
if len(p) > 1 and p[0] == "0":
break # no leading zeros
if int(p) > 255:
break # too big for one part
parts.append(p)
build(start + length, parts)
parts.pop()
build(0, [])
return outCommon mistakes
- Allowing parts like
00or012. - Keeping four parts that leave digits unused.
- Parsing a part before checking its length, which can overflow on long inputs.