# Defanging an IP Address
**Difficulty:** EASY
[External](https://leetcode.com/problems/defanging-an-ip-address)
Canonical: https://scaleengineer.com/dsa/problems/defanging-an-ip-address
**Data structures:** String
**Companies:** [Robinhood](https://scaleengineer.com/companies/robinhood)
---
## Problem
Given a valid (IPv4) IP `address`, return a defanged version of that IP address.

A _defanged IP address_ replaces every period `"."` with `"[.]"`.

**Example 1:**

**Input:** address = "1.1.1.1"
**Output:** "1[.]1[.]1[.]1"

**Example 2:**

**Input:** address = "255.100.50.0"
**Output:** "255[.]100[.]50[.]0"

**Constraints:**

* The given `address` is a valid IPv4 address.

# Approaches
## Approach 1: Split and Join
This approach leverages the `split()` and `join()` methods available for strings. First, the IP address is broken down into its numerical components by splitting it at each period. Then, these components are joined back together, but this time using `"[.]"` as the separator.
**Time:** O(N), where N is the length of the input string. The `split` operation needs to scan the string, taking O(N) time. The `join` operation also takes O(N) time to construct the new string. · **Space:** O(N), where N is the length of the input string. This is because an intermediate array is created to hold the split parts of the string, and its total size is proportional to N. The final output string also requires O(N) space.
**Pros:** The code is very concise and expressive.; It clearly separates the logic of splitting by one delimiter and joining by another.
**Cons:** Involves the overhead of regular expression processing for the `split` method.; Creates an intermediate array to store the parts of the string, which consumes extra memory.
### Explanation
The algorithm proceeds as follows:
1.  Given an input string like `"255.100.50.0"`.
2.  We call `address.split("\\.")`. The `split` method treats its argument as a regular expression, so the dot `.` needs to be escaped with backslashes `\\` to be treated as a literal character. This call produces an array of strings: `["255", "100", "50", "0"]`.
3.  Next, we use `String.join("[.]", ...)` on this array. This method concatenates all elements from the array into a single string, placing the delimiter `"[.]"` between adjacent elements.
4.  The final result is the string `"255[.]100[.]50[.]0"`.

```java
class Solution {
    public String defangIPaddr(String address) {
        String[] parts = address.split("\\.");
        return String.join("[.]", parts);
    }
}
```
### Algorithm
- Split the input `address` string by the `.` delimiter. Note that the period is a special character in regular expressions, so it must be escaped as `"\\."`. This results in an array of strings.
- Join the elements of the array back together using `"[.]"` as the new delimiter.
- Return the resulting string.

## Approach 2: Iteration with StringBuilder
This approach involves manually iterating through the input string character by character and building the result using a `StringBuilder`. A `StringBuilder` is chosen for its efficiency in string manipulation, as it avoids creating a new string object for every concatenation.
**Time:** O(N), where N is the length of the input string. We perform a single pass over the string, making the time complexity linear. · **Space:** O(N), where N is the length of the input string. The `StringBuilder` will grow to the size of the output string, which is `N + 6` for a valid IPv4 address (since there are 3 periods, and each `.` of length 1 is replaced by `[.]` of length 3, a net increase of 2 characters per period).
**Pros:** Highly efficient in terms of performance, as it involves a single pass through the string.; Avoids the overhead of regular expressions and creating intermediate data structures like arrays.; Memory usage is optimized by using a mutable `StringBuilder`.
**Cons:** The code is more verbose than using a built-in `replace` method.; Requires manual implementation of the iteration and replacement logic.
### Explanation
This method provides direct control over the string construction process.
1.  We create an empty `StringBuilder` instance, let's call it `sb`.
2.  We loop through the input `address` string. For each character `c`:
3.  We check if `c` is equal to `'.'`. 
4.  If it is, we append the replacement string `"[.]"` to `sb`.
5.  If it's not a period, we simply append the character `c` to `sb`.
6.  Once the loop has processed all characters in the address, the `sb` contains the defanged version. We call `sb.toString()` to get the final string and return it.

```java
class Solution {
    public String defangIPaddr(String address) {
        StringBuilder sb = new StringBuilder();
        for (char c : address.toCharArray()) {
            if (c == '.') {
                sb.append("[.]");
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
```
### Algorithm
- Initialize a new `StringBuilder`.
- Iterate through each character of the input `address` string.
- If the current character is a `.` (period), append the string `"[.]"` to the `StringBuilder`.
- Otherwise, append the character itself.
- After the loop completes, convert the `StringBuilder` to a string and return it.

## Approach 3: Built-in `replace()` Method
This approach utilizes the built-in `String.replace()` method in Java. It is the most direct and idiomatic way to solve the problem. The method scans the string for all occurrences of a target substring and replaces them with a specified replacement substring, returning a new string.
**Time:** O(N), where N is the length of the input string. The `replace` method must traverse the string to find all occurrences of the target substring to replace. · **Space:** O(N), where N is the length of the input string. A new string object is created to store the result, so the space required is proportional to the length of the output string.
**Pros:** Extremely simple and concise, resulting in highly readable code.; It's the most idiomatic way to perform simple string replacements in Java.; The implementation of `String.replace()` is highly optimized within the JVM, often making it the most performant option for this kind of task.
**Cons:** While highly optimized, it might abstract away the underlying process, which could be a slight disadvantage in a learning context.
### Explanation
This is the simplest solution. The `String` class in Java is immutable, meaning its instances cannot be changed. Methods like `replace()` don't alter the original string; instead, they create and return a new string with the modifications.

The entire logic can be implemented in a single line of code:

```java
class Solution {
    public String defangIPaddr(String address) {
        return address.replace(".", "[.]");
    }
}
```

When `address.replace(".", "[.]")` is called, the Java runtime efficiently finds every `.` character and substitutes it with `"[.]"`, producing the desired defanged IP address in a new string.
### Algorithm
- Call the `replace()` method on the input `address` string.
- Pass `"."` as the first argument (the target sequence to be replaced).
- Pass `"[.]"` as the second argument (the replacement sequence).
- Return the new string returned by the `replace()` method.

# Solutions
### Java

```java
class Solution {
public
  String defangIPaddr(String address) { return address.replace(".", "[.]"); }
}

```

### CPP

```cpp
class Solution {
public:
  string defangIPaddr(string address) {
    for (int i = address.size(); i >= 0; --i) {
      if (address[i] == '.') {
        address.replace(i, 1, "[.]");
      }
    }
    return address;
  }
};

```

### Python

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

```
