File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ Restore IP Addresses
3+ -> IP Address consists of exactly four integers seperated by single dots.
4+ -> Each integer is between 0 and 255.
5+ -> Exempli Gratia - 192.168.1.1 is valid ip address but 192.168@1.1 is an invalid ip address.
6+
7+ We are given with a string containing only digits , return all possible valid IP Addresses that
8+ can be formed by inserting dots in the string.
9+ --> Not allowed to reorder or remove any digits in the string.
10+ --> Return valid IP addresses in any order.
11+
12+ Topics covered: Backtracking
13+
14+ Example:
15+ Input: s = "25525511135"
16+ Output: ["255.255.11.135","255.255.111.35"]
17+
18+ """
19+
20+
21+ class Solution :
22+ def restoreIpAddresses (self , s : str ):
23+ res = []
24+
25+ def backtrack (start , path ):
26+ # Base case: if we have 4 parts and used all digits
27+ if len (path ) == 4 :
28+ if start == len (s ):
29+ res .append ("." .join (path ))
30+ return
31+
32+ # Try segments of length 1 to 3
33+ for l in range (1 , 4 ):
34+ if start + l > len (s ):
35+ break
36+ segment = s [start :start + l ]
37+
38+ # Skip invalid parts (leading zeros or > 255)
39+ if (segment .startswith ('0' ) and len (segment ) > 1 ) or int (segment ) > 255 :
40+ continue
41+
42+ backtrack (start + l , path + [segment ])
43+
44+ backtrack (0 , [])
45+ return res
You can’t perform that action at this time.
0 commit comments