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.
Input: str = “25525511135”
Input: str = “11111011111”
Approach: This problem can be solved using backtracking. In each call we have three options to create a single block of numbers of a valid ip address:
- Either select only a single digit, add a dot and move onto selecting other blocks (further function calls).
- Or select two digits at the same time, add a dot and move further.
- Or select three consecutive digits and move for the next block.
At the end of the fourth block, if all the digits have been used and the address generated is a valid ip-address then add it to the results and then backtrack by removing the digits selected in the previous call.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Program to generate all possible valid IP addresses from given string
- Iterative program to generate distinct Permutations of a String
- Check whether the given string is a valid identifier
- Program to check if a date is valid or not
- Program to check for a Valid IMEI Number
- Generate all rotations of a given string
- Check if a given string is a valid number (Integer or Floating Point) in Java
- Check if a given string is a valid number (Integer or Floating Point) | SET 1(Basic approach)
- Recursive program to generate power set
- Generate a string with maximum possible alphabets with odd frequencies
- Generate all permutations of a string that follow given constraints
- Generate random String of given size in Java
- Generate a string consisting of characters 'a' and 'b' that satisfy the given conditions
- Generate all binary strings of length n with sub-string "01" appearing exactly twice
- Check if a given string is a valid number (Integer or Floating Point) in Java | SET 2 (Regular Expression approach)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
Improved By : AnkitRai01