Restore IP Addresses - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "25525511135"
Output: ["255.255.11.135","255.255.111.35"]
💡 Note: Two valid IP addresses can be formed: 255.255.11.135 and 255.255.111.35. Each segment is between 0-255 with no leading zeros.
Example 2 — No Valid IPs
$ Input: s = "0000"
Output: ["0.0.0.0"]
💡 Note: Only one valid IP can be formed: 0.0.0.0. Each segment is exactly '0' which is valid.
Example 3 — Leading Zero Issue
$ Input: s = "101023"
Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
💡 Note: Multiple valid combinations exist. Note that segments like '010' are invalid due to leading zeros.

Constraints

  • 1 ≤ s.length ≤ 20
  • s consists of digits only

Visualization

Tap to expand
Restore IP Addresses INPUT String s = "25525511135" 2 5 5 2 5 5 1 1 1 3 5 0 1 2 3 4 5 6 7 8 9 10 IP Address Rules: - Exactly 4 segments - Each: 0-255 - No leading zeros (01, 001) - Length: 11 chars Need to place 3 dots: 2 5 5 . 2 5 5 . 1 1 . 1 3 5 ALGORITHM STEPS 1 Backtracking Setup Track: position, segments, path 2 Try Segment Lengths Try 1, 2, or 3 digits each time 3 Validate Segment Check: 0-255, no leading 0 4 Build Result When 4 segments, add to result Backtracking Tree (partial) 255 255.2 255.25 255.255.11 255.255.111 ...135 ...35 FINAL RESULT Valid IP Addresses Found: 2 IP Address #1 255.255.11.135 [3][3][2][3] digits IP Address #2 255.255.111.35 [3][3][3][2] digits Output Array: ["255.255.11.135", "255.255.111.35"] Validation: OK All segments 0-255, no leading zeros Key Insight: Use backtracking to try all possible ways to place 3 dots in the string. At each position, try segments of length 1, 2, or 3. Prune invalid branches early: reject segments greater than 255 or with leading zeros. Time complexity: O(3^4) = O(81) since we make at most 3 choices for each of 4 segments. TutorialsPoint - Restore IP Addresses | Backtracking Approach
Asked in
Facebook 35 Google 25 Amazon 20
185.0K Views
Medium Frequency
~25 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen