Defanging an IP Address — Solution in Python, Java & C++
Defanging an IP Address solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on strings.
Defanging an IP Address is an easy coding problem on strings, asked in Amazon, Wipro and Capgemini interviews.
- Difficulty: Easy
- Topics: Strings
- Asked at: Amazon, Wipro, Capgemini
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
A defanged IP address replaces every period "." with "[.]" so the address cannot be clicked by accident.
Given a valid IPv4 address, return its defanged form.
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
Example 3
Input: address = "8.8.8.8"
Output: 8[.]8[.]8[.]8
Constraints
The input is a valid IPv4 address.
Hints for Defanging an IP Address
Hint 1
Split on the period and join the pieces with
"[.]".Hint 2
Or build the output character by character, appending three characters instead of one for a period.
How to solve Defanging an IP Address
Replace every . with [.].
Approach
- Return
address.replace(".", "[.]"), or rebuild character by character appending three characters for each period.
Why it works
The transformation is a literal substitution with no other rules.
Complexity
- Time —
O(n) - Space —
O(n)
Pitfalls
- In languages where the replace API takes a regex, escape the period.
Reference solution
Python
def defangIPaddr(address: str) -> str:
return address.replace(".", "[.]")Java
public static String defangIPaddr(String address) {
StringBuilder out = new StringBuilder();
for (int i = 0; i < address.length(); i++) {
char c = address.charAt(i);
if (c == '.') out.append("[.]");
else out.append(c);
}
return out.toString();
}C++
string defangIPaddr(string address) {
string out = "";
for (char c : address) {
if (c == '.') out += "[.]";
else out += c;
}
return out;
}JavaScript
var defangIPaddr = function(address) {
return address.split(".").join("[.]");
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings