1108. Defanging an IP Address
Problem Description
You are given a valid IPv4 address as a string, and your task is to "defang" it.
Defanging an IP address means replacing every period character "."
in the address with the string "[.]"
.
For example, if you have the IP address "1.1.1.1"
, after defanging it becomes "1[.]1[.]1[.]1"
.
The solution uses Python's built-in replace()
method to substitute all occurrences of '.'
with '[.]'
in a single operation. This approach directly transforms the input string by finding each period and replacing it with the bracketed version, which effectively "defangs" the IP address.
Intuition
The problem asks us to transform a string by replacing certain characters with a different sequence. When we see this type of pattern - replacing all occurrences of one substring with another - the most straightforward approach is to use string manipulation.
Since we need to replace every '.'
with '[.]'
, we're essentially performing a find-and-replace operation. This is a common string operation that most programming languages support natively. Rather than manually iterating through each character and building a new string piece by piece, we can leverage the built-in replace()
method which handles all the work internally.
The key insight is recognizing that this is a simple substitution problem where:
- The pattern to find is fixed (the period character)
- The replacement is also fixed (the bracketed period)
- We want to replace all occurrences
This leads us directly to using address.replace('.', '[.]')
, which reads naturally as "replace all dots with bracketed dots" - exactly what the problem requires.
Solution Approach
The solution uses a direct string replacement approach. The implementation consists of a single line that leverages Python's built-in replace()
method.
Here's how the solution works:
-
Method Call: We call
address.replace('.', '[.]')
on the input string- First parameter
'.'
is the substring to search for - Second parameter
'[.]'
is what to replace it with
- First parameter
-
Internal Processing: The
replace()
method:- Scans through the entire string from left to right
- Identifies every occurrence of the period character
- Substitutes each period with the bracketed version
'[.]'
- Returns a new string with all replacements made
-
Return Value: The modified string is returned directly as the result
For example, with input "192.168.0.1"
:
- The method finds periods at positions 3, 7, and 9
- Each period gets replaced with
'[.]'
- Result:
"192[.]168[.]0[.]1"
This approach has a time complexity of O(n)
where n
is the length of the input string, as the method needs to traverse the entire string once. The space complexity is also O(n)
for storing the resulting string, which will be longer than the original due to the expanded brackets.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with a simple example: "10.0.0.1"
Step 1: Initial State
- Input string:
"10.0.0.1"
- We need to replace all periods (
.
) with[.]
Step 2: Apply the replace() method
- Call
"10.0.0.1".replace('.', '[.]')
- The method scans the string from left to right
Step 3: Process each character
- Position 0-1:
"10"
- no change needed - Position 2:
.
found → replace with[.]
- Position 3:
"0"
- no change needed - Position 4:
.
found → replace with[.]
- Position 5:
"0"
- no change needed - Position 6:
.
found → replace with[.]
- Position 7:
"1"
- no change needed
Step 4: Build the result
- Original:
"1"
+"0"
+"."
+"0"
+"."
+"0"
+"."
+"1"
- Becomes:
"1"
+"0"
+"[.]"
+"0"
+"[.]"
+"0"
+"[.]"
+"1"
- Final result:
"10[.]0[.]0[.]1"
The entire transformation happens in a single operation with the replace()
method, making it both efficient and straightforward.
Solution Implementation
1class Solution:
2 def defangIPaddr(self, address: str) -> str:
3 """
4 Defangs an IP address by replacing every period '.' with '[.]'.
5
6 This prevents the IP address from being clickable/linkable in certain contexts,
7 which is useful for security purposes when sharing potentially malicious IPs.
8
9 Args:
10 address: A valid IP address string (e.g., "1.1.1.1")
11
12 Returns:
13 The defanged IP address string (e.g., "1[.]1[.]1[.]1")
14 """
15 # Replace all occurrences of '.' with '[.]' to defang the IP address
16 return address.replace('.', '[.]')
17
1class Solution {
2 /**
3 * Defangs an IP address by replacing all periods with "[.]"
4 *
5 * @param address The input IP address string to be defanged
6 * @return The defanged IP address with periods replaced by "[.]"
7 */
8 public String defangIPaddr(String address) {
9 // Replace all occurrences of "." with "[.]" to defang the IP address
10 return address.replace(".", "[.]");
11 }
12}
13
1class Solution {
2public:
3 string defangIPaddr(string address) {
4 // Iterate through the string from back to front
5 // This avoids index shifting issues when replacing characters
6 for (int i = address.size() - 1; i >= 0; --i) {
7 // Check if current character is a dot
8 if (address[i] == '.') {
9 // Replace the dot with "[.]"
10 // Parameters: starting position, length to replace, replacement string
11 address.replace(i, 1, "[.]");
12 }
13 }
14
15 // Return the modified address string
16 return address;
17 }
18};
19
1/**
2 * Defangs an IPv4 address by replacing every period "." with "[.]"
3 * This is commonly used to prevent automatic hyperlinking of IP addresses
4 *
5 * @param address - The IPv4 address string to defang (e.g., "1.1.1.1")
6 * @returns The defanged IP address string (e.g., "1[.]1[.]1[.]1")
7 */
8function defangIPaddr(address: string): string {
9 // Split the address by periods and rejoin with "[.]" as the separator
10 return address.split('.').join('[.]');
11}
12
Time and Space Complexity
The time complexity is O(n)
, where n
is the length of the input string address
. The replace()
method needs to traverse through the entire string to find all occurrences of '.'
and replace them with '[.]'
, which requires examining each character at least once.
The space complexity is O(n)
. While the replace()
operation itself may use constant auxiliary space for its internal operations, it creates and returns a new string as the result. Since each '.'
is replaced with '[.]'
(1 character becomes 3 characters), in the worst case where the input consists entirely of dots, the output string could be up to 3n
in length, which is still O(n)
in terms of complexity. If we ignore the space consumption of the answer string (as mentioned in the reference), the space complexity would be O(1)
since only a constant amount of extra space is used for the operation itself.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Assuming Input Validation is Needed
Many developers overthink this problem and try to validate if the input is a proper IPv4 address before defanging it. They might write complex regex patterns or validation logic to check if each octet is between 0-255, which adds unnecessary complexity.
Why it's a pitfall: The problem states you're given a "valid IPv4 address," so validation is not required and adds unnecessary overhead.
Solution: Trust the problem constraints and use the simple replace method directly without validation:
# Overcomplicated approach (unnecessary)
def defangIPaddr(self, address: str) -> str:
parts = address.split('.')
if len(parts) != 4:
return ""
for part in parts:
if not part.isdigit() or int(part) > 255:
return ""
return address.replace('.', '[.]')
# Simple and correct approach
def defangIPaddr(self, address: str) -> str:
return address.replace('.', '[.]')
2. Using Manual String Building Instead of Built-in Methods
Some developers might iterate through each character and manually build the result string, which is more error-prone and less efficient.
Why it's a pitfall: Manual iteration requires more code, is harder to read, and potentially less efficient than the optimized built-in replace()
method.
Solution: Leverage Python's built-in string methods:
# Manual approach (more complex)
def defangIPaddr(self, address: str) -> str:
result = []
for char in address:
if char == '.':
result.append('[.]')
else:
result.append(char)
return ''.join(result)
# Better approach using replace()
def defangIPaddr(self, address: str) -> str:
return address.replace('.', '[.]')
3. Confusing String Immutability
Some beginners might try to modify the string in-place, forgetting that strings in Python are immutable.
Why it's a pitfall: Attempting to modify a string directly will result in errors, as strings cannot be changed after creation in Python.
Solution: Always remember that string methods return new strings:
# Incorrect thinking (this doesn't work)
def defangIPaddr(self, address: str) -> str:
address.replace('.', '[.]') # This doesn't modify 'address'
return address # Returns the original unchanged string
# Correct approach
def defangIPaddr(self, address: str) -> str:
return address.replace('.', '[.]') # Return the new string
Which of the following array represent a max heap?
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!