Similar Problems

Similar Problems not available

Defanging An Ip Address - Leetcode Solution

Companies:

LeetCode:  Defanging An Ip Address Leetcode Solution

Difficulty: Easy

Topics: string  

Problem Statement: 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"

Solution: We can solve this problem by iterating through each character in the string and adding it to a new string variable. Whenever we encounter a period "." we replace it with "[.]" and add it to the new string. Finally, we return the new string as the defanged IP address.

Algorithm:

  1. Initialize a new string variable defanged_ip to empty string
  2. Iterate through each character in the input string address
  3. If the current character is a period ".", replace it with "[.]" and add it to the defanged_ip string
  4. If the current character is not a period ".", simply add it to the defanged_ip string
  5. After iterating through all characters, return the defanged_ip string as the defanged IP address

Pseudo code: def defang_ip(address): defanged_ip = "" for char in address: if char == ".": defanged_ip += "[.]" else: defanged_ip += char return defanged_ip

Time Complexity: The time complexity of this algorithm is O(n) where n is the length of the input string address. We iterate through each character in the string exactly once.

Space Complexity: The space complexity of this algorithm is also O(n) as we create a new string variable defanged_ip that is the same length as the input string address in the worst case.

Solution in Python:

class Solution: def defangIPaddr(self, address: str) -> str: defanged_ip = "" for char in address: if char == ".": defanged_ip += "[.]" else: defanged_ip += char return defanged_ip

#Test the solution s = Solution() print(s.defangIPaddr("1.1.1.1")) #1[.]1[.]1[.]1 print(s.defangIPaddr("255.100.50.0")) #255[.]100[.]50[.]0

Defanging An Ip Address Solution Code

1