LeetCode 93: Restore IP Addresses

link

With the 3 dots inserted, the length of a valid ip address is len(s)+3. We create different possible four-parts via backtracking and include the valid ones.

Time: \mathcal{O}(n^4), space: \mathcal{O}(1).

class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        # a.b.c.d
        # a: 
        # - in [0, 255]
        # - no leading zero

        # 0 1 2 3 4 5 6 7 8 9 10
        # 2 5 5 2 5 5 1 1 1 3  5

        # len(curr) = len(s) + 3


        ips = []
        parts = []

        def restore(i):
            if len(parts) == 4:
                ip = ".".join(parts)
                if len(ip) == len(s)+3:
                    ips.append(ip)
                return
            
            for j in range(i, min(i+3, len(s))):
                # no leading zeros
                if s[i] == "0" and j > i:
                    break

                # part in [0, 255]
                part = s[i:j+1]
                if not (0 <= int(part) <= 255):
                    break

                parts.append( s[i:j+1] )
                restore(j+1)
                parts.pop()


        restore(0)

        return ips

Leave a comment