SDE & MLE Prep

93. Restore IP Addresses

Problem

s contains only digits. Insert three dots to form every valid IPv4 address: four parts, each from 0 to 255, with no leading zeros ("0" is fine, "01" isn't). Don't reorder or remove digits.

Example: "25525511135" → ["255.255.11.135","255.255.111.35"]; "0000" → ["0.0.0.0"]

Split into exactly 4 parts, each 1–3 digits, value ≤ 255, no leading zeros. Prune when the remaining length can't fit the remaining parts.

Complexity: O(3⁴) — constant.

class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        res = []

        def bt(i, parts):
            if len(parts) == 4:
                if i == len(s):
                    res.append(".".join(parts))
                return
            rem = 4 - len(parts)
            if not rem <= len(s) - i <= 3 * rem:
                return
            for L in range(1, 4):
                p = s[i:i + L]
                if len(p) < L or (p[0] == "0" and L > 1) or int(p) > 255:
                    break
                bt(i + L, parts + [p])

        bt(0, [])
        return res