1. Triple Nested Loops for 3 Dot Placements
Intuition
Iterate i from 1 to 3, j from i+1 to i+3, and k from j+1 to j+3. Slice the 4 segments s[0..i], s[i..j], s[j..k], s[k..N], and check if all 4 are valid.
Algorithm
- Step 1: Use 3 nested loops to place 3 dot separators dividing string into 4 parts.
- Step 2: For each split (s1, s2, s3, s4), check length constraints (1 to 3 characters each).
- Step 3: Validate each segment: no leading zeros (unless single
0) and numeric value <= 255. - Step 4: If all 4 segments are valid, format as s1.s2.s3.s4 and add to result.
#include <iostream>#include <vector>#include <string> class Solution {public: bool isValid(const std::string& s) { if (s.empty() || s.length() > 3) return false; if (s[0] == '0' && s.length() > 1) return false; int val = std::stoi(s); return val >= 0 && val <= 255; } std::vector<std::string> restoreIpAddresses(std::string s) { std::vector<std::string> result; int n = s.length(); if (n < 4 || n > 12) return result; for (int i = 1; i <= 3 && i < n; i++) { for (int j = i + 1; j <= i + 3 && j < n; j++) { for (int k = j + 1; k <= j + 3 && k < n; k++) { std::string s1 = s.substr(0, i); std::string s2 = s.substr(i, j - i); std::string s3 = s.substr(j, k - j); std::string s4 = s.substr(k); if (isValid(s1) && isValid(s2) && isValid(s3) && isValid(s4)) { result.push_back(s1 + "." + s2 + "." + s3 + "." + s4); } } } } return result; }}; int main() { Solution solver; std::vector<std::string> res = solver.restoreIpAddresses("25525511135"); std::cout << "Nested Loop Output for '25525511135':\n"; for (const auto& ip : res) { std::cout << ip << "\n"; } return 0;}Time & Space Complexity
- Time complexity:
O(1)— Loops execute at most 3 * 3 * 3 = 27 iterations. - Space complexity:
O(1)— O(1) auxiliary memory.