# Program to generate all possible valid IP addresses from given string

Given a string containing only digits, restore it by returning all possible valid IP address combinations.
A valid IP address must be in the form of A.B.C.D, where A, B, C, and D are numbers from 0-255. The numbers cannot be 0 prefixed unless they are 0.
Examples :

```Input: 25525511135
Output: [“255.255.11.135”, “255.255.111.35”]
Explanation:
These are the only valid possible

Input: "25505011535"
Output: []
Explanation:
We cannot generate a valid IP
```

First, we will place 3 dots in the given string and then try out all the possible combinations for the 3 dots.
Corner case for validity:

```For string "25011255255"
25.011.255.255 is not valid as 011 is not valid.
25.11.255.255 is not valid either as you are not
allowed to change the string.
250.11.255.255 is valid.
```

Approach: Split the string with ‘ . ‘ and then check for all corner cases. Before entering the loop, check the size of the string. Generate all the possible combinations using looping through the string. If IP is found to be valid then return the IP address, else simply return the empty list.

Below is the implementation of the above approach:

## C++

 `// C++ program to generate all possible ` `// valid IP addresses from given string ` `#include ` `using` `namespace` `std; ` ` `  `// Function checks whether IP digits ` `// are valid or not. ` `int` `is_valid(string ip) ` `{ ` `    ``// Splitting by "." ` `    ``vector ips; ` `    ``string ex = ``""``; ` `    ``for` `(``int` `i = 0; i < ip.size(); i++) { ` `        ``if` `(ip[i] == ``'.'``) { ` `            ``ips.push_back(ex); ` `            ``ex = ``""``; ` `        ``} ` `        ``else` `{ ` `            ``ex = ex + ip[i]; ` `        ``} ` `    ``} ` `    ``ips.push_back(ex); ` ` `  `    ``// Checking for the corner cases ` `    ``// cout << ip << endl; ` `    ``for` `(``int` `i = 0; i < ips.size(); i++) { ` `        ``// cout << ips[i] < 3 ` `            ``|| stoi(ips[i]) < 0 ` `            ``|| stoi(ips[i]) > 255) ` `            ``return` `0; ` ` `  `        ``if` `(ips[i].length() > 1 ` `            ``&& stoi(ips[i]) == 0) ` `            ``return` `0; ` ` `  `        ``if` `(ips[i].length() > 1 ` `            ``&& stoi(ips[i]) != 0 ` `            ``&& ips[i] == ``'0'``) ` `            ``return` `0; ` `    ``} ` `    ``return` `1; ` `} ` ` `  `// Function converts string to IP address ` `void` `convert(string ip) ` `{ ` `    ``int` `l = ip.length(); ` ` `  `    ``// Check for string size ` `    ``if` `(l > 12 || l < 4) { ` `        ``cout << ``"Not Valid IP Address"``; ` `    ``} ` ` `  `    ``string check = ip; ` `    ``vector ans; ` ` `  `    ``// Generating different combinations. ` `    ``for` `(``int` `i = 1; i < l - 2; i++) { ` `        ``for` `(``int` `j = i + 1; j < l - 1; j++) { ` `            ``for` `(``int` `k = j + 1; k < l; k++) { ` `                ``check = check.substr(0, k) + ``"."` `                        ``+ check.substr(k, l - k + 2); ` `                ``check ` `                    ``= check.substr(0, j) + ``"."` `                      ``+ check.substr(j, l - j + 3); ` `                ``check ` `                    ``= check.substr(0, i) + ``"."` `                      ``+ check.substr(i, l - i + 4); ` ` `  `                ``// cout<< check <

## Java

 `// Java Program to generate all possible ` `// valid IP addresses from given string ` `import` `java.util.*; ` ` `  `class` `GFG { ` ` `  `    ``// Function to restore Ip Addresses ` `    ``public` `static` `ArrayList ` `    ``restoreIpAddresses(String A) ` `    ``{ ` `        ``if` `(A.length() < ``3` `|| A.length() > ``12``) ` `            ``return` `new` `ArrayList<>(); ` `        ``return` `convert(A); ` `    ``} ` ` `  `    ``private` `static` `ArrayList ` `    ``convert(String s) ` `    ``{ ` `        ``ArrayList l = ``new` `ArrayList<>(); ` `        ``int` `size = s.length(); ` ` `  `        ``String snew = s; ` ` `  `        ``for` `(``int` `i = ``1``; i < size - ``2``; ` `             ``i++) { ` `            ``for` `(``int` `j = i + ``1``; ` `                 ``j < size - ``1``; j++) { ` `                ``for` `(``int` `k = j + ``1``; ` `                     ``k < size; k++) { ` `                    ``snew ` `                        ``= snew.substring(``0``, k) + ``"."` `                          ``+ snew.substring(k); ` `                    ``snew ` `                        ``= snew.substring(``0``, j) + ``"."` `                          ``+ snew.substring(j); ` `                    ``snew ` `                        ``= snew.substring(``0``, i) + ``"."` `                          ``+ snew.substring(i); ` ` `  `                    ``if` `(isValid(snew)) { ` `                        ``l.add(snew); ` `                    ``} ` `                    ``snew = s; ` `                ``} ` `            ``} ` `        ``} ` ` `  `        ``Collections.sort(l, ``new` `Comparator() { ` `            ``public` `int` `compare(String o1, String o2) ` `            ``{ ` `                ``String a1[] = o1.split(``"[.]"``); ` `                ``String a2[] = o2.split(``"[.]"``); ` ` `  `                ``int` `result = -``1``; ` `                ``for` `(``int` `i = ``0``; i < ``4` `                                ``&& result != ``0``; ` `                     ``i++) { ` `                    ``result = a1[i].compareTo(a2[i]); ` `                ``} ` `                ``return` `result; ` `            ``} ` `        ``}); ` `        ``return` `l; ` `    ``} ` ` `  `    ``private` `static` `boolean` `isValid(String ip) ` `    ``{ ` `        ``String a[] = ip.split(``"[.]"``); ` `        ``for` `(String s : a) { ` `            ``int` `i = Integer.parseInt(s); ` `            ``if` `(s.length() > ``3` `|| i < ``0` `|| i > ``255``) { ` `                ``return` `false``; ` `            ``} ` `            ``if` `(s.length() > ``1` `&& i == ``0``) ` `                ``return` `false``; ` `            ``if` `(s.length() > ``1` `&& i != ``0` `                ``&& s.charAt(``0``) == ``'0'``) ` `                ``return` `false``; ` `        ``} ` ` `  `        ``return` `true``; ` `    ``} ` ` `  `    ``// Driver Code ` `    ``public` `static` `void` `main(String[] args) ` `    ``{ ` `        ``System.out.println( ` `            ``restoreIpAddresses( ` `                ``"25525511135"``) ` `                ``.toString()); ` `    ``} ` `} ` ` `  `// This code is contributed by Nidhi Hooda. `

## Python3

 `# Python3 code to check valid possible IP ` ` `  `# Function checks whether IP digits ` `# are valid or not. ` `def` `is_valid(ip): ` ` `  `    ``# Splitting by "." ` `    ``ip ``=` `ip.split(``"."``) ` `     `  `    ``# Checking for the corner cases ` `    ``for` `i ``in` `ip: ` `        ``if` `(``len``(i) > ``3` `or` `int``(i) < ``0` `or`  `                          ``int``(i) > ``255``): ` `            ``return` `False` `        ``if` `len``(i) > ``1` `and` `int``(i) ``=``=` `0``: ` `            ``return` `False` `        ``if` `(``len``(i) > ``1` `and` `int``(i) !``=` `0` `and` `            ``i[``0``] ``=``=` `'0'``): ` `            ``return` `False` `             `  `    ``return` `True` ` `  `# Function converts string to IP address ` `def` `convert(s): ` `     `  `    ``sz ``=` `len``(s) ` ` `  `    ``# Check for string size ` `    ``if` `sz > ``12``: ` `        ``return` `[] ` `    ``snew ``=` `s ` `    ``l ``=` `[] ` ` `  `    ``# Generating different combinations. ` `    ``for` `i ``in` `range``(``1``, sz ``-` `2``): ` `        ``for` `j ``in` `range``(i ``+` `1``, sz ``-` `1``): ` `            ``for` `k ``in` `range``(j ``+` `1``, sz): ` `                ``snew ``=` `snew[:k] ``+` `"."` `+` `snew[k:] ` `                ``snew ``=` `snew[:j] ``+` `"."` `+` `snew[j:] ` `                ``snew ``=` `snew[:i] ``+` `"."` `+` `snew[i:] ` `                 `  `                ``# Check for the validity of combination ` `                ``if` `is_valid(snew): ` `                    ``l.append(snew) ` `                     `  `                ``snew ``=` `s ` `                 `  `    ``return` `l  ` ` `  `# Driver code          ` `A ``=` `"25525511135"` `B ``=` `"25505011535"` ` `  `print``(convert(A)) ` `print``(convert(B)) `

Output:

```['255.255.11.135', '255.255.111.35']
```

Complexity Analysis:

• Time Complexity: O(n^3), where n is the length of the string
Three nested traversal of the string is needed, where n is always less than 12.
• Auxiliary Space: O(n).
As as extra space is needed.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

5

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.