Skip to main content

1108. Defanging an IP Address

easy

Replace every period in an IPv4 address with '[.]' to neutralise it for safe logging. A single-pass scan with one substitution rule.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged IP address replaces every period '.' with '[.]'.

Constraints

  • The given address is a valid IPv4 address.
  • address.length is between 7 and 15 inclusive.

Examples

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"

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

A built-in replace works in one line: address.replace('.', '[.]').

Hint 2

For an interview, also show the manual build: walk each character, append '[.]' on a period and the character otherwise.

Hint 3

Use a list buffer and join at the end to avoid quadratic concatenation in languages where strings are immutable.

Solution approach

Reveal approach

Linear scan, appending '[.]' on each period and the character itself otherwise into a list, then join. O(n) time and O(n) space for the output. The built-in replace is equivalent in big-O terms but the manual version makes the cost model explicit — important when interviewers ask 'now write it without library calls'.

Complexity

Time
O(n)
Space
O(n)

Related patterns

  • string-building
  • linear-scan

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon

Practice these live with InterviewChamp.AI

Drill Defanging an IP Address and Strings problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →