Defanging an IP Address solution and explanation
9 more videos on this problem
LeetCode 1108: Defanging an IP Address - Interview Prep Ep 16Fisher Coder · 5:10 · 3K views
Leetcode | 1108. Defanging an IP Address | Easy | Java SolutionDeveloper Docs · 4:19 · 828 views
Defanging an IP Address | LeetCode 1108 | EnglishCodeClips with Abhishek Ranjan · 3:08 · 639 views
1108. Defanging an IP Address | LEETCODE EASYcode Explainer · 3:20 · 461 views
Leetcode Solution - 1108 Defanging an IP AddressJohn Leonardo · 3:11 · 296 views
Leetcode Easy: 1108 Defanging an IP Addressleetcode · 2:24 · 278 views
#day7 1108. Defanging an IP Address Leetcode question optimized solutionRCTECHLIFE · 4:06 · 149 views
LEETCODE SOLUTION 1108 | Defanging an IP Address | Leetcode for BEGINNERS | EASY | JavascriptCodingForBeginners · 8:28 · 146 views
LeetCode 1108. Defanging an IP AddressYusuke · 2:10 · 102 views
LeetCode 1108 defanging an IP address LeetCode Live CodingLeetCode Solutions · 12:16 · 84 views
The problem
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.
Approach overview
Problem Overview: You receive a valid IPv4 address as a string such as "1.1.1.1". The task is to "defang" it by replacing every period . with [.]. The result prevents the address from being interpreted as a clickable or executable IP. The challenge is purely string manipulation and focuses on safe and efficient character replacement.
Approach 1: String Replace Function (Time: O(n), Space: O(n))
The simplest solution uses the built‑in string replacement utility available in most languages. Call a method such as replace() to substitute every . with [.]. Internally, the runtime scans the string once and builds a new string with the replacements applied. Since each character is processed at most once, the time complexity is O(n) where n is the length of the address, and the new output string requires O(n) extra space.
This approach is concise and readable. It relies on standard library implementations that are already optimized. For problems centered on string manipulation, built‑in operations are often preferred because they reduce code complexity and avoid manual edge case handling.
Approach 2: Manual Character Replacement (Time: O(n), Space: O(n))
Instead of using a built‑in function, iterate through the string character by character. Maintain a result buffer (string builder, vector, or list depending on language). When the current character is ., append the sequence [.] to the result. Otherwise append the character itself. After processing all characters, convert the buffer into the final string.
This approach gives full control over how characters are appended and is useful when library replacements are unavailable or restricted. It demonstrates understanding of string processing and sequential traversal techniques. The loop processes each character once, so the runtime remains O(n). The result buffer stores the modified string, resulting in O(n) auxiliary space.
Recommended for interviews: The built‑in replace solution is usually the expected answer because the problem focuses on recognizing simple string transformation. Interviewers primarily want to see that you map the requirement directly to a clean operation. Implementing the manual iteration version still shows solid understanding of string traversal and how to construct output efficiently when library helpers are unavailable.
Approach 1: String Replace Function
One straightforward approach to defang an IP address is to use a string replace function available in most programming languages. This involves replacing every period '.' with '[.]'. This method is efficient as most languages provide optimized functions for this purpose.
def defangIPaddr(address: str) -> str:
return address.replace('.', '[.]')
address = "1.1.1.1"
print(f"Defanged IP: {defangIPaddr(address)}")public class Main {
public static String defangIPaddr(String address) {
return address.replace(".", "[.]");
}
public static void main(String[] args) {
String address = "1.1.1.1";
System.out.println("Defanged IP: " + defangIPaddr(address));
}
}#include <iostream>
#include <string>
using namespace std;
string defangIPaddr(string address) {
string result;
for (char c : address) {
if (c == '.') {
result += "[.]";
} else {
result += c;
}
}
return result;
}
int main() {
string address = "1.1.1.1";
cout << "Defanged IP: " << defangIPaddr(address) << endl;
return 0;
}function defangIPaddr(address) {
return address.split('.').join('[.]');
}
let address = "1.1.1.1";
console.log("Defanged IP: " + defangIPaddr(address));#include <stdio.h>
#include <string.h>
void defangIP(char *address, char *result) {
int i, j = 0;
for (i = 0; address[i] != '\0'; i++) {
if (address[i] == '.') {
strcat(result, "[.]");
j += 3;
} else {
result[j++] = address[i];
}
}
result[j] = '\0';
}
int main() {
char address[] = "1.1.1.1";
char result[22]; // Enough to hold the defanged IP address
defangIP(address, result);
printf("Defanged IP: %s\n", result);
return 0;
}using System;
class Program {
public static string DefangIPAddr(string address) {
return address.Replace(".", "[.]");
}
static void Main() {
string address = "1.1.1.1";
Console.WriteLine("Defanged IP: " + DefangIPAddr(address));
}
}In Python, we use the str.replace() method which is a straightforward way to replace '.' with '[.]'. This function is highly optimized for such operations.
Time Complexity: O(n), where n is the length of the input string.
Space Complexity: O(n), due to the creation of a new string.
Approach 2: Manual Character Replacement
Another approach is to manually append each character to a new string or string builder, checking for periods and appending '[.]' instead of '.'. This provides more control over the process and can be more educational for understanding string processing.
def defangIPaddr(address: str) -> str:
result = []
for char in address:
if char == '.':
result.append('[.]')
else:
result.append(char)
return ''.join(result)
address = "255.100.50.0"
print(f"Defanged IP: {defangIPaddr(address)}")public class Main {
public static String defangIPaddr(String address) {
StringBuilder result = new StringBuilder();
for (char c : address.toCharArray()) {
if (c == '.') {
result.append("[.]");
} else {
result.append(c);
}
}
return result.toString();
}
public static void main(String[] args) {
String address = "255.100.50.0";
System.out.println("Defanged IP: " + defangIPaddr(address));
}
}#include <iostream>
using namespace std;
string defangIPaddr(string address) {
string result;
for (char c : address) {
if (c == '.') {
result += "[.]";
} else {
result += c;
}
}
return result;
}
int main() {
string address = "255.100.50.0";
cout << "Defanged IP: " << defangIPaddr(address) << endl;
return 0;
}function defangIPaddr(address) {
let result = '';
for (let char of address) {
if (char === '.') {
result += '[.]';
} else {
result += char;
}
}
return result;
}
let address = "255.100.50.0";
console.log("Defanged IP: " + defangIPaddr(address));#include <stdio.h>
#include <string.h>
void defangIP(char *address, char *result) {
int i, j = 0;
for (i = 0; address[i] != '\0'; i++) {
if (address[i] == '.') {
result[j++] = '[';
result[j++] = '.';
result[j++] = ']';
} else {
result[j++] = address[i];
}
}
result[j] = '\0';
}
int main() {
char address[] = "255.100.50.0";
char result[30]; // Buffer to hold the defanged IP address
defangIP(address, result);
printf("Defanged IP: %s\n", result);
return 0;
}using System;
using System.Text;
class Program {
public static string DefangIPAddr(string address) {
StringBuilder result = new StringBuilder();
foreach (char c in address) {
if (c == '.') {
result.Append("[.]");
} else {
result.Append(c);
}
}
return result.ToString();
}
static void Main() {
string address = "255.100.50.0";
Console.WriteLine("Defanged IP: " + DefangIPAddr(address));
}
}This Python solution uses manual construction of the result string using a list to store parts of the new string. For each character in the original address, '[.]' or the character is added to this list, which is then joined to form the final defanged IP address.
Time Complexity: O(n), as each character is processed once.
Space Complexity: O(n), for storing intermediate results in a list.
Approach 3: Direct Replacement
We can directly replace the '.' in the string with '[.]'.
The time complexity is O(n), where n is the length of the string. Ignoring the space consumption of the answer, the space complexity is O(1).
function defangIPaddr(address: string): string {
return address.split('.').join('[.]');
}func defangIPaddr(address string) string {
return strings.Replace(address, ".", "[.]", -1)
}Complexity comparison
| Approach | Complexity |
|---|---|
| String Replace Function | Time Complexity: O(n), where n is the length of the input string. |
| Manual Character Replacement | Time Complexity: O(n), as each character is processed once. |
| Direct Replacement | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| String Replace Function | O(n) | O(n) | Best choice in most languages when a built-in replace API is available. |
| Manual Character Replacement | O(n) | O(n) | Useful when library helpers are restricted or when demonstrating string traversal logic. |
Frequently asked questions
Is Defanging an IP Address easy or hard?
Defanging an IP Address is categorized as an Easy problem. It focuses on basic string manipulation and recognizing when a built-in replace function solves the task in a single pass.
Defanging an IP Address Python/Java solution
In Python, use address.replace('.', '[.]'). In Java, use address.replace('.', '[.]') or replace(".", "[.]"). Both implementations scan the string once and return a new string with the defanged format.
How to solve Defanging an IP Address in O(n)?
Traverse the string once and replace every '.' with '[.]'. This can be done using a built-in replace method or by building a result string while iterating through characters. Since each character is processed once, the runtime remains O(n).
What is the best approach for Defanging an IP Address?
The most efficient and clean approach uses a built-in string replace function to substitute '.' with '[.]'. It processes the string once, giving O(n) time complexity and O(n) space for the new output string. This approach keeps the code short and leverages optimized standard library functions.
Is Defanging an IP Address asked at Google/Amazon/Meta?
Problems like Defanging an IP Address appear in interview preparation sets and practice platforms because they test basic string manipulation skills. While the exact question is more common in screening rounds or coding practice, similar string transformation tasks frequently appear in big tech interviews.
What data structure is used in Defanging an IP Address?
The primary data structure is a string. Some implementations also use a mutable buffer such as a StringBuilder, list, or character array to construct the result efficiently while iterating through the input.
What is the time complexity of Defanging an IP Address?
The time complexity is O(n), where n is the length of the IP address string. Each character is inspected once either by the replace function or by manual iteration. The algorithm performs a single pass through the string.
