Generate Valid IP Addresses from String

Last Updated : 12 Mar, 2026

Given a string s consisting only of digits, return all possible valid IP address combinations that can be formed from it. A valid IP address consists of four numbers (0–255) separated by dots.

Note: A segment cannot contain leading zeros unless the number itself is 0. For example, 1.1.2.11 and 0.11.21.1 are valid IP addresses, while 01.1.2.11 and 00.11.21.1 are not valid because they contain leading zeros.

Examples:

Input: s = "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: s = "25505011535"
Output: []
Explanation: We cannot generate a valid IP address with this string.

Try It Yourself
redirect icon

Using Backtracking with Pruning

We generate all possible ways to place 3 dots in the string to form 4 segments. During the process, we only continue if the current segment is valid (0–255 and no leading zeros). If a segment becomes invalid, we prune that branch to avoid unnecessary exploration.

Step by Step implementation

  • Start backtracking from the beginning of the string and try forming segments.
  • Choose segment lengths of 1, 2, or 3 digits, since a valid IP part cannot exceed 3 digits.
  • Validate the segment: it must be between 0 and 255 and must not contain leading zeros.
  • If the segment is valid, place a dot and recursively process the remaining string.
  • Prune the recursion if a segment becomes invalid.
  • Stop when 3 dots are placed and check whether the final segment is valid.
  • If all 4 segments are valid, store the formed IP address.
C++
//Driver Code Starts
#include <iostream>
#include <string>
#include <vector>
using namespace std;

//Driver Code Ends

// Check if a segment is a valid IP part
bool isValid(const string &s)
{
    if (s.size() > 1 && s[0] == '0')
    {

        // leading zero not allowed
        return false;
    }

    int val = stoi(s);
    return val <= 255;
}

// Recursive function to generate IP addresses
void generateIpRec(const string &s, int index, string curr, int cnt, vector<string> &res)
{

    if (index >= s.size())
        return;

    // If 3 dots are placed, validate the last segment
    if (cnt == 3)
    {
        string last = s.substr(index);
        if (last.size() <= 3 && isValid(last))
            res.push_back(curr + last);
        return;
    }

    string segment = "";

    // Try segment lengths 1 to 3
    for (int i = index; i < min(index + 3, (int)s.size()); i++)
    {
        segment += s[i];

        if (isValid(segment))
        {
            generateIpRec(s, i + 1, curr + segment + ".", cnt + 1, res);
        }
    }
}

// Generate all valid IP addresses
vector<string> generateIp(string s)
{
    vector<string> res;
    generateIpRec(s, 0, "", 0, res);
    return res;
}

//Driver Code Starts

int main()
{
    string s = "255678166";
    vector<string> res = generateIp(s);

    for (string ip : res)
        cout << ip << endl;
}
//Driver Code Ends
Java
import java.util.List;
import java.util.ArrayList;

class GfG{

    // Check if segment is valid
    static boolean isValid(String s) {
        if (s.length() > 1 && s.charAt(0) == '0')
            return false;

        int val = Integer.parseInt(s);
        return val <= 255;
    }

    static void generateIpRec(String s, int index, String curr, int cnt, List<String> res) {

        if (index >= s.length())
            return;

        // Validate last segment
        if (cnt == 3) {
            String last = s.substring(index);
            if (last.length() <= 3 && isValid(last))
                res.add(curr + last);
            return;
        }

        String segment = "";

        // Try segment length 1–3
        for (int i = index; i < Math.min(index + 3, s.length()); i++) {
            segment += s.charAt(i);

            if (isValid(segment))
                generateIpRec(s, i + 1, curr + segment + ".", cnt + 1, res);
        }
    }

    static List<String> generateIp(String s) {
        List<String> res = new ArrayList<>();
        generateIpRec(s, 0, "", 0, res);
        return res;
    }

    public static void main(String[] args) {
        String s = "255678166";
        List<String> res = generateIp(s);

        for (String ip : res)
            System.out.println(ip);
    }
}
Python
# Check if segment is valid
def isValid(s):
    if len(s) > 1 and s[0] == '0':
        return False
    return int(s) <= 255


def generateIpRec(s, index, curr, cnt, res):

    if index >= len(s):
        return

    # Validate last segment
    if cnt == 3:
        last = s[index:]
        if len(last) <= 3 and isValid(last):
            res.append(curr + last)
        return

    segment = ""

    # Try segment length 1–3
    for i in range(index, min(index + 3, len(s))):
        segment += s[i]

        if isValid(segment):
            generateIpRec(s, i + 1, curr + segment + ".", cnt + 1, res)


def generateIp(s):
    res = []
    generateIpRec(s, 0, "", 0, res)
    return res


#Driver Code Starts

if __name__ == "__main__":
    s = "255678166"
    res = generateIp(s)

    for ip in res:
        print(ip)

#Driver Code Ends
C#
//Driver Code Starts
using System;
using System.Collections.Generic;

class GfG {

    // Check if segment is valid
//Driver Code Ends

    static bool isValid(string s) {
        if (s.Length > 1 && s[0] == '0')
            return false;

        int val = int.Parse(s);
        return val <= 255;
    }

    static void generateIpRec(string s, int index, string curr, int cnt, List<string> res) {

        if (index >= s.Length)
            return;

        // Validate last segment
        if (cnt == 3) {
            string last = s.Substring(index);
            if (last.Length <= 3 && isValid(last))
                res.Add(curr + last);
            return;
        }

        string segment = "";

        // Try segment length 1–3
        for (int i = index; i < Math.Min(index + 3, s.Length); i++) {
            segment += s[i];

            if (isValid(segment))
                generateIpRec(s, i + 1, curr + segment + ".", cnt + 1, res);
        }
    }

    static List<string> generateIp(string s) {
        List<string> res = new List<string>();
        generateIpRec(s, 0, "", 0, res);
        return res;
    }

//Driver Code Starts

    static void Main() {
        string s = "255678166";
        List<string> res = generateIp(s);

        foreach (string ip in res)
            Console.WriteLine(ip);
    }
}
//Driver Code Ends
JavaScript
// Check if segment is valid
function isValid(s) {
    if (s.length > 1 && s[0] === '0')
        return false;

    return parseInt(s) <= 255;

    // Driver code
}

function generateIpRec(s, index, curr, cnt, res) {

    if (index >= s.length)
        return;

    // Validate last segment
    if (cnt === 3) {
        let last = s.substring(index);
        if (last.length <= 3 && isValid(last))
            res.push(curr + last);
        return;
    }

    let segment = "";

    // Try segment length 1–3
    for (let i = index; i < Math.min(index + 3, s.length); i++) {
        segment += s[i];

        if (isValid(segment))
            generateIpRec(s, i + 1, curr + segment + ".", cnt + 1, res);
    }
}

function generateIp(s) {
    let res = [];
    generateIpRec(s, 0, "", 0, res);
    return res;
}


//Driver Code Starts
// Driver code
let s = "255678166";
let res = generateIp(s);

for (let ip of res)
    console.log(ip);
//Driver Code Ends

Output
25.56.78.166
255.6.78.166
255.67.8.166
255.67.81.66

Time Complexity

  • O(27 × n) ≈ O(n)
  • At each step, we can choose a segment of 1, 2, or 3 digits → 3 choices.
  • Since 3 dots are placed, the maximum combinations explored are 3 × 3 × 3 = 27.
  • Each combination may process up to n characters.

Auxiliary Space

  • O(n)
  • Used by temporary strings and recursion stack during backtracking.
Comment