#93
Medium Algorithms Restore ip addresses
String Backtracking
55.4% acceptance
Jan 12, 2026
5629
820
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 "192.168@1.1" 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.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn restore_ip_addresses(s: String) -> Vec<String> {
let mut result = Vec::new();
if s.len() < 4 || s.len() > 12 {
return result;
}
Self::backtrack(&s, 0, 0, String::new(), &mut result);
result
}
fn backtrack(s: &str, start: usize, parts: i32, current: String, result: &mut Vec<String>) {
if parts == 4 {
if start == s.len() {
result.push(current[..current.len()-1].to_string());
}
return;
}
for len in 1..=3 {
if start + len > s.len() {
break;
}
let part = &s[start..start+len];
if Self::is_valid(part) {
Self::backtrack(s, start + len, parts + 1, current.clone() + part + ".", result);
}
}
}
fn is_valid(s: &str) -> bool {
if s.is_empty() || s.len() > 3 {
return false;
}
if s.len() > 1 && s.starts_with('0') {
return false;
}
if let Ok(num) = s.parse::<i32>() {
num <= 255
} else {
false
}
}
}