Defanging IP Address
This question is asked by Amazon. Given a valid IP address, defang it.
Note: To defang an IP address, replace every "." with "[.]".
Example(s)
Example 1:
Input: address = "127.0.0.1"
Output: "127[.]0[.]0[.]1"
Explanation:
Replace each "." with "[.]"
127.0.0.1 → 127[.]0[.]0[.]1
Example 2:
Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"
Explanation:
Replace each "." with "[.]"
1.1.1.1 → 1[.]1[.]1[.]1
Example 3:
Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"
Explanation:
Replace each "." with "[.]"
255.100.50.0 → 255[.]100[.]50[.]0
Solution
The solution uses string replacement:
- Replace dots: Replace every "." with "[.]"
- Return result: Return the defanged IP address
- JavaScript Solution
- Python Solution
JavaScript Solution - Replace
/**
* Defang IP address by replacing "." with "[.]"
* @param {string} address - Valid IP address
* @return {string} - Defanged IP address
*/
function defangIPaddr(address) {
// Replace all occurrences of "." with "[.]"
return address.replace(/./g, '[.]');
}
// Test cases
console.log('Example 1:', defangIPaddr("127.0.0.1"));
// "127[.]0[.]0[.]1"
console.log('Example 2:', defangIPaddr("1.1.1.1"));
// "1[.]1[.]1[.]1"
console.log('Example 3:', defangIPaddr("255.100.50.0"));
// "255[.]100[.]50[.]0"
console.log('Test 4:', defangIPaddr("192.168.1.1"));
// "192[.]168[.]1[.]1"Output:
Click "Run Code" to execute the code and see the results.
Python Solution - Replace
def defang_i_paddr(address: str) -> str:
"""
Defang IP address by replacing "." with "[.]"
Args:
address: Valid IP address
Returns:
str: Defanged IP address
"""
# Replace all occurrences of "." with "[.]"
return address.replace('.', '[.]')
# Test cases
print('Example 1:', defang_i_paddr("127.0.0.1"))
# "127[.]0[.]0[.]1"
print('Example 2:', defang_i_paddr("1.1.1.1"))
# "1[.]1[.]1[.]1"
print('Example 3:', defang_i_paddr("255.100.50.0"))
# "255[.]100[.]50[.]50[.]0"
print('Test 4:', defang_i_paddr("192.168.1.1"))
# "192[.]168[.]1[.]1"Loading Python runtime...
Output:
Click "Run Code" to execute the code and see the results.
Alternative Solution (String Builder)
Here's a version using string building:
- JavaScript Builder
- Python Builder
/**
* Using string builder
*/
function defangIPaddrBuilder(address) {
let result = '';
for (const char of address) {
if (char === '.') {
result += '[.]';
} else {
result += char;
}
}
return result;
}
def defang_i_paddr_builder(address: str) -> str:
"""
Using string builder
"""
result = []
for char in address:
if char == '.':
result.append('[.]')
else:
result.append(char)
return ''.join(result)
Alternative Solution (Split and Join)
Here's a version using split and join:
- JavaScript Split
- Python Split
/**
* Using split and join
*/
function defangIPaddrSplit(address) {
return address.split('.').join('[.]');
}
def defang_i_paddr_split(address: str) -> str:
"""
Using split and join
"""
return '[.]'.join(address.split('.'))
Complexity
- Time Complexity: O(n) - Where n is the length of the string. We process each character once.
- Space Complexity: O(n) - For the result string.
Approach
The solution uses string replacement:
-
Replace dots:
- Replace every "." with "[.]"
- Use string replace method with global flag
-
Return result:
- Return the defanged IP address
Key Insights
- Simple replacement: Just replace "." with "[.]"
- Global replacement: Replace all occurrences, not just the first
- String methods: Built-in replace method is simplest
- O(n) time: Must process each character
- O(n) space: For the result string
Step-by-Step Example
Let's trace through Example 1: address = "127.0.0.1"
address = "127.0.0.1"
Replace operation:
"127.0.0.1".replace(/\./g, '[.]')
Find all "." characters:
Position 3: "."
Position 5: "."
Position 7: "."
Replace each with "[.]":
"127" + "[.]" + "0" + "[.]" + "0" + "[.]" + "1"
Result: "127[.]0[.]0[.]1"
Visual Representation
Example 1: address = "127.0.0.1"
Original: 1 2 7 . 0 . 0 . 1
↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑
Keep all, replace dots
Defanged: 1 2 7 [ . ] 0 [ . ] 0 [ . ] 1
↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑
All characters kept, dots replaced with [.]
Result: "127[.]0[.]0[.]1"
Edge Cases
- Standard IP: Works correctly (e.g., "192.168.1.1")
- Localhost: Works correctly (e.g., "127.0.0.1")
- All zeros: Works correctly (e.g., "0.0.0.0")
- All ones: Works correctly (e.g., "1.1.1.1")
- Large numbers: Works correctly (e.g., "255.255.255.255")
Important Notes
- Valid IP address: Problem states input is valid
- Replace all dots: Every "." must be replaced with "[.]"
- Global replacement: Use global flag in regex or replace all
- O(n) time: Must process each character
- O(n) space: For the result string
Why Defanging?
Purpose of defanging:
- Prevents IP addresses from being automatically converted to clickable links
- Makes IP addresses safe to display in text/HTML
- Common security practice when displaying IP addresses
Comparison of Approaches
| Approach | Time | Space | Readability | Notes |
|---|---|---|---|---|
| Replace | O(n) | O(n) | Excellent | Simplest |
| Split/Join | O(n) | O(n) | Good | Alternative |
| Builder | O(n) | O(n) | Good | More control |
Related Problems
- Validate IP Address: Different problem
- Restore IP Addresses: Different problem
- String Replace: Similar concept
- Reverse Words: Different string problem
Takeaways
- String replace is the simplest solution
- Global replacement replaces all occurrences
- O(n) time is optimal (must process each character)
- O(n) space for the result string
- Simple problem with straightforward solution