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.
Solutions
Solution
class Solution {public String defangIPaddr(String address) { 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.