algoadvance

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

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

Example:

Input:

address = "1.1.1.1"

Output:

"1[.]1[.]1[.]1"

Clarifying Questions:

  1. Q: Can the input strings contain characters other than digits and periods?
    • A: No, the input will always be a valid IPv4 address, containing only digits and periods.
  2. Q: Are there any constraints on the length of the input string?
    • A: The length of the input string can be up to 15 characters, as the longest IPv4 address (255.255.255.255) has 15 characters.
  3. Q: Can the input string be empty?
    • A: No, the input will always contain a valid IPv4 address.

Strategy:

To solve this problem, we simply need to replace all occurrences of the period character . with [.].

Python’s string replace method is ideal for this task, as it allows direct replacement of substrings in a straightforward and efficient manner.

Steps:

  1. Use the replace method on the input string address to replace all . with [.].
  2. Return the resulting string.

Code:

def defangIPaddr(address: str) -> str:
    # Replace all occurrences of '.' with '[.]'
    return address.replace('.', '[.]')

Time Complexity:

The time complexity of the solution is O(n), where n is the length of the input string, because the replace method needs to traverse the string to replace each occurrence of ..

This approach is both time-efficient and space-efficient for the given problem constraints.

Try our interview co-pilot at AlgoAdvance.com