Defanging An IP Address

Companies:
  • Amazon Interview Questions
  • Apple Interview Questions
  • Facebook Interview Questions

Problem Source: LeetCode
Companies: Facebook, Amazon, Apple

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 = “172.16.140.1”

Output: “172[.]16[.]140[.]1”

Example 2:

Input: address = “255.135.3.6”

Ouptput: “255[.]135[.]3[.]6[.]”

Constraints:

  • The given address is a valid IPv4 address.

Solution:

This is a very simple problem, we just have to manipulate our given string and add [ to the left of . and ] to the right of . or simply replace . with [.].

We can use built-in methods of java and python to solve this problem.

Implementation:

Java

class Solution {
    public String defangIPaddr(String address) {
            //String.replaceAll() takes in a regex which needs to be escaped
            return address.replaceAll("\\.", "\\[\\.\\]");
        }
}

Python

class Solution:
    def defangIPaddr(self, address: str) -> str:
        return address.replace(".","[.]")

Complexity Analysis:

  • Time complexity: O(n).
  • Space complexity: O(n).
Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]