AlgoInsight

DSA problem

Restore IP Addresses

MediumBacktrackingPattern: Backtrackingtop600AmazonMicrosoftGoogleBloombergAdobe

Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting exactly three dots into s. You are not allowed to reorder or remove any digits in s. Each of the four numeric segments separated by dots must be in [0, 255] and may not contain leading zeros (so "0" is allowed but "01" is not).

This problem is a constrained string partition: we need to split s into exactly four non-empty contiguous segments such that each segment satisfies the IP-segment rule. Brute force would try every (i, j, k) triple of dot positions and check validity, giving roughly C(n - 1, 3) partitions; backtracking arrives at the same answer with cleaner pruning baked in.

The recursive routine maintains a list of segments built so far and a start index into s. At each call we have one of four states (segments.length == 0..3) and need to pick the length of the next segment (1, 2, or 3 digits). We validate immediately: a 2 or 3-digit segment cannot start with '0', and a 3-digit segment value must be <= 255. Pre-pruning these cases avoids descending into impossible branches.

When segments.length == 4, we have four segments; if start == s.length we have consumed the whole string and can join with dots to produce a valid IP address. Otherwise we discard the path. With n <= 12 digits and at most 3 choices per slot, total work is bounded by 3^4 = 81 paths — tiny.

Examples

Example 1
Input: s = "25525511135"
Output: ["255.255.11.135","255.255.111.35"]
Explanation: Two ways to dot-partition this 11-digit string into 4 segments each in [0,255] with no leading zeros.
Example 2
Input: s = "0000"
Output: ["0.0.0.0"]
Explanation: Each segment must be a non-empty digit string in [0,255] without leading zeros; "0" is the only legal single-digit-zero segment.
Example 3
Input: s = "101023"
Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
Explanation: Five valid partitions of 6 digits into 4 segments. Note that "10.10.23" would only have 3 segments and is invalid for that reason.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

backtrackingstringrecursion

Browse all DSA problems