Defanging An IP Address

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

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

Example 2:

Input: address = “”

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


  • The given address is a valid IPv4 address.


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.



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


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"]