LeetCode 1108 - Defanging an IP Address

The problem asks us to transform a valid IPv4 address into its "defanged" version. A defanged IP address is created by replacing every period character "." with the string "[.]". An IPv4 address consists of four numeric segments separated by periods. For example, "1.1.1.

LeetCode Problem 1108

Difficulty: 🟢 Easy
Topics: String

Solution

Problem Understanding

The problem asks us to transform a valid IPv4 address into its "defanged" version. A defanged IP address is created by replacing every period character "." with the string "[.]".

An IPv4 address consists of four numeric segments separated by periods. For example, "1.1.1.1" contains four numbers separated by three periods. The required transformation changes each separator so the final result becomes "1[.]1[.]1[.]1".

The input is a single string named address. The problem guarantees that this string is already a valid IPv4 address, which means we do not need to perform validation checks such as ensuring the numbers are within range or confirming the format. Our only task is to replace every "." character.

The expected output is another string where all periods have been replaced while all numeric characters remain unchanged.

The constraints are intentionally simple. Since the input is guaranteed to be a valid IPv4 address, the string length is very small and fixed in structure. A valid IPv4 address contains exactly three periods and four numeric segments. Because of this, efficiency is not a major concern for this particular problem, but it is still useful to discuss clean and optimal string manipulation techniques.

One important edge case is an address where segments contain multiple digits, such as "255.100.50.0". A naive implementation that incorrectly processes characters or splits the string improperly could accidentally alter the numeric parts. Another consideration is ensuring every period is replaced, not just the first one. The problem guarantee that the input is valid removes concerns about malformed strings, empty input, or missing segments.

Approaches

Brute Force Approach

A straightforward way to solve this problem is to iterate through every character in the string and manually construct a new result string.

For each character:

  • If the character is a period ".", append "[.]" to the result.
  • Otherwise, append the original character.

This approach is correct because every character is examined exactly once, and each period is replaced with the required substring.

However, if implemented inefficiently using repeated string concatenation, it can become slower than necessary in languages where strings are immutable. Every concatenation may create a new string, leading to unnecessary copying work.

Optimal Approach

The key observation is that this problem is simply a global string replacement operation. Most modern languages provide optimized built-in methods for replacing substrings.

Instead of manually processing each character, we can directly replace every "." with "[.]" using:

  • replace() in Python
  • strings.ReplaceAll() in Go

These library functions are implemented efficiently and make the solution concise and readable.

Approach Comparison

Approach Time Complexity Space Complexity Notes
Brute Force O(n) O(n) Iterates character by character and builds a new string
Optimal O(n) O(n) Uses built-in string replacement for cleaner implementation

Algorithm Walkthrough

Optimal Algorithm

  1. Start with the input string address.
  2. Search the string for every occurrence of the period character ".".
  3. Replace each period with the substring "[.]".
  4. Return the newly constructed string.

The reason this works is that the problem only requires a direct character substitution. No parsing or validation is necessary because the input is guaranteed to already be a valid IPv4 address.

Why it works

The algorithm works because it preserves every character in the original string except periods. Each "." is deterministically replaced by "[.]", which exactly matches the problem definition of a defanged IP address. Since every character is processed and every period is replaced exactly once, the final string is guaranteed to be correct.

Python Solution

class Solution:
    def defangIPaddr(self, address: str) -> str:
        return address.replace(".", "[.]")

The implementation uses Python's built-in replace() method. The method scans the string and replaces every occurrence of "." with "[.]".

This directly matches the algorithm described earlier:

  • The original string is used as input.
  • Every period is replaced globally.
  • The resulting transformed string is returned.

Because Python strings are immutable, replace() creates and returns a new string rather than modifying the original one in place.

Go Solution

package main

import "strings"

func defangIPaddr(address string) string {
    return strings.ReplaceAll(address, ".", "[.]")
}

The Go solution uses strings.ReplaceAll() from the standard library. This function replaces every occurrence of the target substring with the replacement substring.

One Go-specific detail is that string utilities are provided through the strings package, so it must be imported explicitly. Unlike Python methods attached directly to the string object, Go uses package functions for these operations.

There are no concerns about integer overflow, nil handling, or mutable string behavior in this problem because the operation is purely string replacement.

Worked Examples

Example 1

Input:

address = "1.1.1.1"

Processing steps:

Step Current String Action
Initial "1.1.1.1" Start with original input
Replace first . "1[.]1.1.1" First period replaced
Replace second . "1[.]1[.]1.1" Second period replaced
Replace third . "1[.]1[.]1[.]1" Third period replaced

Final output:

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

Example 2

Input:

address = "255.100.50.0"

Processing steps:

Step Current String Action
Initial "255.100.50.0" Start with original input
Replace first . "255[.]100.50.0" First period replaced
Replace second . "255[.]100[.]50.0" Second period replaced
Replace third . "255[.]100[.]50[.]0" Third period replaced

Final output:

"255[.]100[.]50[.]0"

Complexity Analysis

Measure Complexity Explanation
Time O(n) Every character in the string is examined once
Space O(n) A new output string is created

The time complexity is linear because the algorithm scans through the input string once to identify replacement locations. The space complexity is also linear because the output string must store the transformed address, which is larger than the original due to the added brackets.

Test Cases

solution = Solution()

# Provided example with single-digit segments
assert solution.defangIPaddr("1.1.1.1") == "1[.]1[.]1[.]1"

# Provided example with multi-digit segments
assert solution.defangIPaddr("255.100.50.0") == "255[.]100[.]50[.]0"

# Minimum numeric values
assert solution.defangIPaddr("0.0.0.0") == "0[.]0[.]0[.]0"

# Maximum numeric values
assert solution.defangIPaddr("255.255.255.255") == "255[.]255[.]255[.]255"

# Mixed segment lengths
assert solution.defangIPaddr("192.168.1.1") == "192[.]168[.]1[.]1"

# Leading zeros in segments
assert solution.defangIPaddr("001.002.003.004") == "001[.]002[.]003[.]004"

# Different valid IPv4 structure
assert solution.defangIPaddr("127.0.0.1") == "127[.]0[.]0[.]1"

Test Summary

Test Why
"1.1.1.1" Verifies the basic example
"255.100.50.0" Tests multi-digit segments
"0.0.0.0" Tests smallest segment values
"255.255.255.255" Tests largest segment values
"192.168.1.1" Tests mixed-length segments
"001.002.003.004" Ensures leading zeros remain unchanged
"127.0.0.1" Tests a common localhost-style address

Edge Cases

One important edge case is an address where every segment is a single digit, such as "1.1.1.1". This tests whether the algorithm correctly replaces all periods without accidentally removing or duplicating digits. The implementation handles this naturally because it only targets the "." characters.

Another important case is an address with large numeric segments like "255.255.255.255". A buggy implementation might incorrectly parse or manipulate the numbers themselves. Since our solution performs only direct string replacement, the numeric content remains untouched.

A third edge case involves leading zeros, such as "001.002.003.004". Some implementations that attempt to parse the address numerically could accidentally strip the zeros during conversion. Our implementation avoids numeric parsing entirely, so all characters remain exactly as they appear in the original string except for the replaced periods.