Defanging an IP Address (LeetCode 1108): Solution and Explanation
Given a valid IPv4 address such as 1.1.1.1, return a copy where every period is written as [.], so the address cannot be clicked or resolved by accident.
Intuition
The output is the input with one local rewrite: each . turns into the three characters [.], and every digit stays as it is. Nothing depends on neighbours, so the job is a single left-to-right pass.
Because a period grows from one character to three, the output cannot be written in place inside the input. In most languages strings are immutable anyway, so the natural tool is an output buffer that you append to.
Appending to a list, StringBuilder or strings.Builder and joining once keeps the pass linear. Building the result with repeated += on an immutable string can copy the growing prefix each time, which is quadratic in the worst case, though harmless at IPv4 sizes.
Approach: Single pass with a builder
- Create an empty output buffer.
- For each character
chofaddress: if it is., append[.]; otherwise appendch. - Join the buffer into a string and return it.
Step-by-step example
address = "1.1.1.1"
- Start with an empty buffer.
1is a digit: copy it. Output so far1..is a period: append[.]. Output1[.].- The next
1,.,1,.repeat the same two moves, giving1[.]1[.]1[.]. - The last
1is copied, so the output is"1[.]1[.]1[.]1", six characters longer than the input because three periods each grew by two.
Code: Python, Java, C++
1class Solution:
2 def defangIPaddr(self, address: str) -> str:
3 out = []
4 for ch in address:
5 if ch == '.':
6 out.append('[.]')
7 else:
8 out.append(ch)
9 return ''.join(out)1class Solution {
2 public String defangIPaddr(String address) {
3 StringBuilder out = new StringBuilder();
4 for (char ch : address.toCharArray()) {
5 if (ch == '.') {
6 out.append("[.]");
7 } else {
8 out.append(ch);
9 }
10 }
11 return out.toString();
12 }
13}1class Solution {
2public:
3 string defangIPaddr(string address) {
4 string out;
5 for (char ch : address) {
6 if (ch == '.') {
7 out += "[.]";
8 } else {
9 out += ch;
10 }
11 }
12 return out;
13 }
14};Time and space complexity
O(n)
Each character of the address is visited once and appended once (three characters for a period), and the final join is linear.
O(n)
The output holds n + 2 * (number of periods) characters. For an IPv4 address that is at most 21.
Other approaches
Built-in replace (time O(n), space O(n))
Call address.replace('.', '[.]') (or replaceAll / strings.ReplaceAll). It is the one-liner most people use in practice and runs in linear time; interviewers may then ask you to write the loop yourself.
Split and join (time O(n), space O(n))
Split the address on periods into its four numbers and join them with [.]. It reads well for IP addresses specifically, but builds an intermediate list.
Common mistakes
- Using a regular-expression replace with an unescaped
., which matches every character and turns each digit into[.]too. - In Java,
String.replaceis literal butreplaceAlltakes a regex, soaddress.replaceAll(".", "[.]")gives the wrong answer. - Trying to modify the input string in place. The output is longer than the input, so a new buffer is needed.
Frequently asked questions
Why is it called defanging?
Security reports and threat feeds write addresses like 1[.]1[.]1[.]1 so that mail clients and chat tools do not turn them into live links, and nobody connects to a malicious host by accident.
Do I need to validate the IP address?
No. The constraints guarantee a valid IPv4 address, so you only need to rewrite the periods.
How long is the output?
An IPv4 address has exactly three periods, so the output is always the input length plus 6.
What is the time and space complexity?
O(n) time for one pass and O(n) space for the output string.