Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Generate Valid IP Addresses from String
Next article icon

Generate Valid IP Addresses from String

Last Updated : 28 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a String containing only digits, the task is to 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.

Examples:

Input: "255678166"
Output: [“25.56.78.166”, “255.6.78.166”, "255.67.8.166", "255.67.81.66"]
Explanation: These are the only valid possible IP addresses.

Input: "25505011535"
Output: []
Explanation: We cannot generate a valid IP address with this string.

Approach - Using Backtracking with pruning

The idea is to use backtracking and prune recursive branches that would lead to invalid IP addresses.
An IP address consists of 4 valid numbers separated by 3 dots. We have to place these 3 dots at positions such that 4 valid numbers are formed.

One key observation is that the next dot can be placed 1, 2, or 3 positions after the last dot, as the numbers formed must not exceed 255. Additionally, before placing a dot, we check if the current number being formed is valid or invalid. If the number is invalid, we will backtrack and explore other available options.

Step by Step implementation

  • First place dots in the string to form valid IP segments.
  • Check whether the current segment is valid before continuing. If it is invalid prune that recursive branch.
  • Stop once 3 dots are placed, ensuring the final segment is valid.
C++
// C++ program to generate all possible valid // ip address using backtracking  #include <algorithm> #include <iostream> #include <string> #include <vector>  using namespace std;  // Function to check whether segment is valid or not. bool isValid(string &s) {     int n = s.size();    	// Segment of lenght one are always valid     if (n == 1)          return true; 	   	// converting string into integer      int val = stoi(s);        // Invalid case: If it has preceding zero or    	// if its value is greater than 255.     if (s[0] == '0' || val > 255)          return false;   	     return true; }  // Recursive helper Function to generate valid IP address void generateIpRec(string &s, int index, string curr, int cnt,                     				vector<string> &res) {     string temp = ""; 	   	// Base case: Reached end of string and    	// all 4 segments were not completed     if (index >= s.size())        	return;  	if (cnt == 3) {         temp = s.substr(index);          // Checking 4th(last) segment of ip address         if (temp.size() <= 3 && isValid(temp) )              res.push_back(curr+temp);                  return;     }      for (int i = index; i < min(index + 3, (int)s.size()); i++) {                  // creating next segment of ip address.         temp = temp + s[i];          // If the created segment is valid.         if (isValid(temp)) {           	           	// Generate the remaining segments of IP             generateIpRec(s, i + 1, curr + temp + '.', cnt + 1, res);         }     } }  // Function to generate valid IP address vector<string> generateIp(string s) {     vector<string> res;      generateIpRec(s, 0, "", 0, res);     return res; }  int main() {     string s = "255678166";     vector<string> res = generateIp(s);      for (string ip : res)          cout << ip << endl; } 
Java
// Java program to generate all possible valid // ip address using backtracking import java.util.ArrayList;  class GfG {        // Function to check whether segment is valid or not.     static boolean isValid(String s) {         int n = s.length();          // Segment of length one is always valid         if (n == 1)              return true;          // Converting string into integer         int val = Integer.parseInt(s);          // Invalid case: If it has a preceding zero or        	// its value is greater than 255.         if (s.charAt(0) == '0' || val > 255)              return false;          return true;     }      // Recursive helper function to generate valid IP address     static void generateIpRec(String s, int index, String curr,                                int cnt, ArrayList<String> res) {         String temp = "";          // Base case: Reached end of string and        	// all 4 segments were not completed         if (index >= s.length())              return;          if (cnt == 3) {             temp = s.substring(index);              // Checking 4th (last) segment of IP address             if (temp.length() <= 3 && isValid(temp))                  res.add(curr + temp);              return;         }          for (int i = index; i < Math.min(index + 3, s.length()); i++) {             // Creating next segment of IP address             temp += s.charAt(i);              // If the created segment is valid             if (isValid(temp)) {                 // Generate the remaining segments of IP                 generateIpRec(s, i + 1, curr + temp + ".", cnt + 1, res);             }         }     }      // Function to generate valid IP address     static ArrayList<String> generateIp(String s) {         ArrayList<String> res = new ArrayList<>();         generateIpRec(s, 0, "", 0, res);         return res;     }      public static void main(String[] args) {         String s = "255678166";         ArrayList<String> res = generateIp(s);          for (String ip : res)              System.out.println(ip);     } } 
Python
# Python program to generate all possible valid # ip address using backtracking  # Function to check whether segment is valid or not. def isValid(s):     n = len(s)      # Segment of length one is always valid     if n == 1:         return True      # Converting string into integer     val = int(s)      # Invalid case: If it has a preceding zero or      # its value is greater than 255     if s[0] == '0' or val > 255:         return False      return True  # Recursive helper function to generate valid IP address def generateIpRec(s, index, curr, cnt, res):     temp = ""      # Base case: Reached end of string and      # all 4 segments were not completed     if index >= len(s):         return      if cnt == 3:         temp = s[index:]          # Checking 4th (last) segment of IP address         if len(temp) <= 3 and isValid(temp):             res.append(curr + temp)          return      for i in range(index, min(index + 3, len(s))):         # Creating next segment of IP address         temp += s[i]          # If the created segment is valid         if isValid(temp):             # Generate the remaining segments of IP             generateIpRec(s, i + 1, curr + temp + ".", cnt + 1, res)  # Function to generate valid IP address def generateIp(s):     res = []     generateIpRec(s, 0, "", 0, res)     return res  if __name__ == "__main__":     s = "255678166"     res = generateIp(s)          for ip in res:         print(ip) 
C#
// C# program to generate all possible valid // ip address using backtracking using System; using System.Collections.Generic;  class GfG {     // Function to check whether segment is valid or not.     static bool isValid(string s) {         int n = s.Length;          // Segment of length one is always valid         if (n == 1)              return true;          // Converting string into integer         int val = int.Parse(s);          // Invalid case: If it has a preceding zero or        	// its value is greater than 255.         if (s[0] == '0' || val > 255)              return false;          return true;     }      // Recursive helper function to generate valid IP address     static void generateIpRec(string s, int index, string curr,                                	int cnt, List<string> res) {         string temp = "";          // Base case: Reached end of string and        	// all 4 segments were not completed         if (index >= s.Length)              return;          if (cnt == 3) {             temp = s.Substring(index);              // Checking 4th (last) segment of IP address             if (temp.Length <= 3 && isValid(temp))                  res.Add(curr + temp);              return;         }          for (int i = index; i < Math.Min(index + 3, s.Length); i++) {             // Creating next segment of IP address             temp += s[i];              // If the created segment is valid             if (isValid(temp)) {                 // Generate the remaining segments of IP                 generateIpRec(s, i + 1, curr + temp + ".", cnt + 1, res);             }         }     }      // Function to generate valid IP address     static List<string> generateIp(string s) {         List<string> res = new List<string>();         generateIpRec(s, 0, "", 0, res);         return res;     }      static void Main(string[] args) {         string s = "255678166";         List<string> res = generateIp(s);          foreach (string ip in res)              Console.WriteLine(ip);     } } 
JavaScript
// JavaScript program to generate all possible valid // ip address using backtracking  // Function to check whether segment is valid or not. function isValid(s) {     const n = s.length;      // Segment of length one is always valid     if (n === 1)          return true;      // Converting string into integer     const val = parseInt(s, 10);      // Invalid case: If it has a preceding zero or      // its value is greater than 255     if (s[0] === '0' || val > 255)          return false;      return true; }  // Recursive helper function to generate valid IP address function generateIpRec(s, index, curr, cnt, res) {     let temp = "";      // Base case: Reached end of string and      // all 4 segments were not completed     if (index >= s.length)          return;      if (cnt === 3) {         temp = s.substring(index);          // Checking 4th (last) segment of IP address         if (temp.length <= 3 && isValid(temp))              res.push(curr + temp);          return;     }      for (let i = index; i < Math.min(index + 3, s.length); i++) {         // Creating next segment of IP address         temp += s[i];          // If the created segment is valid         if (isValid(temp)) {             // Generate the remaining segments of IP             generateIpRec(s, i + 1, curr + temp + ".", cnt + 1, res);         }     } }  // Function to generate valid IP address function generateIp(s) {     const res = [];     generateIpRec(s, 0, "", 0, res);     return res; }  // Driver code const s = "255678166"; const res = generateIp(s); res.forEach(ip => console.log(ip)); 

