Taro Logo

Restore IP Addresses

#5 Most AskedMedium
0 views
Topics:
StringsRecursion

A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros.

  • For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses.

Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.

Example 1:

Input: s = "25525511135"
Output: ["255.255.11.135","255.255.111.35"]

Example 2:

Input: s = "0000"
Output: ["0.0.0.0"]

Example 3:

Input: s = "101023"
Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

Constraints:

  • 1 <= s.length <= 20
  • s consists of digits only.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the input string s, and can it be empty or contain non-digit characters?
  2. How should we handle numbers with leading zeros (e.g., "03" vs "0")? Are they strictly invalid unless the integer itself is "0"?
  3. If no valid IP address can be formed from the given string, should I return an empty list?
  4. Does the order of the IP addresses in the returned list matter?
  5. Can the integers in the IP address be outside the standard 0 to 255 range?

Brute Force Solution

Approach

Imagine you have a string of digits and you need to slice it into four pieces to form a valid internet address. The brute force approach involves trying every single possible place to make cuts in the string to see what works.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the original sequence of digits.
  2. Try every possible combination of placing three dividing marks somewhere between the digits to break the sequence into four separate pieces.
  3. For every combination you try, check if the four pieces follow the rules of a valid internet address, such as not having leading zeros and staying between zero and two hundred fifty-five.
  4. If a combination of four pieces successfully follows all the rules, save it as a valid answer.
  5. If any piece breaks the rules, throw that combination away.
  6. Repeat this trial-and-error process for every possible placement of the dividing marks until you have tested all of them.

Code Implementation

def restore_ip_addresses(digit_string):
    valid_ip_addresses = []

    # Iterate through all possible lengths for the first three octets to exhaustively test every cut combination
    for first_end in range(1, min(4, len(digit_string))):

        for second_end in range(first_end + 1, min(first_end + 4, len(digit_string))):

            for third_end in range(second_end + 1, min(second_end + 4, len(digit_string))):
                first_octet = digit_string[:first_end]
                second_octet = digit_string[first_end:second_end]
                third_octet = digit_string[second_end:third_end]
                fourth_octet = digit_string[third_end:]

                octets_list = [first_octet, second_octet, third_octet, fourth_octet]

                # Validate each octet to ensure it satisfies IPv4 rules regarding length and numerical limits
                is_valid = True
                for current_octet in octets_list:
                    if len(current_octet) == 0 or len(current_octet) > 3:
                        is_valid = False
                        break
                    if current_octet[0] == '0' and len(current_octet) > 1:
                        is_valid = False
                        break
                    if int(current_octet) > 255:
                        is_valid = False
                        break

                # Append successfully verified configurations to our collection of valid internet addresses
                if is_valid:
                    valid_ip_addresses.append(".".join(octets_list))

    return valid_ip_addresses

Big(O) Analysis

Time Complexity
O(1) – The length of the input string n is strictly constrained between 4 and 12 characters because a valid IP address cannot be shorter than 4 digits or longer than 12 digits. Since the input size has a strict upper bound regardless of how large a general input might theoretically be, the number of possible placements for the three dividing marks is a constant maximum. Therefore, testing all combinations takes a constant number of operations, which simplifies to O(1) time complexity.
Space Complexity
O(1) – The auxiliary space is dominated by the recursion stack used to try every possible combination of placing the three dividing marks, which reaches a maximum depth of just 4 levels. Additionally, storing the intermediate four pieces and the resulting valid internet addresses uses a constant amount of extra memory since the maximum number of valid IP addresses for any string is bounded by a small fixed constant rather than scaling with the input length N. Because the maximum depth and the number of stored valid configurations do not grow as the input string length N increases, the auxiliary space complexity remains strictly constant.

Optimal Solution

Approach

To find all valid IP addresses hidden inside a string of digits, the optimal approach uses a systematic trial-and-error strategy. It places three dividing dots across the digits in every possible valid position, checking along the way to ensure each of the four resulting sections follows the proper rules.

Here's how the algorithm would work step-by-step:

  1. Look at the string of digits from the very beginning and decide where to place the first dividing dot.
  2. Ensure that the section before the first dot has a valid length and does not break any rules, such as starting with a zero unless it is just a single zero.
  3. Once the first section is valid, look at the remaining digits and decide where to place the second dot.
  4. Continue this process to place the third dot, which automatically creates the fourth and final section at the very end of the string.
  5. Check if all four sections satisfy the size rules, meaning none of them exceed the maximum allowed value.
  6. If all four sections are valid, save this specific combination as one of the successful answers.
  7. Backtrack to try different positions for the dots until every single valid combination has been discovered and recorded.

Code Implementation

class Solution:
    def restoreIpAddresses(self, input_string: str) -> list[str]:
        valid_ip_addresses = []

        def backtrack_ip_parts(string_index: int, current_parts: list[str]):
            if len(current_parts) == 4 and string_index == len(input_string):
                valid_ip_addresses.append(".".join(current_parts))
                return

            if len(current_parts) == 4 or string_index == len(input_string):
                return

            # We iterate up to 3 digits because an IP octet cannot exceed 255 in length.
            for segment_length in range(1, 4):
                if string_index + segment_length > len(input_string):
                    break

                potential_segment = input_string[string_index:string_index + segment_length]

                # Leading zeros are invalid unless the segment is a single zero character.
                if (potential_segment.startswith("0") and len(potential_segment) > 1) or int(potential_segment) > 255:
                    continue

                current_parts.append(potential_segment)
                
                backtrack_ip_parts(string_index + segment_length, current_parts)
                current_parts.pop()

        backtrack_ip_parts(0, [])
        
        return valid_ip_addresses

Big(O) Analysis

Time Complexity
O(1) – The length of the input string s is strictly constrained between 4 and 12 characters because a valid IPv4 address cannot be shorter than 4 digits or longer than 12 digits. Since the input size n is bounded by a constant maximum of 12, the number of possible dot placements is also finite and independent of any scaling variable. As a result, the backtracking algorithm explores a constant number of states, performing a fixed amount of work that takes O(1) time complexity.
Space Complexity
O(1) – The auxiliary space complexity is considered constant because a valid IPv4 address can contain at most 12 digits, bounding the recursion depth to a maximum of 4 levels and limiting the length of any intermediate path. The number of valid IP addresses generated is also strictly bounded by a small constant, meaning the result storage does not scale with the input length. Consequently, the memory used by the recursion stack and temporary variables remains independent of the input size N.

Edge Cases

String length is less than 4 or greater than 12
How to Handle:
Return an empty list immediately because a valid IPv4 address requires between 4 and 12 digits inclusive.
Segments with leading zeros such as 03
How to Handle:
Prune the recursion branch when a segment starts with zero and has a length greater than one.
Segments exceeding the maximum value of 255
How to Handle:
Validate that the integer value of each formed segment is less than or equal to 255 before proceeding.
Input string containing only zeros like 0000
How to Handle:
Successfully parse and validate each single-digit zero segment to return 0.0.0.0.
No valid IP address combinations can be formed
How to Handle:
The backtracking algorithm naturally exhausts all paths and returns an empty list.
Maximum-sized input of 12 digits
How to Handle:
The algorithm executes in constant time O(1) because the search space is bounded by a maximum of 3 to the power of 4 states.
Input strings containing non-digit characters
How to Handle:
The problem constraints guarantee the string contains only digits, but input validation could reject non-digits if needed.
0/13 completed