Smudged Router Label

MediumbacktrackingAlso known as Restore IP Addresses

A repair shop prints a sticker with each device's network address, like 192.168.1.1. The label printer has a fault: it drops every dot. A sticker now just reads 19216811, and the technician has to 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 is written without leading zeros, so 0 is fine 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 the dots, like "192.168.1.1".

Use every digit, in the given 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

Eight digits split into four numbers. 192.168.1.1 is the address the printer started from, but the sticker cannot tell it apart from the others: 19.216.81.1 is also four numbers from 0 to 255. Something like 1.921.68.11 does not, 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. 10.2.0.3 and 1.0.20.3 work. 1.02.0.3 and 1.0.2.03 fail, 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

There are n − 1 gaps between digits. Try every way to choose 3 of them for the dots and check the four pieces. For a 12-digit label that is only 165 choices, so this is not slow at this size; its weakness is that it is rigid and wasteful.

It builds and checks splits whose first piece is 1921 or 05, which were hopeless from the first cut, and the three nested loops are hard-wired to four parts. Building the address piece by piece and rejecting a bad piece the moment it appears does less work and works for 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