Output
25.56.78.166 255.6.78.166 255.67.8.166 255.67.81.66 

Time complexity: O(27*n) = O(n), since total 3 times recursive call is made and number of branches in each recursive call is 3.
Auxiliary Space: O(n), used by temporary strings.


Next Article
Generate Valid IP Addresses from String

A

Abhishek Sharma 44
Improve
Article Tags :
  • Misc
  • Strings
  • Python
  • DSA
  • python-list
  • python-string
  • Python list-programs
  • Python string-programs
Practice Tags :
  • Misc
  • python
  • python-list
  • Strings

Similar Reads

    How to validate an IP address using ReGex
    Given an IP address, the task is to validate this IP address with the help of Regex (Regular Expression) in C++ as a valid IPv4 address or IPv6 address. If the IP address is not valid then print an invalid IP address. Examples: Input: str = "203.120.223.13" Output: Valid IPv4 Input: str = "000.12.23
    5 min read
    Python script to get device vendor name from MAC Address
    Prerequisite: Python Requests A MAC address is a unique identity of a network interface that is used to address the device in a Computer Network. What does MAC Address consist of? A MAC address is made up of 12 hexadecimal digits, 6 octets separated by ':'. There are 6 octets in a MAC address. In th
    2 min read
    How to validate MAC address using Regular Expression
    Given string str, the task is to check whether the given string is a valid MAC address or not by using Regular Expression. A valid MAC address must satisfy the following conditions: It must contain 12 hexadecimal digits.One way to represent them is to form six pairs of the characters separated with
    6 min read
    Program to validate an IP address
    Write a program to Validate an IP Address. An IP address is a unique identifier for devices on a network, enabling internet communication. It has two versions: IPv4 and IPv6. We will validate IPv4 and IPv6 addresses separately.Table of ContentIPv4 Addresses ValidationIPv6 Addresses ValidationIPv4 Ad
    15+ min read
    Convert IP address to integer and vice versa
    We will use the ipaddress module for this purpose. ipaddress is a module that helps in the creation, manipulation and operation on IPv4 and IPv6 addresses and networks. The motivation of converting IP Addresses to integers and vice versa is that other modules that use IP addresses (such as socket) u
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences