
You are given a string “S” containing only digits from 0 to 9. Your task is to find all possible IP addresses that can be obtained from S in lexicographical order. If no valid IP address can be generated from S, return an empty string.
Note:A valid IP address consists of exactly four integers, each integer is between 0 and 255 separated by single dots, and cannot have leading zeros (except if they are zero).
For example-
Following are valid IP addresses.
0.1.24.255
18.5.244.1
Following are invalid IP addresses.
2.01.24.255
18.312.244.1
The first line of input contains a single integer ‘T’, representing the number of test cases or queries to be run. Then the test cases follow.
The only line of each test case contains a string ‘S’.
Output format :
For each test case, print a single line containing all possible valid IP addresses that can be obtained from S separated by a single space.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 1000
0 <= |S| <= 15
where |S| denotes the length of string, S.
S contains only digits from 0 to 9.
Time Limit: 1sec
2
00000
23579
2.3.5.79 2.3.57.9 2.35.7.9 23.5.7.9
For the first test case, no valid IP address can be found.
For the second test case, all possible IP addresses are shown below: [2.3.5.79, 2.3.57.9, 2.35.7.9, 23.5.7.9]
2
5555
02300
5.5.5.5
0.2.30.0 0.23.0.0
For the first test case, there is only one possible IP address that is 5.5.5.5.
For the second test case, all possible IP addresses are shown below:
[0.2.30.0, 0.23.0.0]
Think of a solution using nested for loops.
In this solution, the idea is to divide the given string into 4 parts using 3 dots, where each part corresponds to a number. Then we will add the current IP address to final answer if it satisfies the following conditions:
So we will run 4 nested loops from 1 to 3.
Steps :
O(1).
We are using 3 nested loops, the outer loop runs for min(3, N) times while both inner loops run 3 times. Since the maximum length of S to generate a valid IP address can be 12, the overall time complexity is constant.
O(1), constant space is used.