Smudged Router Label

MediumbacktrackingAlso known as Restore IP Addresses

A repair shop prints each device's network address on a sticker, like 192.168.1.1. The faulty label printer drops every dot, so a sticker reads 19216811, and the technician must work out which addresses it could have been.

A valid address is four numbers separated by dots. Each number is from 0 to 255 and has no leading zeros, so 0 is allowed but 01 and 00 are not.

Your task

Write possibleAddresses(label). label is a string of digits. Return every valid address that becomes label when its three dots are removed, written with dots, like "192.168.1.1".

Use every digit, in order. Return the addresses in any order, each once. If none is possible, return an empty list.

possibleAddresses(label: string) → string[] Any order of the returned list is accepted.

Examples

Example 1
Input
label = "19216811"
Output
["1.92.168.11", "19.2.168.11", "19.21.68.11", "19.216.8.11", "19.216.81.1", "192.1.68.11", "192.16.8.11", "192.16.81.1", "192.168.1.1"]
Why

The eight digits are split into four numbers. The sticker cannot distinguish the original 192.168.1.1 from other valid splits such as 19.216.81.1, which is also four numbers from 0 to 255. The split 1.921.68.11 is invalid because 921 is over 255.

Example 2
Input
label = "10203"
Output
["1.0.20.3", "10.2.0.3"]
Why

Five digits in four numbers means exactly one number has two digits. The splits 10.2.0.3 and 1.0.20.3 are valid. The splits 1.02.0.3 and 1.0.2.03 are invalid, because a number cannot start with 0 unless it is just 0.

Constraints

  • 0 ≤ label.length ≤ 20
  • label contains only the digits 0 to 9.
  • Addresses may be returned in any order.
Start with brute force

Choose 3 of the n − 1 gaps between digits for the dots and check the four pieces. For 12 digits that is only 165 choices, so it is not slow, but it is rigid and wasteful.

It checks splits whose first piece is 1921 or 05, which can never work, and its three nested loops are hard-wired to four parts. Building the address piece by piece and rejecting a bad piece immediately does less work and handles any number of parts.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code