Defanging an IP Address - Problem

Given a valid (IPv4) IP address, return a defanged version of that IP address.

A defanged IP address replaces every period "." with "[.]".

Input & Output

Example 1 — Basic Case
$ Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"
💡 Note: Replace each dot with [.]: 1.1.1.1 becomes 1[.]1[.]1[.]1
Example 2 — Standard IP
$ Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"
💡 Note: Each dot is replaced with [.] while numbers remain unchanged
Example 3 — Different Numbers
$ Input: address = "192.168.1.1"
Output: "192[.]168[.]1[.]1"
💡 Note: Three dots become three [.] replacements

Constraints

  • The given address is a valid IPv4 address.

Visualization

Tap to expand
Defanging an IP Address Replace every "." with "[.]" in IP address INPUT Original IP Address: "1.1.1.1" Character breakdown: 1 . 1 . 1 . 1 = Period to replace Total periods: 3 Each "." becomes "[.]" ALGORITHM STEPS 1 Initialize Take input string 2 Call Replace Use built-in replace() address.replace( "." , "[.]" ) 3 Process All Replace all occurrences . --> [.] 4 Return Result Output defanged string FINAL RESULT Defanged IP Address: "1[.]1[.]1[.]1" Result breakdown: 1 [.] 1 [.] 1 [.] 1 OK - Success! Original length: 7 Result length: 13 Added chars: +6 Time: O(n) | Space: O(n) Key Insight: The built-in string replace() method efficiently handles all period replacements in one call. "Defanging" prevents IP addresses from being auto-linked or parsed as network addresses in text. TutorialsPoint - Defanging an IP Address | Built-in String Replace Approach
Asked in
Amazon 15 Google 8
185.0K Views
Low Frequency
~5 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen