Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1108. Defanging an IP Address - Leetcode Solution

Problem Description

The Leetcode problem "Defanging an IP Address" asks you to transform a given valid IPv4 address into a "defanged" version. An IPv4 address is a string in the format "X.X.X.X" where X is a number between 0 and 255, and periods '.' separate the numbers.

To defang an IP address, you must replace every period '.' with "[.]". The rest of the characters remain unchanged.

Constraints:

  • The input string address is a valid IPv4 address.
  • There is only one valid solution for each input.
Example:
Input: "1.1.1.1"
Output: "1[.]1[.]1[.]1"

Thought Process

When approaching this problem, the first idea that comes to mind is to look for every period '.' in the string and replace it with "[.]". Since the input is guaranteed to be a valid IPv4 address, we do not need to validate the format or handle edge cases with invalid input.

A brute-force approach would be to iterate through each character in the string, check if it is a period, and build a new string accordingly. Alternatively, many programming languages provide string replacement functions that can directly substitute all occurrences of a character with a new substring, making the solution concise and efficient.

The main focus is to ensure that every period is replaced, and no other characters are altered. Optimization is straightforward here, as the problem is simple and the input size is small (IPv4 addresses are short strings).

Solution Approach

To solve the problem, we can use either a manual traversal or a built-in string replacement function. Here’s how both can be approached:

  • Using String Replacement:
    • Most languages have a built-in function (like replace in Python, Java, and JavaScript, or std::replace in C++) that can replace all instances of a character or substring with another.
    • We call this function on the input string, replacing '.' with "[.]".
    • This approach is concise, readable, and efficient.
  • Manual Traversal:
    • Iterate through each character in the input string.
    • If the character is a period, append "[.]" to the result string.
    • Otherwise, append the character itself.
    • This approach is language-agnostic and helps understand string manipulation fundamentals.

In practice, the string replacement method is preferred due to its simplicity and directness.

Example Walkthrough

Let’s walk through an example with the input "192.168.0.1":

  • Start with an empty result string.
  • Iterate character by character:
    • '1' → append '1'
    • '9' → append '9'
    • '2' → append '2'
    • '.' → append '[.]'
    • '1' → append '1'
    • '6' → append '6'
    • '8' → append '8'
    • '.' → append '[.]'
    • '0' → append '0'
    • '.' → append '[.]'
    • '1' → append '1'
  • The final result is "192[.]168[.]0[.]1".

If using a built-in replace function, the entire process is reduced to a single operation: address.replace('.', '[.]').

Code Implementation

class Solution:
    def defangIPaddr(self, address: str) -> str:
        return address.replace('.', '[.]')
      
class Solution {
public:
    string defangIPaddr(string address) {
        string result;
        for (char c : address) {
            if (c == '.') {
                result += "[.]";
            } else {
                result += c;
            }
        }
        return result;
    }
};
      
class Solution {
    public String defangIPaddr(String address) {
        return address.replace(".", "[.]");
    }
}
      
/**
 * @param {string} address
 * @return {string}
 */
var defangIPaddr = function(address) {
    return address.replace(/\./g, '[.]');
};
      

Time and Space Complexity

Brute-force approach (manual traversal):

  • Time Complexity: O(N), where N is the length of the input string. Each character is checked and appended to the result string.
  • Space Complexity: O(N), since a new string is constructed with potentially more characters (each '.' replaced by 3 characters).
Optimized approach (using built-in replacement):
  • Time Complexity: O(N), as the replace operation still processes each character once.
  • Space Complexity: O(N), for the new string with replacements.

In both approaches, the complexity is linear in the size of the input string, which is very efficient given the typically short length of IPv4 addresses.

Summary

The "Defanging an IP Address" problem is a straightforward string manipulation exercise. The key is to replace every period '.' with "[.]" in the given IPv4 address. Built-in string replacement functions make the implementation concise and efficient, while a manual character-by-character approach reinforces fundamental programming concepts. The problem’s simplicity and clear constraints enable a direct and elegant solution with linear time and space complexity.