#1108

Defanging an IP Address

Easy
StringString ManipulationRegular Expressions
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses built-in string manipulation methods to replace all occurrences of '.' in a single pass. This is efficient and leverages the language's capabilities to handle string replacement directly.

⚙️

Algorithm

2 steps
  1. 1Step 1: Use the string replace method to replace all '.' with '[.]'.
  2. 2Step 2: Return the modified string.
solution.py2 lines
1def defangIPaddr(address):
2    return address.replace('.', '[.]')

Complexity note: The time complexity is O(n) because we traverse the string once to replace the characters. The space complexity is O(n) since we create a new string for the result.

  • 1String manipulation can often be optimized with built-in methods.
  • 2Understanding time complexity is crucial for evaluating performance.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.