# 93\_Restore IP Address

\[Medium]

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

**Example:**

```
Input: "25525511135"

Output:["255.255.11.135", "255.255.111.35"]
```

## Solution 1: iterative

**Idea**:

* Loop over all possible placements of three periods, and check if all four corresponding substring are between 0 and 255.
* If a substring has length larger than 1 and starts with 0, this substring is invalid.

**Time Complexity**: $$O(n^3)$$ where n is the length of input string.

**Space Complexity**: No extra space needed except the output.

```python
def restoreIpAddresses(s):
    """
    :type s: str
    :rtype: List[str]
    """
    def is_valid_part(s):
        return int(s) >= 256 or (len(s) >= 2 and s[0] == "0")

    if len(s) > 12: return []
    output = []
    for i in range(len(s)-3):
        if not is_valid_part(s[:i+1]):
            for j in range(i+1, len(s)-2):
                if not is_valid_part(s[i+1:j+1]):
                    for k in range(j+1, len(s)-1):
                        if not is_valid_part(s[j+1:k+1]) and not is_valid_part(s[k+1:]):
                            output.append(s[:i+1]+"."+s[i+1:j+1]+"."+s[j+1:k+1]+"."+s[k+1:])
    return output
```

## Solution 2: backtracking


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lei-d.gitbook.io/leetcode/string/93restore-ip-address.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
