Restore IP Addresses - 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.
Input & Output
Example 1 — Basic Case
$
Input:
s = "25525511135"
›
Output:
["255.255.11.135","255.255.111.35"]
💡 Note:
Two valid IP addresses can be formed: 255.255.11.135 and 255.255.111.35. Each segment is between 0-255 with no leading zeros.
Example 2 — No Valid IPs
$
Input:
s = "0000"
›
Output:
["0.0.0.0"]
💡 Note:
Only one valid IP can be formed: 0.0.0.0. Each segment is exactly '0' which is valid.
Example 3 — Leading Zero Issue
$
Input:
s = "101023"
›
Output:
["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
💡 Note:
Multiple valid combinations exist. Note that segments like '010' are invalid due to leading zeros.
Constraints
- 1 ≤ s.length ≤ 20
- s consists of digits only
Visualization
Tap to expand
Understanding the Visualization
1
Input
String of digits that need to be split into 4 IP segments
2
Split & Validate
Try all ways to place 3 dots, validate each segment
3
Output
Return all valid IP address combinations
Key Takeaway
🎯 Key Insight: Use backtracking to systematically try all segment combinations while validating IP rules
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code