Generate IP Addresses | Practice | GeeksforGeeks

Given a string S containing only digits, Your task is to complete the function genIp() which returns a vector containing all possible combinations of valid IPv4 IP addresses and takes only a string S as its only argument.
Note: Order doesn't matter.

For string 11211 the IP address possible are 
1.1.2.11
1.1.21.1
1.12.1.1
11.2.1.1
Example 1:
Input:
S = 1111
Output: 1.1.1.1

Example 2:
Input:
S = 55
Output: -1

Your Task:
Your task is to complete the function genIp() which returns a vector containing all possible combinations of valid IPv4 IP addresses in sorted order or -1 if no such IP address could be generated through the input string S, the only argument to the function.
Expected Time Complexity: O(N * N * N * N)
Expected Auxiliary Space: O(N * N * N * N)
Constraints:
1<=N<=16
here, N = length of S.
S only contains digits(i.e. 0-9)
0
dev1713 weeks ago
simple c++ with for loops and conditions checks
    vector<string> genIp(string &s) {
        // Your code here
        vector<string>ans;
        for(int a=1;a<=3;a++)
         for(int b=1;b<=3;b++)
          for(int c=1;c<=3;c++)
           for(int d=1;d<=3;d++)
           if(a+b+c+d==s.size()){
               int A=stoi(s.substr(0,a));
               int B=stoi(s.substr(a,b));
               int C=stoi(s.substr(a+b,c));
               int D=stoi(s.substr(a+b+c,d));
               string temp;
               if(A<=255 && B<=255 && C<=255 &&D<=255){
                   temp=to_string(A)+"."+to_string(B)+"."+to_string(C)+"."+to_string(D);
               if(temp.size()==s.size()+3)
               ans.push_back(temp);
               }
           }
           return ans;
    }
-1
shashankrustagii3 months ago
class Solution{
  public:
    vector<string> genIp(string &s) {
        vector<string>res;
        string ans;
        for(int a=1;a<=3;a++)
            for(int b=1;b<=3;b++)
                for(int c=1;c<=3;c++)
                    for(int d=1;d<=3;d++)
                        if(a+b+c+d==s.length()){
                            int w=stoi(s.substr(0,a)),x=stoi(s.substr(a,b)), y=stoi(s.substr(a+b,c)), z=stoi(s.substr(a+b+c,d));
                            if(w<=255 and x<=255 and y<=255 and z<=255)
                                if((ans=to_string(w)+"."+to_string(x)+"."+to_string(y)+"."+to_string(z)).size()==s.length()+3)
                                    res.push_back(ans);
                        }
        return res;
    }
};
0
nikhar25003 months ago
c++ codebool check(string s)   {       if( s != "" and s.size()<4)       {           if(s[0] == '0' and s.size() > 1)           {               return false;           }           else if(stoi(s) >=0 and stoi(s)<=255)           {                   return true;           }       }       return false;   }   void validip(string&s,int&i, int&j, int&k, vector<string>&temp)   {       string first = "",second = "",third = "",four = "";              for(int x=0; x<=i; x++)       first += s[x];              for(int x=i+1; x<=j; x++)       second += s[x];              for(int x=j+1; x<=k; x++)       third += s[x];              for(int x=k+1; x<s.size(); x++)       four += s[x];          if(check(first) and check(second) and check(third) and check(four) == true)       {           temp.push_back("T");           temp.push_back(first + "." + second + "." + third + "." + four);           return;       }       else       {           temp.push_back("F");           return;       }          }   vector<string> genIp(string &s) {       // Your code here       int n = s.size();       vector<string> ans;       for(int i=0; i<n-3; i++)       {           for(int j=i+1; j<n-2; j++)           {               for(int k=j+1; k<n-1; k++)               {                   vector<string>temp;                   validip(s,i,j,k,temp);                   if(temp[0] == "T")                   {                       ans.push_back(temp[1]);                   }               }           }       }              return ans;   }
};
+2
singhsanskar20003 months ago
vector<string> genIp(string &s) {
        vector<string>res;
        string ans;
        for(int a=1;a<=3;a++){
            for(int b=1;b<=3;b++){
                for(int c=1;c<=3;c++){
                    for(int d=1;d<=3;d++){
                        if(a+b+c+d==s.length()){
                            int w=stoi(s.substr(0,a));
                            int x=stoi(s.substr(a,b));
                            int y=stoi(s.substr(a+b,c));
                            int z=stoi(s.substr(a+b+c,d));
                            if(w<=255 and x<=255 and y<=255 and z<=255){
                                if((ans=to_string(w)+"."+to_string(x)+"."+to_string(y)+"."+to_string(z)).size()==s.length()+3){
                                    res.push_back(ans);
                                }
                            }
                        }
                    }
                }
            }
        }
        return res;
    }
