Bird
Raised Fist0
Interview PrepbacktrackingmediumAmazonFacebookGoogle

Restore IP Addresses

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
</>
IDE
def restore_ip_addresses(s: str) -> list:public List<String> restoreIpAddresses(String s)vector<string> restoreIpAddresses(string s)function restoreIpAddresses(s)
def restore_ip_addresses(s: str) -> list:
    # Write your solution here
    pass
class Solution {
    public List<String> restoreIpAddresses(String s) {
        // Write your solution here
        return new ArrayList<>();
    }
}
#include <vector>
#include <string>
using namespace std;

vector<string> restoreIpAddresses(string s) {
    // Write your solution here
    return {};
}
function restoreIpAddresses(s) {
    // Write your solution here
}
0/10
Common Bugs to Avoid
Wrong: ["255.255.111.35", "255.255.11.135", "255.255.111.135"]Including segments longer than 3 digits or not pruning segments > 255.Add condition to skip segments longer than 3 or with integer value > 255.
Wrong: ["0.0.0.0", "00.0.0.0"]Allowing segments with leading zeros like '00'.Reject segments starting with '0' unless segment is exactly '0'.
Wrong: ["1.0.10.23", "1.0.102.3", "10.1.0.23", "10.10.2.3"]Missing some valid IPs due to incomplete backtracking or pruning too early.Ensure backtracking explores all segment length options 1 to 3 and validates each segment.
Wrong: ["255.255.255.256"]Not checking upper bound of 255 for segments.Add check to reject segments with integer value > 255.
Wrong: ["0.10.0.10", "0.100.1.0", "0.01.0.10"]Allowing segments with leading zeros like '01'.Reject segments starting with '0' and length > 1.
Test Cases
t1_01basic
Input{"s":"25525511135"}
Expected["255.255.11.135","255.255.111.35"]

The string can be split into these two valid IP addresses by placing dots at appropriate positions.

