We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Defanging an IP Address

Number: 1205

Difficulty: Easy

Paid? No

Companies: Google, Meta, Amazon, Adobe, Apple, Bloomberg


Problem Description

Given a valid IPv4 address, return a defanged version of that IP address by replacing every period "." with "[.]".


Key Insights

  • The problem is straightforward: it requires a simple string replacement.
  • Since IPv4 addresses have a fixed, small structure, iterating through the string or using built-in string methods will be efficient.
  • Edge cases are minimal because the input is guaranteed to be a valid IPv4 address.

Space and Time Complexity

Time Complexity: O(n) where n is the length of the address string. Space Complexity: O(n) for storing the new defanged string.


Solution

The solution can use a built-in string method to replace all occurrences of "." with "[.]" in the provided IP address. This approach is both efficient and clear. In languages without a built-in replace function, a simple iteration over each character and an append operation to a new string can be used. This maintains the same O(n) time complexity. The key data structure used here is the string itself, and the algorithmic approach involves either a single pass through the string or leveraging an optimized library function for string replacement.


Code Solutions

# Define the function to defang the IP address
def defang_ip_address(address):
    # Use the built-in string replace method to replace "." with "[.]"
    return address.replace(".", "[.]")

# Example usage:
if __name__ == "__main__":
    test_address = "255.100.50.0"
    print(defang_ip_address(test_address))  # Expected output: "255[.]100[.]50[.]0"
← Back to All Questions