KatInterview

Reconstruct IPv4 Addresses from Digit Sequence

StringsAuto-graded · 23 test cases
MediumAuto-gradedStringsstringsbacktrackingparsing

Last updated

Parse a string of numeric digits into all possible valid four-part IPv4 address representations.

Given a string s containing only numerical digits, find every valid IPv4 address configuration that can be generated by inserting three period separators (.) into s. You must use all characters in s in their original order.

A valid IPv4 address must consist of exactly four blocks separated by periods, where each block satisfies all of the following rules:

  1. It contains between 1 and 3 digits.
  2. Its numeric value falls within the range 0 to 255 inclusive.
  3. It does not have extraneous leading zeros (e.g., "0" is permissible, but "00" and "07" are invalid).

Return all generated valid IPv4 address strings sorted in lexicographical (dictionary) order. If no valid IPv4 address can be produced, return an empty list.

Constraints

  • 1 <= len(s) <= 20
  • s consists exclusively of ASCII digits ('0' through '9').

Examples

Example 1

Input: restore_ip_addresses('25525511135')

Output: ['255.255.11.135', '255.255.111.35']

Example 2

Input: restore_ip_addresses('0000')

Output: ['0.0.0.0']

Example 3

Input: restore_ip_addresses('101023')

Output: ['1.0.10.23', '1.0.102.3', '10.1.0.23', '10.10.2.3', '101.0.2.3']

Hints

Hint 1

Check string length bounds first: a valid IPv4 address requires between 4 and 12 digits.

Hint 2

You can either use backtracking or simple nested loops to partition the string into 4 subsegments of length 1 to 3.

Hint 3

Be careful with leading zeros: a segment longer than 1 character cannot start with '0'.