0
sandeep55213 months ago
Easy To Understand Backtracking solution in C++.
class Solution{
 public:
   void func(string s,vector<string> &ans,string v,int i,int d) // evolved brute force by backtracking
   {
       if(i==s.size() and d==4) // base case
       {
           v.pop_back();
           ans.push_back(v);
           return;
       }
       if(i==s.size() or d==4) // fail case
           return;
       string t; // very useful but temporary string
       for (int j = i; j < s.size(); j++)
       {
           t.push_back(s[j]);
           if(t.size()==2 and t[0]=='0') // invalid ip
               return;
           if(t.size()>3 or stoi(t)>255) // invalid ip
               return;
           v.push_back(s[j]);
           v.push_back('.');
           func(s,ans,v,j+1,d+1);
           v.pop_back(); // backtracking
       }
   }
   vector<string> genIp(string &s) {
       vector<string> ans;
       func(s,ans,"",0,0);
       return ans;
   }
};
0
himanshujain4574 months ago
SIMPLEST CODE:
 vector<string> genIp(string &s)   {       vector<string>v;       set<string>mp;       int n=s.length();       for(int i=0;i<n-3;i++)       {           for(int j=i+1;j<n-2;j++)           {               for(int k=j+1;k<n-1;k++)               {                   for(int l=k+1;l<n;l++)                   {                      string t1=s.substr(0,j);                      string t2=s.substr(j,k-j);                      string t3=s.substr(k,l-k);                      string t4=s.substr(l);                      if(t1.length()>3||t2.length()>3||t3.length()>3||t4.length()>3)                      continue;           if(stol(t1)<256 and stol(t2)<256 and stol(t3)<256 and stol(t4)<256)                      {                          string temp=t1+'.'+t2+'.'+t3+'.'+t4;                          if((t1[0]=='0' and t1.length()>1)||                          (t2[0]=='0' and t2.length()>1)||                          (t3[0]=='0' and t3.length()>1)||                          (t4[0]=='0' and t4.length()>1))                          continue;                          else                          {                             //v.push_back(temp);                              mp.insert(temp);                          }                      }                   }               }           }       }       for(auto e:mp)       v.push_back(e);              sort(v.begin(),v.end());       return v;          } 
0
anutiger4 months ago
    vector<string> res;
    void solve(string s,string t,int cnt){
        if(s.length() == 0  and cnt == 4){
            t.pop_back();
            res.push_back(t);
            return;
        }
        for(int i  = 0; i < s.length() ; i++){
            string d = s.substr(0 , i  + 1);
            if(d[0] == '0' and d.length() > 1) continue;
            if(stol(d) < 256){
                string tmp  = s.substr(i + 1);
                solve(tmp,t + d + '.' , cnt + 1);
            }else return;
        }
    }
    vector<string> genIp(string &s) {
        res.clear();
        solve(s, "" , 0);
        return res;
    }
0
danail kozhuharov
This comment was deleted.
0
hunkthanatos5 months ago
Can anyone tell me how to optimise this?
 
public ArrayList<String> genIp(String s) {
        // code here
        ArrayList<String> arr = new ArrayList<String>();
        String op="";
        solve(s,0,op,arr);
        
        ArrayList<String> res = new ArrayList<String>();
        for(String sp: arr){
            if(validIP(sp))
                res.add(sp);
        }
        return res;
    }
    
    public void solve(String s, int i, String op, ArrayList<String> arr){
        
        if(i == s.length()){
            arr.add(op);
            return;
        }
        
        solve(s, i+1, op+s.charAt(i)+".", arr);
        solve(s, i+1, op+s.charAt(i), arr);
    }
    
    public boolean validIP (String ip) {
        try {
            if ( ip == null || ip.isEmpty() ) {
                return false;
            }
    
            String[] parts = ip.split( "\\." );
            if ( parts.length != 4 ) {
                return false;
            }
    
            for ( String s : parts ) {
                int i = Integer.parseInt( s );
                if ( (i < 0) || (i > 255) ) {
                    return false;
                }
            }
            if ( ip.endsWith(".") ) {
                return false;
            }
    
            return true;
        } catch (NumberFormatException nfe) {
            return false;
        }
    }
+1
whitewolf057 months ago
Can anyOne say what is wrong in this code:
 
 
class Solution {   public ArrayList<String> genIp(String s) {       // code here       ArrayList<String> al = new ArrayList<>();       int n = s.length();              for(int i =0; i<n-3; i++){           for(int j=i;j<n-2; j++){               for(int k=j; j<n-1;j++){                   if(isValid(s,i, j, k)){                       al.add(makeIp(s, i, j, k));                   }               }           }       }       return al;   }      public boolean isValid(String s, int i, int j, int k){       String A = s.substring(0,i);       String B = s.substring(i+1, j);       String C = s.substring(j+1, k);       String D = s.substring(k+1, s.length()-1);              int a = Integer.parseInt(A);       int b = Integer.parseInt(B);       int c = Integer.parseInt(C);       int d = Integer.parseInt(D);                     if(A.length()>0 && A.length()<=3 || B.length()>0 && B.length()<=3 || C.length()>0 &&                C.length()<=3 || D.length()>0 && D.length()<=3){                   return true;               }       if(A.charAt(0)=='0' && A.length() == 1 || B.charAt(0)=='0' && B.length() == 1 ||            C.charAt(0)=='0' && C.length() == 1 || D.charAt(0)=='0' && D.length() == 1 )                   return true;                         if(a>=0 && a<=255 || b>=0 && b<=255 ||c>=0 && c<=255 ||d>=0 && d<=255 ){           return true;       }                     return false;          }      public String makeIp(String s, int i, int j, int k){       String res="";       for(int a =0; a<s.length(); a++){           if(a==i+1||a==j+1||a==k+1){               res= res+".";           }           res+= s.charAt(a);       }              return res;   }}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.