t1_02basic
Input{"s":"101023"}
Expected["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

Multiple valid IP addresses can be formed by splitting the string into 4 valid segments.

t2_01edge
Input{"s":""}
Expected[]

Empty input string cannot form any valid IP address.

t2_02edge
Input{"s":"1"}
Expected[]

Input length less than 4 cannot form a valid IP address with 4 segments.

t2_03edge
Input{"s":"0000"}
Expected["0.0.0.0"]

All segments are '0', which is valid; no leading zeros issue here.

t2_04edge
Input{"s":"1234567890123"}
Expected[]

Input length greater than 12 cannot form valid IP addresses since max 3 digits per segment and 4 segments.

t3_01corner
Input{"s":"255255255255"}
Expected["255.255.255.255"]

Maximum valid IP address with all segments at upper boundary 255.

t3_02corner
Input{"s":"010010"}
Expected["0.10.0.10","0.100.1.0"]

Tests handling of leading zeros and multiple valid splits.

t3_03corner
Input{"s":"1111"}
Expected["1.1.1.1"]

Minimal valid IP with all segments length 1.

t4_01performance
Input{"s":"12345678901234567890"}
⏱ Performance - must finish in 2000ms

Input length 20 (max constraint). Backtracking with pruning must complete within 2 seconds.

Practice

(1/5)
1. You need to generate all combinations of balanced parentheses pairs for a given number n. Which algorithmic approach guarantees generating only valid sequences without generating invalid ones first?
easy
A. Brute force: generate all possible sequences of '(' and ')' of length 2n, then filter valid ones
B. Backtracking with pruning: build sequences by adding '(' or ')' only when it keeps the sequence valid
C. Greedy approach: always add '(' until n is reached, then add ')' to close all opened parentheses
D. Dynamic programming: count the number of valid sequences using Catalan number formula

Solution

  1. Step 1: Understand problem constraints

    We want to generate all valid parentheses sequences without generating invalid ones first.
  2. Step 2: Analyze approaches

    Brute force generates all sequences including invalid ones, greedy fails to generate all valid sequences, DP counts sequences but does not generate them. Backtracking with pruning adds '(' or ')' only when valid, thus generating only valid sequences.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Backtracking with pruning avoids invalid sequences [OK]
Hint: Backtracking prunes invalid sequences early [OK]
Common Mistakes:
  • Thinking greedy can generate all valid sequences
  • Confusing counting with generating sequences
2. The following code attempts to solve N-Queens using bitmask backtracking. Which line contains a subtle bug that can cause invalid solutions or missed solutions?
medium
A. Line extracting rightmost 1-bit as position
B. Line updating diag1 and diag2 with incorrect bit shifts in recursive call
C. Line computing available_positions with bitmask and negation
D. Line resetting board[row][col] to '.' after recursion

Solution

  1. Step 1: Identify bit shift directions for diagonals

    diag1 (major diagonal) must be shifted left by 1, diag2 (minor diagonal) shifted right by 1 to reflect next row attacks.
  2. Step 2: Check recursive call shifts

    The code incorrectly shifts diag1 right and diag2 left, reversing the attack directions, causing invalid pruning.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Correct diagonal shifts are diag1 << 1 and diag2 >> 1 [OK]
Hint: Diagonal attack masks must shift opposite directions each row [OK]
Common Mistakes:
  • Swapping diag1 and diag2 shifts
  • Not resetting board after recursion
  • Incorrect bitmask negation
3. What is the time complexity of the optimal backtracking algorithm that generates unique permutations of an array with duplicates by sorting and skipping duplicates during recursion?
medium
A. O(n! * log n) due to sorting and binary search for duplicates
B. O(n! * n^2) because each permutation requires copying the array and checking duplicates
C. O(n^n) because the recursion explores all possible swaps without pruning
D. O(n! * n) because pruning duplicates early reduces redundant branches but each permutation still requires O(n) copying

Solution

  1. Step 1: Identify complexity of outer and inner loops

    Backtracking explores permutations, which is O(n!). Each permutation requires copying O(n) elements to result.
  2. Step 2: Check if pruning duplicates reduces complexity

    Pruning duplicates early avoids redundant branches, so complexity is O(n! * n), not worse. Sorting is O(n log n) but done once.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Pruning reduces branches but copying each permutation costs O(n) [OK]
Hint: Pruning duplicates reduces branches but copying costs O(n) per permutation [OK]
Common Mistakes:
  • Confusing pruning effect or ignoring copy cost
4. What is the time complexity of the optimal backtracking with Trie approach for Word Search II, given a board of size MxN and a list of words with maximum length L? Assume the Trie is already built.
medium
A. O(M * N * 4 * 3^(L-1)) due to pruning and adjacency constraints
B. O(M * N * 4^L * W), where W is the number of words
C. O(M * N * L^2) because each cell explores all prefixes
D. O(M * N * L) since each cell is visited once per character

Solution

  1. Step 1: Identify branching factor in backtracking

    From each cell, up to 4 directions are possible initially, then up to 3 directions for subsequent steps due to no revisiting.
  2. Step 2: Calculate complexity with pruning

    Trie pruning reduces unnecessary paths, so complexity is roughly O(M * N * 4 * 3^(L-1)) where L is max word length.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Matches known complexity from Trie + backtracking analysis [OK]
Hint: Branching factor reduces after first step due to visited constraints [OK]
Common Mistakes:
  • Confusing W (number of words) as multiplicative factor in optimal approach.
5. Examine the following code snippet for the Word Search problem. It is almost correct but contains one subtle bug. Identify the line causing the bug.
medium
A. Line where board[r][c] = temp is restored after recursion
B. Line where temp = board[r][c]
C. Line where directions are defined
D. Line missing board[r][c] = '#' to mark visited

Solution

  1. Step 1: Identify missing visited marking

    The code does not mark the current cell as visited before recursive calls, allowing revisits.
  2. Step 2: Understand impact of missing marking

    Without marking, dfs can revisit the same cell multiple times, causing incorrect matches or infinite loops.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Marking visited cells is essential to prevent reuse [OK]
Hint: Check if visited cells are marked before recursion [OK]
Common Mistakes:
  • Forgetting to mark visited cells
  • Restoring cell too early