Tutorialspoint
Problem
Solution
Submissions

Valid IP Addresses

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 12

Write a C# program to restore all possible valid IP addresses from a given string containing only digits. An IP address consists of four decimal numbers separated by dots, each ranging from 0 to 255 inclusive. Leading zeros in decimal numbers are not allowed except for the number 0 itself.

Example 1
  • Input: "25525511135"
  • Output: ["255.255.11.135", "255.255.111.35"]
  • Explanation:
    • There are two ways to split the given string into four valid decimal numbers:
    • 1. 255.255.11.135
    • 2. 255.255.111.35
    • Both are valid IP addresses.
Example 2
  • Input: "0000"
  • Output: ["0.0.0.0"]
  • Explanation:
    • There is only one way to split the given string into four valid decimal numbers:
    • 0.0.0.0
Constraints
  • 0 ≤ s.length ≤ 20
  • s consists of digits only
  • Time Complexity: O(1) since the input is constrained
  • Space Complexity: O(1) since we generate a finite number of IP addresses
StringsBacktracking TCS (Tata Consultancy Services)Walmart
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use backtracking to generate all possible combinations
  • Each valid IP address must have exactly 4 segments
  • Each segment must be between 0 and 255 inclusive
  • No leading zeros are allowed (except for 0 itself)
  • Try all possibilities of placing dots between digits

Steps to solve by this approach:

 Step 1: Check if the string length is between 4 and 12, as a valid IP address must have 4 to 12 digits.
 Step 2: Use four nested loops to try all possible combinations of separating the string into four parts.
 Step 3: Ensure that the sum of lengths of all four parts equals the length of the original string.
 Step 4: Parse each part as an integer and verify it's between 0 and 255.
 Step 5: Check for invalid leading zeros in each part (except when the part is just "0").
 Step 6: Construct valid IP addresses and add them to the result list.
 Step 7: Return all possible valid IP addresses found.

Submitted Code :