Given a valid (IPv4) IP address
, return a defanged version of that IP address.
A defanged IP address replaces every period "."
with "[.]"
.
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:
address
is a valid IPv4 address.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The goal is to replace periods in an IP address with '[.]'. The brute force method essentially looks at each character in the IP address one by one. If it finds a period, it substitutes it.
Here's how the algorithm would work step-by-step:
def defang_ip_address(ip_address):
defanged_ip = ''
for char in ip_address:
# Need to check each character to see if it's a period
if char == '.':
defanged_ip += '[.]'
# Otherwise, we add the character to the result as is
else:
defanged_ip += char
return defanged_ip
The task is to replace each period in an IP address with '[.]'. Instead of trying to manipulate the string character by character, the best way is to think of it as replacing one chunk of text with another. We can achieve this with a simple and efficient technique.
Here's how the algorithm would work step-by-step:
def defang_ip_address(ip_address):
# Replace all occurrences of '.' with '[.]'
defanged_ip = ip_address.replace('.', '[.]')
# Replacing allows creating the defanged IP easily
return defanged_ip
Case | How to Handle |
---|---|
Null or empty input string | Return an empty string or null, or throw an IllegalArgumentException as appropriate for the language and API contract. |
Input string contains no periods | Return the original string since no defanging is needed. |
Input string contains only periods | Replace each period with '[.]' to produce '[.][.][.]...'. |
Input string has leading or trailing periods | These periods should also be replaced with '[.]'. |
Extremely long input string (performance) | Use a StringBuilder or similar mechanism to avoid string concatenation performance issues. |
Invalid IPv4 address format (e.g., missing numbers, extra periods) | The problem statement specifies a 'valid IPv4 address', so this input could be considered out of scope, or an exception could be thrown. |
Input string contains characters other than numbers and periods | If the problem statement limits the input to numbers and periods, other characters might be out of scope, or could throw an exception. |
Very short IP address (e.g., '.'), | This still needs to be handled, which would result in '[.]' being returned. |