KatInterview

93. Restore IP Addresses

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Backtracking with Pruning

The problem asks us to find all possible ways to insert three dots into a string of digits to form a valid IP address. A valid IP address has four parts (octets), each ranging from 0 to 255, without extra leading zeros (e.g., "01" is invalid, but "0" is valid).

Solution

Restore IP Addresses in Python

class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        result = []
        n = len(s)

        # An IP address must have 4 to 12 digits.
        if not (4 <= n <= 12):
            return []

        def backtrack(start_index, current_path):
            # If we have 4 parts and have used up the whole string, we found a valid IP.
            if len(current_path) == 4:
                if start_index == n:
                    result.append(".".join(current_path))
                return
            
            # Try to form the next part of the IP address with length 1, 2, or 3.
            for length in range(1, 4):
                end_index = start_index + length
                if end_index > n:
                    break
                
                segment = s[start_index:end_index]

                # Rule 1: No leading zeros, unless the number is 0 itself.
                if len(segment) > 1 and segment[0] == '0':
                    break  # Any longer segment will also have a leading zero.
                
                # Rule 2: The number must be between 0 and 255.
                if int(segment) > 255:
                    break # Any longer segment will also be > 255.
                
                # If the segment is valid, add it to our path and recurse.
                current_path.append(segment)
                backtrack(end_index, current_path)
                current_path.pop() # Backtrack

        backtrack(0, [])
        return result

Restore IP Addresses in Java

class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> result = new ArrayList<>();
        int n = s.length();

        // An IP address must have 4 to 12 digits.
        if (n < 4 || n > 12) {
            return result;
        }

        backtrack(s, 0, new ArrayList<>(), result);
        return result;
    }

    private void backtrack(String s, int startIndex, List<String> currentPath, List<String> result) {
        // If we have 4 parts and have used up the whole string, we found a valid IP.
        if (currentPath.size() == 4) {
            if (startIndex == s.length()) {
                result.add(String.join(".", currentPath));
            }
            return;
        }

        // Try to form the next part of the IP address with length 1, 2, or 3.
        for (int length = 1; length <= 3 && startIndex + length <= s.length(); length++) {
            String segment = s.substring(startIndex, startIndex + length);

            // Rule 1: No leading zeros, unless the number is 0 itself.
            if (segment.length() > 1 && segment.charAt(0) == '0') {
                break; // Any longer segment will also have a leading zero.
            }

            // Rule 2: The number must be between 0 and 255.
            if (Integer.parseInt(segment) > 255) {
                break; // Any longer segment will also be > 255.
            }

            // If the segment is valid, add it to our path and recurse.
            currentPath.add(segment);
            backtrack(s, startIndex + length, currentPath, result);
            currentPath.remove(currentPath.size() - 1); // Backtrack
        }
    }
}

Restore IP Addresses in C++

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> result;
        vector<string> currentPath;
        int n = s.length();

        // An IP address must have 4 to 12 digits.
        if (n < 4 || n > 12) {
            return result;
        }

        backtrack(s, 0, currentPath, result);
        return result;
    }

private:
    void backtrack(const string& s, int startIndex, vector<string>& currentPath, vector<string>& result) {
        // If we have 4 parts and have used up the whole string, we found a valid IP.
        if (currentPath.size() == 4) {
            if (startIndex == s.length()) {
                string ip = currentPath[0];
                for (int i = 1; i < 4; ++i) {
                    ip += "." + currentPath[i];
                }
                result.push_back(ip);
            }
            return;
        }

        // Try to form the next part of the IP address with length 1, 2, or 3.
        for (int length = 1; length <= 3 && startIndex + length <= s.length(); ++length) {
            string segment = s.substr(startIndex, length);

            // Rule 1: No leading zeros, unless the number is 0 itself.
            if (segment.length() > 1 && segment[0] == '0') {
                break; // Any longer segment will also have a leading zero.
            }

            // Rule 2: The number must be between 0 and 255.
            if (stoi(segment) > 255) {
                break; // Any longer segment will also be > 255.
            }

            // If the segment is valid, add it to our path and recurse.
            currentPath.push_back(segment);
            backtrack(s, startIndex + length, currentPath, result);
            currentPath.pop_back(); // Backtrack to explore other possibilities.
        }
    }
};

Restore IP Addresses in TypeScript

function restoreIpAddresses(s: string): string[] {
    const result: string[] = [];
    const n = s.length;

    // An IP address must have 4 to 12 digits.
    if (n < 4 || n > 12) {
        return [];
    }

    function backtrack(startIndex: number, currentPath: string[]): void {
        // If we have 4 parts and have used up the whole string, we found a valid IP.
        if (currentPath.length === 4) {
            if (startIndex === n) {
                result.push(currentPath.join('.'));
            }
            return;
        }

        // Try to form the next part of the IP address with length 1, 2, or 3.
        for (let length = 1; length <= 3 && startIndex + length <= n; length++) {
            const segment = s.substring(startIndex, startIndex + length);

            // Rule 1: No leading zeros, unless the number is 0 itself.
            if (segment.length > 1 && segment[0] === '0') {
                break; // Any longer segment will also have a leading zero.
            }

            // Rule 2: The number must be between 0 and 255.
            if (parseInt(segment, 10) > 255) {
                break; // Any longer segment will also be > 255.
            }

            // If the segment is valid, add it to our path and recurse.
            currentPath.push(segment);
            backtrack(startIndex + length, currentPath);
            currentPath.pop(); // Backtrack
        }
    }

    backtrack(0, []);
    return result;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.