↓Skip to main content
  1. LeetCode/

LeetCode 93: Restore IP Addresses

·2 mins· ·
LeetCode Medium String Backtracking
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-11-05

  • Submissions: Accepted ×2

Approach
#

Partition backtracking (Backtracking Variation 5): each level cuts 1 to 3 characters; a piece is valid when 0 <= int(piece) <= 255 and piece == "0" or piece[0] != "0". Record after 4 pieces only if the string is used up. Prune when the remaining length is outside remaining pieces × 1 to remaining pieces × 3.

My Attempts
#

Both 2022-11 submissions passed. The first did not cap pieces at 3 characters, relying on int(piece) < 256 to reject long ones, and had no remaining-length pruning.

Solution
#

class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        res, path = [], []
        def dfs(start):
            left = 4 - len(path)
            if left == 0:
                if start == len(s):
                    res.append(".".join(path))
                return
            if not left <= len(s) - start <= 3 * left:
                return
            for end in range(start + 1, min(start + 3, len(s)) + 1):
                piece = s[start:end]
                if (piece == "0" or piece[0] != "0") and int(piece) <= 255:
                    path.append(piece)
                    dfs(end)
                    path.pop()
        dfs(0)
        return res

Complexity
#

Time O(3^4), space O(1) excluding output.

Mistakes to Avoid
#

  • Leading zeros: "01" is invalid while "0" is fine.
  • Exactly 4 pieces, and the whole string must be used.

Interview Explanation
#

I backtrack over cuts of 1 to 3 characters, each at most 255 with no leading zero except 0 itself, recording when four pieces use up the string and pruning when the remaining length cannot fit.

Related

LeetCode 131: Palindrome Partitioning
·2 mins
LeetCode Medium String Dynamic-Programming Backtracking
LeetCode 131 note: each level cuts a palindrome from the front of the remaining string, trying every length from 1 to the whole remainder
LeetCode 79: Word Search
·3 mins
LeetCode Medium Array String Backtracking Depth-First-Search
LeetCode 79 note: backtrack from every cell, matching the next character in four directions with visited cells marked temporarily and restored; prune early with character counts
LeetCode 17: Letter Combinations of a Phone Number
·2 mins
LeetCode Medium Hash-Table String Backtracking
LeetCode 17 note: each level handles one digit and tries its letters; an empty input returns an empty list
LeetCode 647: Palindromic Substrings
·1 min
LeetCode Medium Two-Pointers String Dynamic-Programming
LeetCode 647 note: expand around centers, counting one palindromic substring for each successful expansion
LeetCode 208: Implement Trie (Prefix Tree)
·2 mins
LeetCode Medium Hash-Table String Design Trie
LeetCode 208 note: each node is a children dict plus an is_end flag; insert, search and startsWith all walk down character by character
LeetCode 424: Longest Repeating Character Replacement
·2 mins
LeetCode Medium Hash-Table String Sliding-Window
LeetCode 424 note: a variable sliding window where window length minus the top character count is the number of replacements; shrink when it exceeds k