sagelearnai

Restore IP Addresses

Difficulty: Medium · Pattern: Backtracking · LeetCode #93

Given a string of digits s, return all valid IPv4 addresses that can be formed by inserting three dots. Each of the 4 parts must be an integer in 0–255 without leading zeros ("0" is fine, "01" is not). Any order is accepted.

Examples

text
"25525511135"  →  ["255.255.11.135","255.255.111.35"]
"0000"         →  ["0.0.0.0"]
"101023"       →  ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

Hints

  1. Each part is 1–3 characters, so there are at most 3⁴ = 81 ways to cut.
  2. Prune: the remaining characters must fit in the remaining parts (between 1 and 3 each).

Approach

bt(start, parts). When len(parts) == 4, the cut is valid only if start == len(s). Otherwise, for length in 1..3:

  • seg = s[start:start+length]. Skip it if it's too short (out of characters), has a leading '0' with length > 1, or is greater than 255.

Pruning when the remaining length is outside [need, 3·need] keeps the search tiny. It's constant time, since the input is at most 12 relevant digits.

Complexity

Time: O(1), at most 81 cuts. Space: O(1).

Python solution
def restoreIpAddresses(s):
    res, parts = [], []
    def bt(start):
        need = 4 - len(parts)
        rem = len(s) - start
        if need == 0:
            if rem == 0:
                res.append('.'.join(parts))
            return
        if rem < need or rem > 3 * need:
            return
        for L in range(1, 4):
            seg = s[start:start + L]
            if len(seg) < L or (L > 1 and seg[0] == '0') or int(seg) > 255:
                break
            parts.append(seg)
            bt(start + L)
            parts.pop()
    bt(0)
    return res
JavaScript solution
function restoreIpAddresses(s) {
  const res = [], parts = [];
  const bt = (start) => {
    const need = 4 - parts.length, rem = s.length - start;
    if (need === 0) { if (rem === 0) res.push(parts.join('.')); return; }
    if (rem < need || rem > 3 * need) return;
    for (let L = 1; L <= 3 && start + L <= s.length; L++) {
      const seg = s.slice(start, start + L);
      if ((L > 1 && seg[0] === '0') || Number(seg) > 255) break;
      parts.push(seg); bt(start + L); parts.pop();
    }
  };
  bt(0);
  return res;
}