Skip to content
Problem 93 · LeetCode 93(opens in a new tab)

Restore IP Addresses

MediumBacktracking

An IP address is four whole numbers joined by dots, like 10.0.255.7. Each number is from 0 to 255 and is written without extra zeros in front: 0 is fine, but 00 and 07 are not.

You are given a string s made only of digits. Put exactly three dots into it, without moving, adding or dropping any digit, so that it becomes a valid IP address. Return every address you can make this way, in any order.

Example 1

Input:  s = "00124"
Output: ["0.0.1.24", "0.0.12.4"]
Why:    00 and 01 can never be a part, so the first two parts are 0
2 more examples and the constraints

Example 2

Input:  s = "2552001"
Output: ["2.55.200.1", "25.5.200.1", "255.20.0.1"]
Why:    each one ends in .1, since 01 and 001 have leading zeros

Example 3

Input:  s = "123"
Output: []
Why:    four parts need at least four digits

Constraints

  • 1 ≤ length of s ≤ 20
  • s contains only the digits 0 to 9

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every place for the dotsO(n⁴)
  2. Backtracking with pruningO(1)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 12-digit stringVerdict
Try every place for the dotsO(n⁴)
Passes; checks many splits that are doomed
Backtracking with pruningO(1)
Best; drops bad prefixes early

n = length of s. Only strings of 4 to 12 digits can have an answer.

Edge cases to test

  • Too short or too long. Fewer than 4 or more than 12 digits: return an empty list.
  • Zeros. A 0 must be a part on its own. "0000" has exactly one answer, 0.0.0.0.
  • Values above 255. "256256256256" has no answer: each part would have to be 256.
  • Exactly 12 digits. Every part must be 3 digits, so there is at most one answer.

Common mistakes

  • Allowing a part like 01 or 00. Only the single digit 0 may start with a zero.
  • Parsing a long slice as an int before checking its length, which overflows.
  • Saving an address when all four parts are placed but digits are left over.

How to talk through it

  1. 1Clarify. Must every digit be used, in order? Is 0 allowed as a part but not 00? Any order for the output?
  2. 2Count the space. Four parts of 1 to 3 digits: at most 81 splits, so brute force is already fine.
  3. 3Build it with backtracking. Cut one part at a time, push it, recurse on the rest, pop it.
  4. 4Prune. Break on a leading zero or a value above 255; skip when the rest cannot fit the parts left.
  5. 5Test out loud. Run "00124", "0000" and "123", and check 2, 1 and 0 answers.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?