Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Recursion & Backtracking

Restore IP Addresses

Medium · Recursion & Backtracking · Asked at Amazon, Microsoft, Meta, Cisco

Insert three dots into the digit string to form a valid IPv4 address: four parts, each between 0 and 255, and no part with a leading zero (0 alone is fine, 01 is not). Print every possible address in lexicographic order, one per line, or NONE if there is none.

Input

A single line with the digits.

Output

The valid IP addresses, or NONE.

Constraints

Backtrack over the four parts, trying lengths 1, 2 and 3 for each. Reject a part that starts with 0 and has more than one digit, or that is above 255. Strings longer than 12 digits have no answer.

Example 1

Input

25525511135

Output

255.255.11.135
255.255.111.35

Example 2

Input

0000

Output

0.0.0.0

Hints

  1. An address is exactly four parts of 1–3 digits.
  2. A part is valid if it is "0" or has no leading zero, and is at most 255.
  3. Try the 3 × 3 × 3 choices of the first three lengths; the fourth length is what remains.

Approach

Backtrack (or use three nested loops) over the lengths of the first three parts; the fourth part takes the rest and must have length 1–3. Keep the split only when all four parts are valid. Collect the addresses, sort them as strings, and print them — or NONE. At most 27 splits are checked, so even a 20-digit string is instant.

Complexity: O(27 · n) time · O(1) extra space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

bool ok(const string &p) {
    if (p.empty() || p.size() > 3) return false;
    if (p.size() > 1 && p[0] == '0') return false;
    return stoi(p) <= 255;
}

int main() {
    string s;
    cin >> s;
    int n = s.size();
    vector<string> res;
    for (int a = 1; a <= 3; a++)
        for (int b = 1; b <= 3; b++)
            for (int c = 1; c <= 3; c++) {
                int d = n - a - b - c;
                if (d < 1 || d > 3) continue;
                string p1 = s.substr(0, a), p2 = s.substr(a, b), p3 = s.substr(a + b, c), p4 = s.substr(a + b + c);
                if (ok(p1) && ok(p2) && ok(p3) && ok(p4)) res.push_back(p1 + "." + p2 + "." + p3 + "." + p4);
            }
    sort(res.begin(), res.end());
    if (res.empty()) cout << "NONE\n";
    for (auto &x : res) cout << x << "\n";
    return 0;
}

Python solution

s = input().strip()
n = len(s)


def ok(p):
    return 1 <= len(p) <= 3 and (p == "0" or p[0] != "0") and int(p) <= 255


res = []
for a in range(1, 4):
    for b in range(1, 4):
        for c in range(1, 4):
            d = n - a - b - c
            if not 1 <= d <= 3:
                continue
            parts = [s[:a], s[a : a + b], s[a + b : a + b + c], s[a + b + c :]]
            if all(ok(p) for p in parts):
                res.append(".".join(parts))
print("\n".join(sorted(res)) if res else "NONE")

Java solution

import java.util.*;

public class Main {
    static boolean ok(String p) {
        if (p.isEmpty() || p.length() > 3) return false;
        if (p.length() > 1 && p.charAt(0) == '0') return false;
        return Integer.parseInt(p) <= 255;
    }

    public static void main(String[] args) {
        String s = new Scanner(System.in).next();
        int n = s.length();
        List<String> res = new ArrayList<>();
        for (int a = 1; a <= 3; a++)
            for (int b = 1; b <= 3; b++)
                for (int c = 1; c <= 3; c++) {
                    int d = n - a - b - c;
                    if (d < 1 || d > 3) continue;
                    String p1 = s.substring(0, a), p2 = s.substring(a, a + b), p3 = s.substring(a + b, a + b + c), p4 = s.substring(a + b + c);
                    if (ok(p1) && ok(p2) && ok(p3) && ok(p4)) res.add(p1 + "." + p2 + "." + p3 + "." + p4);
                }
        Collections.sort(res);
        StringBuilder sb = new StringBuilder();
        if (res.isEmpty()) sb.append("NONE\n");
        for (String x : res) sb.append(x).append('\n');
        System.out.print(sb);
    }
}

Solve Restore IP Addresses online · All practice problems