Leetcode #93: Restore IP Addresses
In this guide, we solve Leetcode #93 Restore IP Addresses in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: String, Backtracking
Intuition
We must explore combinations of choices, but many branches can be pruned early.
Backtracking enumerates valid candidates while keeping the search space under control.
Approach
Use DFS to build candidates step by step, and backtrack when constraints are violated.
Pruning keeps the exploration practical for typical constraints.
Steps:
- Define the decision tree.
- DFS through choices and backtrack.
- Prune invalid paths early.
Example
Input: s = "25525511135"
Output: ["255.255.11.135","255.255.111.35"]
Python Solution
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
def check(i: int, j: int) -> int:
if s[i] == "0" and i != j:
return False
return 0 <= int(s[i : j + 1]) <= 255
def dfs(i: int):
if i >= n and len(t) == 4:
ans.append(".".join(t))
return
if i >= n or len(t) >= 4:
return
for j in range(i, min(i + 3, n)):
if check(i, j):
t.append(s[i : j + 1])
dfs(j + 1)
t.pop()
n = len(s)
ans = []
t = []
dfs(0)
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.