Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on core interview patterns fundamentals.
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 = "1.1.1.1" Output: "1[.]1[.]1[.]1"
Example 2:
Input: address = "255.100.50.0" Output: "255[.]100[.]50[.]0"
Constraints:
address is a valid IPv4 address.Problem summary: Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged IP address replaces every period "." with "[.]".
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: General problem-solving
"1.1.1.1"
"255.100.50.0"
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1108: Defanging an IP Address
class Solution {
public String defangIPaddr(String address) {
return address.replace(".", "[.]");
}
}
// Accepted solution for LeetCode #1108: Defanging an IP Address
func defangIPaddr(address string) string {
return strings.Replace(address, ".", "[.]", -1)
}
# Accepted solution for LeetCode #1108: Defanging an IP Address
class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace('.', '[.]')
// Accepted solution for LeetCode #1108: Defanging an IP Address
struct Solution;
impl Solution {
fn defang_i_paddr(address: String) -> String {
address.replace(".", "[.]")
}
}
#[test]
fn test() {
let address = "1.1.1.1".to_string();
let res = "1[.]1[.]1[.]1".to_string();
assert_eq!(Solution::defang_i_paddr(address), res);
let address = "255.100.50.0".to_string();
let res = "255[.]100[.]50[.]0".to_string();
assert_eq!(Solution::defang_i_paddr(address), res);
}
// Accepted solution for LeetCode #1108: Defanging an IP Address
function defangIPaddr(address: string): string {
return address.split('.').join('[.]');
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.