← Home

93. Restore IP Addresses

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
backtrackingC++Markdown
93

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 93. Restore IP Addresses, the solution in this repository is mainly a backtracking solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: backtracking.

The notes already sitting in the source point us in the right direction:

  • backtracking

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are join, isValid, backtrack, restoreIpAddresses.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • Substring checks are convenient but not free, so they are part of the real complexity story.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//backtracking
02//Runtime: 4 ms, faster than 80.26% of C++ online submissions for Restore IP Addresses.
03//Memory Usage: 7.1 MB, less than 26.58% of C++ online submissions for Restore IP Addresses.
04class Solution {
05public:
06    vector<string> ans;
07    
08    string join(const string& s, vector<int>& split){
09        string ret = s;
10        
11        for(int i = split.size()-1; i >= 0; --i){
12            // cout << split[i] << " " << ret << endl;
13            ret.insert(ret.begin()+split[i], '.');
14        }
15        // cout << ret << endl;
16        
17        return ret;
18    }
19    
20    bool isValid(string s){
21        //length == 0 or length > 3
22        if(s.empty() || s.size() > 3) return false;
23        //length == 3 and >= 256
24        if(s.size() == 3 && stoi(s) >= 256) return false;
25        //length > 1 and start with 0
26        if(s.size() > 1 && s[0] == '0') return false;
27        return true;
28    }
29    
30    void backtrack(string& s, int start, vector<int>& split){
31        if(split.size() == 3){
32            if(isValid(s.substr(split.back()))){
33                ans.push_back(join(s, split));
34            }
35        }else{
36            for(int len = 1; len <= 3 && start + len < s.size(); ++len){
37                if(!isValid(s.substr(start, len))) continue;
38                //now s[start:start+len-1] is valid
39                //'.' will be the (start+len)th char
40                split.push_back(start+len);
41                backtrack(s, start+len, split);
42                split.pop_back();
43            }
44        }
45    }
46    
47    vector<string> restoreIpAddresses(string s) {
48        vector<int> split;
49        backtrack(s, 0, split);
50        return ans;
51    }
52};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.