Code Logo

Luminous Script Segmentation Count

Published at05 Jan 2026
Hard 3 views
Like15

You are given a script string and a dictionary of allowed phrases. The job is to count how many different ways the full script can be segmented so that every piece is one of those phrases.

This is not about rearranging phrases. The order is fixed by the original script, and every character must be covered exactly once from left to right.

For example, if the script is empty, the answer is 1 because there is exactly one way to segment it: choose nothing. If the script can be broken in multiple valid phrase sequences, all of those count toward the total.

So the task is to count all valid left-to-right segmentations of the script using only the allowed phrases.

Example Input & Output

Example 1
Input
script = "lanternfair", phrases = ["lan","lantern","tern","fair"]
Output
1
Explanation

The script can be restored as "lantern fair" or "lan tern fair".

Example 2
Input
script = "riverlights", phrases = ["river","light","lights","riverlight"]
Output
2
Explanation

Only the segmentation "river lights" matches the script.

Example 3
Input
script = "", phrases = ["lantern"]
Output
1
Explanation

The empty script has one valid segmentation that uses no phrases.

Algorithm Flow

Recommendation Algorithm Flow for Luminous Script Segmentation Count
Recommendation Algorithm Flow for Luminous Script Segmentation Count

Solution Approach

This is a counting version of word break, so dynamic programming works well. Let dp[i] mean the number of ways to segment the suffix that starts at position i.

The base case is:

dp[script.length] = 1

That says once we reach the end of the string, we have found one complete valid segmentation.

At each position i, we try every phrase that matches the script starting there. If a phrase of length len fits, then every valid segmentation of the remaining suffix contributes to the current answer:

dp[i] += dp[i + len]

We fill the DP from right to left, or use memoized recursion to compute the same idea on demand.

At the end, dp[0] is the total number of valid segmentations for the whole script.

Best Answers

java
import java.util.*;
class Solution {
    public int count_segmentations(String s, String[] dictionary) {
        Set<String> words = new HashSet<>(Arrays.asList(dictionary));
        int n = s.length();
        int[] dp = new int[n + 1];
        dp[0] = 1;
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < i; j++) {
                if (words.contains(s.substring(j, i))) {
                    dp[i] += dp[j];
                }
            }
        }
        return dp[n];
    }
}