Defanging an IP Address
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given a valid (IPv4) IP address, return a defanged version of that IP address.
A defanged IP address replaces every period "." with "[.]".
Examples
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
addressis a valid IPv4 address.
Solution
Method 1 – String Replacement
Intuition
The problem is a simple string manipulation: replace every period . in the IP address with [.]. This can be done efficiently using built-in string replacement functions in most languages.
Approach
- Iterate through the string and replace every
.with[.]. - Return the modified string.
Code
C++
class Solution {
public:
string defangIPaddr(string address) {
string ans;
for (char c : address) {
if (c == '.') ans += "[.]";
else ans += c;
}
return ans;
}
};
Go
func defangIPaddr(address string) string {
ans := ""
for _, c := range address {
if c == '.' {
ans += "[.]"
} else {
ans += string(c)
}
}
return ans
}
Java
class Solution {
public String defangIPaddr(String address) {
return address.replace(".", "[.]");
}
}
Kotlin
class Solution {
fun defangIPaddr(address: String): String {
return address.replace(".", "[.]")
}
}
Python
class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace('.', '[.]')
Rust
impl Solution {
pub fn defang_i_paddr(address: String) -> String {
address.replace(".", "[.]")
}
}
TypeScript
class Solution {
defangIPaddr(address: string): string {
return address.replace(/\./g, '[.]');
}
}
Complexity
- ⏰ Time complexity:
O(n), wherenis the length of the address, since we scan each character once. - 🧺 Space complexity:
O(n), for the output string.