Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Restore IP addresses from a string

Given a string of digits, produce all valid IPv4 addresses by inserting dots.

Python practice16 minRecursion & BacktrackingIntermediateLast updated March 27, 2026

Problem statement

Given a string s containing only digits, return all possible valid IPv4 addresses that can be obtained by inserting three dots into s. A valid segment is between 0 and 255 inclusive, and cannot have leading zeros unless it is exactly '0'. Return addresses in the order they are generated by a left-to-right backtracking approach. If there are no valid addresses, return an empty list.

Task

Use backtracking to place three dots to form valid IP addresses, validating each segment (0-255, no leading zeros unless the segment is '0').

Examples

Basic example

Input

s = "25525511135"

Output

['255.255.11.135', '255.255.111.35']

Two possible valid addresses.

Input format

A single string s. You will call restore_ip_addresses(s).

Output format

A list of strings where each string is a valid IPv4 address, e.g. ['1.1.1.1'].

Constraints

0 <= len(s) <= 20. Only digits are present in s. The final list size is limited by combinatorics of splits (max small).

Samples

Sample 1

Input

s = "0000"

Output

['0.0.0.0']

Each segment must be '0' (leading zeros not allowed otherwise).