00:00

Problem Statement

Input/Output Examples

Visual Explanation

The search also stops early when the remaining digits cannot fill the remaining parts, because every part needs between 1 and 3 digits. That pruning keeps the search tiny.

Approaches

Both approaches try every way to choose the part lengths. Backtracking prunes as it goes; the loop version enumerates the lengths directly.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Every address has four parts of 1 to 3 digits, so at most 81 splits are checked and the input can have at most 12 useful digits. Both approaches therefore run in constant time.

Interview Tips and Recommended Approach

  • Validate leading zeros. "0" is fine, but "00" and "01" are not.
  • Check the value, not just the length. A three-digit part must also be at most 255.
  • Prune by remaining length. It turns many hopeless branches into one comparison.
  • Explain why the complexity is constant. The number of parts and digits per part are both fixed.

Recommended Approach: Backtracking

Why: it applies the general backtracking pattern with clear pruning, so the same code structure works if the rules change, for example for a different number of parts.