Problem 1108

Abstract / Summary

Replace every period in the given ip address with three dots and a bracket to produce a defanged version of the address.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1108.py

class Solution:
    def defangIPaddr(self, address: str) -> str:
        return address.replace(".", "[.]")
3 lines | 111 bytes | submitted October 27, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 90% (900k+ submissions).

Typical patterns to solve this problem:
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method, defangIPaddr. The method receives an IPv4 address as a string and returns a transformed version where every period (.) is replaced by the sequence [.]. This transformation, often called “defanging,” is used to make the address safe for contexts where a literal dot could be interpreted specially, such as in certain markup or logging systems. The implementation relies on Python’s built-in string method replace, which performs the substitution in a single, efficient pass.

Key Steps

The core logic consists of a single expression:

return address.replace(".", "[.]")

The method begins by invoking replace on the input string address. The first argument to replace is the target substring, the period character, and the second argument is the replacement string [.]. The call returns a new string where every occurrence of the period has been substituted, and this new string is returned directly to the caller.

Edge Cases Handled

When the input string contains no periods, the replace call leaves the string unchanged, and the method returns the original address. This behavior correctly handles IP addresses that are already defanged or malformed strings lacking the expected delimiter. An empty string is also a valid input for replace; the method will return an empty string, which is a sensible result for an absent address. Strings with consecutive periods, such as "192..168.1.1", are processed correctly: each period is replaced individually, yielding "192[.][.]168[.]1[.]1". Leading or trailing periods are treated the same way, ensuring that any dot at the start or end of the string is safely escaped.

Performance Optimizations

The implementation leverages Python’s native replace method, which is implemented in C and operates at a lower level than a manual loop in pure Python. This choice eliminates the overhead of iterating over each character in Python code, reducing interpreter dispatch costs. The method also avoids constructing intermediate strings; replace computes the final result in a single allocation, minimizing memory churn. Because the operation is performed in one pass, the runtime scales linearly with the length of the input string, but the constant factors are kept low due to the optimized C implementation. The absence of additional data structures or conditional logic further contributes to a lean execution path.

written by openai gpt

ELI5 - Simplified Explanation

Think of this code like a little machine that helps a computer read secret addresses. Sometimes computers see dots in an address and get a bit confused. To help them out, this machine looks for every single dot in the address and swaps it with a special bracket-dot-bracket shape. It is like taking a plain piece of paper and putting colorful frames around all the little dots so they stand out and are easy to spot. The machine goes through the whole address from start to finish until every dot has a new, fancy frame.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 9 | μ = 8.42 | σ = 2.10

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
lzl124631x C++
muhammadfarhankt Go
qiyuangong Java
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
lzl124631x C++
muhammadfarhankt Go
qiyuangong Java
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
34 links | 23 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

2 easy 2 medium
5 solutions   October 27, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality