Solving Leetcode Interviews in Seconds with AI: Restore IP Addresses
Introduction
In this blog post, we will explore how to solve the LeetCode problem "93" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order. Example 1: Input: s = "25525511135" Output: ["255.255.11.135","255.255.111.35"] Example 2: Input: s = "0000" Output: ["0.0.0.0"] Example 3: Input: s = "101023" Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"] Constraints: 1 <= s.length <= 20 s consists of digits only.
Explanation
Here's a breakdown of the approach, complexities, and the Python code:
High-Level Approach:
- Use recursion to explore all possible placements of three dots in the given string.
- At each step, check if the current segment (string between dots) is a valid integer (0-255 without leading zeros).
- If a valid combination of four segments is found, add it to the result.
Complexity:
- Runtime Complexity: O(33) which simplifies to O(1) because the number of iterations is bounded. The recursion depth is at most 4, and at each level, we try at most 3 possible lengths for a segment. Storage Complexity: O(1), primarily for the call stack and the list of valid IP addresses (which is also bounded due to the input constraints).
Python Code:
Code
def restoreIpAddresses(s: str) -> list[str]: """
Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s.
"""
result = []
def isValid(segment: str) -> bool:
"""Helper function to check if a segment is a valid integer between 0 and 255"""
if not segment:
return False
if len(segment) > 1 and segment[0] == '0':
return False
if int(segment) > 255:
return False
return True
def backtrack(index: int, dots: int, current_ip: str):
"""Recursive helper function to explore possible IP addresses"""
if dots == 4:
if index == len(s):
result.append(current_ip[:-1]) # Remove trailing dot
return
if index == len(s):
return
for i in range(1, min(4, len(s) - index + 1)):
segment = s[index:index + i]
if isValid(segment):
backtrack(index + i, dots + 1, current_ip + segment + ".")
backtrack(0, 0, "")
return result