cswork / libraryOpen practice workspace

Coding questions · TikTok

Find second-minimal word segmentation count

This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Find second-minimal word segmentation count states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.

Given a string s and a dictionary D of non-empty words, define a 'segmentation' as splitting s into a sequence of words from D whose concatenation equals s. Let the cost of a segmentation be the number of words used. Return the second-smallest possible cost among all valid segmentations, or -1 if fewer than two valid segmentations exist. Only return the cost; do not enumerate segmentations. Describe your algorithm, justify its time and space complexity, and explain how you would handle large inputs.

What a Strong Answer Covers

  • A clear algorithm with the right data structures and enough pseudocode or code-level detail to implement it.
  • A correctness argument that explains why the algorithm covers all required cases.
  • Time and space complexity, plus at least one alternative approach when relevant.
  • Focused tests for normal cases, edge cases, and failure modes.

Follow-up Questions

  • How would the approach change if the input were streaming or too large for memory?
  • What invariants would you assert in production code?
  • Which tests would catch off-by-one, duplicate, or tie-breaking bugs?

Find second-minimal word segmentation count

Given a string s and a dictionary D of non-empty words, a segmentation splits s into a sequence of words from D whose concatenation equals s. The cost of a segmentation is the number of words it uses.

Return the second-smallest possible cost among all valid segmentations of s. If two different segmentations have the same cost, that cost is counted once per segmentation (i.e. consider the multiset of costs over all valid segmentations and return the value at the second position when sorted ascending). Return -1 if fewer than two valid segmentations exist.

Return only the cost — do not enumerate the segmentations.

Examples

  • s = "catsanddog", D = ["cat","cats","and","sand","dog"] → 3. The two valid segmentations are cats|and|dog (cost 3) and cat|sand|dog (cost 3); the sorted multiset of costs is [3, 3], so the second-smallest is 3.
  • s = "aaa", D = ["a","aa"] → 2. Segmentations: a|aa (2), aa|a (2), a|a|a (3); sorted costs [2, 2, 3], second-smallest is 2.
  • s = "leetcode", D = ["leet","code"] → -1. Only one valid segmentation exists.

The word dictionary is passed as a list words; a word may be reused any number of times.

Constraints

  • 1 <= len(s) <= 10^4 (s may also be empty, in which case the answer is -1).
  • Each word in the dictionary is non-empty.
  • Words may be reused any number of times within a segmentation.
  • Return -1 when fewer than two valid segmentations exist.

Hints

  1. This is a variant of Word Break II, but you must NOT enumerate segmentations — track only the best two costs per prefix.
  2. Let dp[i] hold the two smallest costs to segment the prefix s[0:i]. To extend, for every word ending at i, add 1 to each of the predecessor's two best costs and keep the global two smallest.
  3. Keep a separate ways[i] counter (number of valid segmentations of s[0:i]) so you can correctly return -1 when fewer than two full segmentations exist — even if the two best costs happen to be equal.
  4. Because costs are positive and additive, keeping only the two smallest per node is sufficient: the second-smallest full-string cost always extends one of the two smallest predecessor costs.

Solution

Solution Alignment

The prompt asks for an implementation-level answer. The safest way to present it is to define the state, maintain clear invariants, then walk through complexity and tests.

Problem Restatement

Given a string s and a dictionary D of non-empty words, define a 'segmentation' as splitting s into a sequence of words from D whose concatenation equals s. Let the cost of a segmentation be the number of words used. Return the second-smallest possible cost among all valid segmentations, or -1 if fewer than two valid segmentations exist. Only return the cost; do not enumerate segmentations. Describe your algorithm, justify its time and space complexity, and explain how you would handle large inputs.

Recommended Approach

Use the string constraints to choose between two pointers, a stack, frequency counts, prefix/suffix state, or dynamic programming. Maintain the invariant that processed characters have already been normalized, counted, or matched according to the operation.

Correctness

The implementation should maintain an invariant after each loop or operation that directly matches the problem statement. At termination, that invariant implies the returned value has considered every valid candidate exactly once, or has preserved the required data-structure state after every API call.

Complexity

Most direct string scans are O(n) time. Space ranges from O(1) for two pointers to O(n) for stacks, maps, or DP tables.

Edge Cases and Tests

Empty string, length 1, repeated characters, invalid characters, case sensitivity, Unicode vs ASCII, and very long input.