1108. Defanging an IP Address
Model: qwen2.5-coder:14b
Topics: String
FAANG asked: 0
Acceptance rate: 88.4%
Problem Breakdown
The problem requires transforming a valid IPv4 address by replacing every period "." with "[.]". The input is a string representing a valid IPv4 address, and the output should be the defanged version of that IP address. There are no implicit constraints or tricky edge cases mentioned other than ensuring the input is a valid IPv4 address.
Intuition
A brute-force approach would involve iterating through each character in the string, checking if it’s a period, and replacing it with "[.]". This approach works but has a time complexity of O(n) where n is the length of the string, as we need to examine each character. The key insight is that strings are immutable in Python, so repeatedly concatenating strings can be inefficient due to creating multiple intermediate strings. A more efficient approach would be to use a list to collect characters and then join them at the end.
Approach
- Initialize an empty list to store the characters of the defanged IP address.
- Iterate through each character in the input string:
- If the character is a period
".", append"[.]"to the list. - Otherwise, append the character itself to the list.
- If the character is a period
- After processing all characters, join the list into a single string using the
join()method. - Return the resulting defanged IP address.
Complexity Analysis
- Time Complexity: O(n), where n is the length of the input string. We iterate through each character once.
- Space Complexity: O(n), as we store all characters in a list before joining them into a final string.
Solution
def defangIPaddr(address: str) -> str:
# Initialize an empty list to collect characters
result = []
# Iterate through each character in the input string
for char in address:
if char == '.':
# Replace period with "[.]"
result.append("[.]")
else:
# Append the character itself
result.append(char)
# Join the list into a single string and return it
return ''.join(result)
Edge Cases Handled
- The code handles typical valid IPv4 addresses like
"1.1.1.1"and"255.100.50.0". - The code assumes the input is always a valid IPv4 address, so no additional checks for invalid inputs are necessary.
The solution provided is correct, efficient, and clear. It adheres to the problem constraints and handles the task as described.