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:
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.