Restore IP Addresses solution explained

To restore IP addresses from a digit string, try every way to cut it into four pieces and keep the splits where each piece is a number from 0 to 255 with no leading zero ("0" is fine, "05" is not). Backtracking with a length check prunes dead branches early. Because an address has exactly four parts of one to three digits, there are at most 27 ways to place the dots and at most 81 search paths, so the Restore IP Addresses solution runs in constant time for any input that can produce an answer.

By Published 7 min read

The task, restated

You receive a string made only of the characters 0 to 9. Insert exactly three dots so that the result is a valid IPv4 address, and return every such address in any order. You may not reorder, drop or add digits. Each of the four parts must be an integer between 0 and 255, and a part longer than one digit cannot begin with a zero.

Inputs and outputs worked out for this page
InputValid addressesWhy
"10023"1.0.0.23 and 10.0.2.3"100.2.3" needs a fourth part; "1.00.2.3" has a leading zero
"3001"3.0.0.1Only one split avoids "00" or "01"
"100100"1.0.0.100, 10.0.10.0, 100.1.0.0Zeros must stand alone unless a non-zero digit leads
"99999"Four answers: the 99 can sit in any of the four slotsEvery other split leaves a part above 255 or an empty part
"123" or a 13-digit stringNoneFewer than 4 or more than 12 digits can never fit
Inputs and outputs worked out for this page. Scroll sideways on a small screen.

Questions worth asking first: can the string contain anything but digits, and should the output be in a particular order? Most versions promise digits only and accept any order. If the interviewer wants sorted output, sort at the end rather than complicating the search.

How interviewers use it

Restore IP Addresses is a backtracking problem with a small, fixed depth, which makes it a good test of whether you can write a clean recursive search and state the validity rules precisely. Most bugs come from the leading-zero rule, from forgetting that the whole string must be used, and from off-by-one slicing. Interviewers also listen for the complexity answer, because "exponential" is the reflex and it is wrong here.

  • Explain the bound. Four parts, three length choices each, so at most 3 to the power 4 = 81 leaf paths.
  • Handle IPv6 or a different part count. The same search works with the slot count and the per-part rule as parameters.
  • Count the addresses instead of listing them. A small DP over (position, parts placed) counts without building strings.
  • Validate one given address. That is the per-part check alone, a common warm-up before this question.

Brute force: three nested cut positions

Place the first dot after 1, 2 or 3 characters, the second dot 1 to 3 characters later, and the third dot 1 to 3 characters after that. Whatever remains is the fourth part. Check all four pieces with the same helper. This is short, obviously complete, and makes a good reference to test the recursive version against.

def valid_part(p):
    if not p or len(p) > 3:
        return False
    if p[0] == "0" and len(p) > 1:
        return False  # "0" is allowed, "05" is not
    return int(p) <= 255

def restore_by_cuts(s):
    n, out = len(s), []
    for i in range(1, 4):
        for j in range(i + 1, i + 4):
            for k in range(j + 1, j + 4):
                if k >= n:
                    break  # the fourth part would be empty
                parts = [s[:i], s[i:j], s[j:k], s[k:]]
                if all(valid_part(p) for p in parts):
                    out.append(".".join(parts))
    return out
Python: every combination of three cut positions, then validate the pieces.

The fourth piece can be long when the input is long, which is why valid_part rejects anything over three characters before converting it. Without that check, a 20-digit tail would still be parsed as an integer before being rejected.

Backtracking with pruning

Build the address one part at a time. At each step you know how many parts are still missing and how many digits are left. If fewer digits remain than parts (each part needs at least one) or more than three per missing part, stop immediately. Otherwise try a piece of length 1, 2 and 3, skipping pieces with a leading zero or a value above 255. When four parts are placed and no digits remain, record the address.

def restore_ip_addresses(s):
    if not (4 <= len(s) <= 12) or not (s.isascii() and s.isdigit()):
        return []
    out, parts = [], []

    def place(start):
        missing = 4 - len(parts)
        rest = len(s) - start
        if missing == 0:
            if rest == 0:
                out.append(".".join(parts))
            return
        if rest < missing or rest > 3 * missing:
            return  # the remaining digits cannot fill the remaining slots
        for size in (1, 2, 3):
            piece = s[start:start + size]
            if len(piece) < size:
                break
            if size > 1 and piece[0] == "0":
                break  # longer pieces would start with the same zero
            if int(piece) > 255:
                break
            parts.append(piece)
            place(start + size)
            parts.pop()

    place(0)
    return out
