Restore IP Addresses — LeetCode 93 Python Solution

MediumStringBacktracking
Problem
#93
Reading time
4 min

The 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.

Example

Input
s = "25525511135"
Output
["255.255.11.135","255.255.111.35"]

Python solution

Python
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

MeasureComplexity
TimeO(n \times 3^4)
SpaceO(n) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 93. Restore IP Addresses is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 93. Restore IP Addresses?
LeetCode 93. Restore IP Addresses is rated Medium on LeetCode.
What is the time complexity of LeetCode 93. Restore IP Addresses?
The Python solution on this page runs in O(n \times 3^4).
What is the space complexity of LeetCode 93. Restore IP Addresses?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 93. Restore IP Addresses cover?
LeetCode 93. Restore IP Addresses is tagged String and Backtracking on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview