Defang an IP Address
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.
Function Signature (Python):
class Solution:
def defangIPaddr(self, address: str) -> str:
# Your code here
pass
Related Python Concepts
Hint
How can you systematically go through the input string and replace each occurrence of a specific character?
- Built-in Power: Does Python's string type have a built-in method that can directly replace all occurrences of one substring with another? This is often the simplest solution.
- Manual Iteration: If you couldn't use a direct replacement method, how would you build the new string character by character?
- You could iterate through the input string. When you encounter a period, append
"[.]"to your result. Otherwise, append the character itself.
- You could iterate through the input string. When you encounter a period, append
- Split and Join: Can you break the string apart at the periods and then put it back together with
"[.]"in between?
Solution Explanation & Interview Strategy
The Goal: We're given an IP address like "1.1.1.1". We need to change every dot . into [.]. So, "1.1.1.1" becomes "1[.]1[.]1[.]1".
This is a basic string manipulation task, often used to see if you know common string operations or can think through building a new string.
Approach 1: Using the `replace()` String Method (Most Pythonic)
Python strings have a built-in replace() method that is perfect for this task. It takes two arguments: the substring to be replaced, and the substring to replace it with.
class Solution:
def defangIPaddr_replace(self, address: str) -> str:
return address.replace(".", "[.]")
# Example Usage:
# sol = Solution()
# print(sol.defangIPaddr_replace("1.1.1.1")) # Output: "1[.]1[.]1[.]1"
Complexity Analysis:
Time Complexity: O(N), where N is the length of the address string. The replace() method needs to scan the string. In Python, string operations that create new strings (like replace) typically take time proportional to the length of the strings involved.
Space Complexity: O(N), because a new string is created to store the result. The original string is immutable.
Interview Note: This is usually the expected and most efficient solution for this specific problem in Python. It demonstrates knowledge of standard library functions.
Approach 2: Manual Iteration and String Building
If an interviewer wants to see you implement the logic without relying heavily on built-ins (or if the language didn't have a convenient replace), you could iterate through the input string and build the new string character by character.
class Solution:
def defangIPaddr_manual_iteration(self, address: str) -> str:
defanged_parts = []
for char in address:
if char == '.':
defanged_parts.append('[.]')
else:
defanged_parts.append(char)
return "".join(defanged_parts)
# Example Usage:
# sol = Solution()
# print(sol.defangIPaddr_manual_iteration("255.100.50.0")) # "255[.]100[.]50[.]0"
- Initialize
defanged_parts = []. char = '1'. Append '1'.defanged_parts = ['1'].char = '.'. Append '[.]'.defanged_parts = ['1', '[.]'].char = '1'. Append '1'.defanged_parts = ['1', '[.]', '1'].- Loop ends.
"".join(['1', '[.]', '1'])returns "1[.]1".
Note: Using a list to append parts and then joining is generally more efficient in Python than repeated string concatenation (e.g., result_str += char) which can be O(N2).
Complexity Analysis:
Time Complexity: O(N). We iterate through the string once (O(N)). Appending to the list is O(1) on average. The final join() operation also takes O(N) time as it constructs the new string.
Space Complexity: O(N) for storing defanged_parts and for the final joined string.
Approach 3: Using `split()` and `join()`
Another way is to split the string by the period . and then join the resulting parts with "[.]".
class Solution:
def defangIPaddr_split_join(self, address: str) -> str:
parts = address.split('.') # Example: "1.1.1.1" -> ['1', '1', '1', '1']
return "[.]".join(parts) # Example: "[.]".join(['1','1','1','1']) -> "1[.]1[.]1[.]1"
# Example Usage:
# sol = Solution()
# print(sol.defangIPaddr_split_join("1.1.1.1")) # "1[.]1[.]1[.]1"
Complexity Analysis:
Time Complexity: O(N). Both split() and join() operations are typically O(N) where N is the length of the string.
Space Complexity: O(N). The split() method creates a list of substrings, and join() creates the new final string. Both can take space proportional to N.
Key Takeaways for Interviews:
- Start with the Most Direct: For this problem, the
str.replace()method is the most idiomatic and efficient Python solution. It's perfectly acceptable to offer this first. - Be Prepared for Alternatives: If the interviewer probes for other methods or implies a restriction on built-ins, be ready to discuss manual iteration (Approach 2) or the split-and-join technique (Approach 3).
- Discuss Efficiency (Briefly): While all common approaches are O(N) time and space for this problem, it's good to be aware of why manual string concatenation with
+=in a loop is less efficient than building a list of parts and then joining. - Clarity and Simplicity: Since it's an "easy" problem, the clarity of your code is important. The
replace()method excels here.