Python: recursive search over the four slots with an early length check.
function restoreIpAddresses(s) {
  const out = [];
  if (s.length < 4 || s.length > 12 || !/^[0-9]+$/.test(s)) return out;
  const parts = [];
  const place = (start) => {
    const missing = 4 - parts.length;
    const rest = s.length - start;
    if (missing === 0) {
      if (rest === 0) out.push(parts.join("."));
      return;
    }
    if (rest < missing || rest > 3 * missing) return;
    for (let size = 1; size <= 3 && start + size <= s.length; size++) {
      const piece = s.slice(start, start + size);
      if (size > 1 && piece[0] === "0") break;
      if (Number(piece) > 255) break;
      parts.push(piece);
      place(start + size);
      parts.pop();
    }
  };
  place(0);
  return out;
}
JavaScript: the same search; a regular expression rejects non-digits up front.

Each break is safe because the loop goes from short pieces to long ones. If a two-digit piece starts with zero, the three-digit piece does too. If a piece is already above 255, adding a digit only makes it bigger.

Time and space

Complexity for an input of length n
ApproachTimeExtra space
Three nested loopsAt most 27 cut combinations; slicing a long tail makes it O(n) for long inputs, O(1) for 12 digits or fewerO(1) besides the output
Backtracking with pruningAt most 81 leaf paths, usually far fewer: O(1)Recursion depth 4, O(1) besides the output
Either, with n unrestrictedO(n) only for reading or rejecting the inputSame
Complexity for an input of length n. Scroll sideways on a small screen.

A fair way to say it: "The search space is bounded by the shape of an IPv4 address, not by the input, so it is constant. If the part count were k instead of 4, it would be O(3^k · k)." That shows you know where the bound comes from.

Edge cases

  • Fewer than 4 or more than 12 digits: return an empty list without searching.
  • Runs of zeros: every zero must be its own part, so four zeros give exactly one address.
  • A part of exactly 255 is valid; 256 is not.
  • A tail like "013" is invalid even though its value, 13, is in range.
  • Characters other than digits, if the input is not guaranteed clean.

Mistakes to avoid

  • Accepting "00" or "012" because int() quietly drops the zeros.
  • Stopping after four parts without checking that every digit was used.
  • Converting a very long remaining tail to an integer before checking its length.
  • Calling the solution exponential without noting that the depth is fixed at four.
  • Sharing one parts list across branches but forgetting to pop after the recursive call.

How to explain it out loud

Fictional example

Walking an interviewer through "10023"
Candidate
An address has four parts, each one to three digits, at most 255, and no leading zero unless the part is a single 0. So I need to pick three dot positions.
Candidate
I will backtrack: choose the first part, recurse on the rest with three parts left. Before trying pieces I check that the remaining digits fit, at least one and at most three per missing part.
Candidate
For 10023, a first part of 1 leads to 1.0.0.23; a first part of 10 leads to 10.0.2.3; 100 leaves 23, which cannot fill three parts, so that branch dies at once.
Candidate
There are at most 81 paths no matter the input, so the time is constant once I reject strings outside 4 to 12 characters.

The rest of this set is about pointer work on linked lists, a different kind of careful bookkeeping. Rotate List also hinges on a length check and a modulo, and Design Linked List asks you to pin down index rules as precisely as the part rules here. For a broader list of algorithm topics, see algorithm interview questions.

Where Natively fits

When you rehearse problems like this on a Mac or Windows PC, Natively can read the statement from a screenshot and write an approach and code in its overlay, which you can compare with your own validity rules. Transcribing a mock round also shows whether you explained the 81-path bound or skipped it. More on the AI interview assistant page.

Questions people ask

How do you solve Restore IP Addresses?

Backtrack over the four parts. At each step try a piece of one, two or three digits, skip it if it has a leading zero or exceeds 255, and record the address when four parts use every digit.

Why is "01" not a valid part of an IP address?

In this problem a part longer than one digit may not begin with zero. A lone "0" is valid, but "01", "00" and "012" are not, even though their values are in range.

What is the time complexity of Restore IP Addresses?

Constant. Four parts with at most three length choices each give at most 81 paths, and any input outside 4 to 12 digits is rejected at once.

Can Restore IP Addresses be solved without recursion?

Yes. Three nested loops over the dot positions, followed by a check of the four pieces, cover every split and are easy to verify.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP