Taro Logo

Defanging an IP Address

Easy
10 views
a month ago

Given a valid (IPv4) IP address, return a defanged version of that IP address.

A defanged IP address replaces every period "." with "[.]".

For example:

  • Input: address = "1.1.1.1"

  • Output: "1[.]1[.]1[.]1"

  • Input: address = "255.100.50.0"

  • Output: "255[.]100[.]50[.]0"

Write a function that takes a string representing a valid IPv4 address and returns a new string with all periods replaced by [.].

Sample Answer
def defang_ip_address(address: str) -> str:
    """Defangs an IPv4 address by replacing each period "." with "[.]".

    Args:
        address (str): A valid IPv4 address.

    Returns:
        str: The defanged IP address.
    """
    return address.replace(".", "[.]")

# Example usage:
address1 = "1.1.1.1"
defanged_address1 = defang_ip_address(address1)
print(f"Original address: {address1}, Defanged address: {defanged_address1}")

address2 = "255.100.50.0"
defanged_address2 = defang_ip_address(address2)
print(f"Original address: {address2}, Defanged address: {defanged_address2}")

Big(O) Run-time Analysis

The replace() method in Python has a time complexity of O(n), where n is the length of the input string. In this case, the length of the IP address string is relatively small (typically 15 characters for IPv4). Therefore, the run-time complexity can be considered O(1), assuming the length of the IP address is constant.

Big(O) Space Usage Analysis

The replace() method creates a new string. In the worst-case scenario, every character in the original string needs to be replaced. The new string will have the same number of characters as the original. The space required for the new string is O(n). Again, since the length of IP address is relatively small, the space usage can be considered O(1).

Edge Cases

  1. Invalid IP Address Format:

    • If the input string is not a valid IPv4 address (e.g., contains characters other than digits and periods or has an incorrect number of octets), the function will still execute without raising an error. However, the output will not be a properly defanged IP address.
  2. Empty String:

    • If the input string is empty, the function will return an empty string, which is a valid, albeit trivial, output.
  3. String with No Periods:

    • If the input string does not contain any periods, the function will return the original string unchanged.
  4. Leading/Trailing Spaces:

    • If the input string has leading or trailing spaces, these spaces will be included in the defanged output.