Defanging an IP Address
EasyPrompt
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:
- The given
addressis a valid IPv4 address.
Approaches
3 approaches with complexity analysis and trade-offs.
This approach involves manually iterating through the input string character by character and building the result using a StringBuilder. A StringBuilder is chosen for its efficiency in string manipulation, as it avoids creating a new string object for every concatenation.
Algorithm
- Initialize a new
StringBuilder. - Iterate through each character of the input
addressstring. - If the current character is a
.(period), append the string"[.]"to theStringBuilder. - Otherwise, append the character itself.
- After the loop completes, convert the
StringBuilderto a string and return it.
Walkthrough
This method provides direct control over the string construction process.
- We create an empty
StringBuilderinstance, let's call itsb. - We loop through the input
addressstring. For each characterc: - We check if
cis equal to'.'. - If it is, we append the replacement string
"[.]"tosb. - If it's not a period, we simply append the character
ctosb. - Once the loop has processed all characters in the address, the
sbcontains the defanged version. We callsb.toString()to get the final string and return it.
class Solution { public String defangIPaddr(String address) { StringBuilder sb = new StringBuilder(); for (char c : address.toCharArray()) { if (c == '.') { sb.append("[.]"); } else { sb.append(c); } } return sb.toString(); }}Complexity
Time
O(N), where N is the length of the input string. We perform a single pass over the string, making the time complexity linear.
Space
O(N), where N is the length of the input string. The `StringBuilder` will grow to the size of the output string, which is `N + 6` for a valid IPv4 address (since there are 3 periods, and each `.` of length 1 is replaced by `[.]` of length 3, a net increase of 2 characters per period).
Trade-offs
Pros
Highly efficient in terms of performance, as it involves a single pass through the string.
Avoids the overhead of regular expressions and creating intermediate data structures like arrays.
Memory usage is optimized by using a mutable
StringBuilder.
Cons
The code is more verbose than using a built-in
replacemethod.Requires manual implementation of the iteration and replacement logic.
This approach leverages the split() and join() methods available for strings. First, the IP address is broken down into its numerical components by splitting it at each period. Then, these components are joined back together, but this time using "[.]" as the separator.
Algorithm
- Split the input
addressstring by the.delimiter. Note that the period is a special character in regular expressions, so it must be escaped as"\\.". This results in an array of strings. - Join the elements of the array back together using
"[.]"as the new delimiter. - Return the resulting string.
Walkthrough
The algorithm proceeds as follows:
- Given an input string like
"255.100.50.0". - We call
address.split("\\."). Thesplitmethod treats its argument as a regular expression, so the dot.needs to be escaped with backslashes\\to be treated as a literal character. This call produces an array of strings:["255", "100", "50", "0"]. - Next, we use
String.join("[.]", ...)on this array. This method concatenates all elements from the array into a single string, placing the delimiter"[.]"between adjacent elements. - The final result is the string
"255[.]100[.]50[.]0".
class Solution { public String defangIPaddr(String address) { String[] parts = address.split("\\."); return String.join("[.]", parts); }}Complexity
Time
O(N), where N is the length of the input string. The `split` operation needs to scan the string, taking O(N) time. The `join` operation also takes O(N) time to construct the new string.
Space
O(N), where N is the length of the input string. This is because an intermediate array is created to hold the split parts of the string, and its total size is proportional to N. The final output string also requires O(N) space.
Trade-offs
Pros
The code is very concise and expressive.
It clearly separates the logic of splitting by one delimiter and joining by another.
Cons
Involves the overhead of regular expression processing for the
splitmethod.Creates an intermediate array to store the parts of the string, which consumes extra memory.
This approach utilizes the built-in String.replace() method in Java. It is the most direct and idiomatic way to solve the problem. The method scans the string for all occurrences of a target substring and replaces them with a specified replacement substring, returning a new string.
Algorithm
- Call the
replace()method on the inputaddressstring. - Pass
"."as the first argument (the target sequence to be replaced). - Pass
"[.]"as the second argument (the replacement sequence). - Return the new string returned by the
replace()method.
Walkthrough
This is the simplest solution. The String class in Java is immutable, meaning its instances cannot be changed. Methods like replace() don't alter the original string; instead, they create and return a new string with the modifications.
The entire logic can be implemented in a single line of code:
class Solution { public String defangIPaddr(String address) { return address.replace(".", "[.]"); }}When address.replace(".", "[.]") is called, the Java runtime efficiently finds every . character and substitutes it with "[.]", producing the desired defanged IP address in a new string.
Complexity
Time
O(N), where N is the length of the input string. The `replace` method must traverse the string to find all occurrences of the target substring to replace.
Space
O(N), where N is the length of the input string. A new string object is created to store the result, so the space required is proportional to the length of the output string.
Trade-offs
Pros
Extremely simple and concise, resulting in highly readable code.
It's the most idiomatic way to perform simple string replacements in Java.
The implementation of
String.replace()is highly optimized within the JVM, often making it the most performant option for this kind of task.
Cons
While highly optimized, it might abstract away the underlying process, which could be a slight disadvantage in a learning context.
Solutions
Solution
class Solution {public String defangIPaddr(String address) { return address.replace(".", "[.]"); }}class Solution {public: string defangIPaddr(string address) { for (int i = address.size(); i >= 0; --i) { if (address[i] == '.') { address.replace(i, 1, "[.]"); } } return address; }};class Solution: def defangIPaddr( self, address: str) -> str: return address . replace('.', '[.]')Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.