BackmediumStringsOracleAtlassian

Galactic Transmission 3 Solution

Problem Statement

You are given a list of distinct packet strings and one of them is marked as the final packet. A packet A is considered a valid predecessor of packet B if B can be produced by inserting exactly one character at any position in A while keeping the relative order of the existing characters unchanged. Using only the packets supplied in the list, determine the maximum possible number of packets that can form a valid chain that ends with the final packet. The chain must start with any packet in the list and each subsequent packet must be a valid predecessor of the next one, with the last packet in the chain being the final packet. Output the length of the longest such chain.

Input format:

  • The first line contains an integer N (1 ≤ N ≤ 10^5), the number of packets.
  • The following N lines each contain a non‑empty string consisting of lowercase English letters. All strings are distinct.
  • The final packet is guaranteed to be one of the N strings.

Output format:

  • A single integer: the length of the longest valid predecessor chain that ends with the final packet.

The problem requires an efficient algorithm that can handle up to 10^5 packets and string lengths up to 10^3.

Example 1
Input
5 a ab abc abcd abcde
Output
5

Explanation: Starting from "a", each string adds one character: a → ab → abc → abcd → abcde. This chain has length 5, which is the maximum possible.

Example 2
Input
6 x xy xyz xz xyzq xyzqr
Output
5

Explanation: The longest chain is x → xy → xyz → xyzq → xyzqr. The string "xz" cannot be inserted into this chain because it would break the predecessor rule. Thus the maximum length is 5.

Example 3
Input
4 a b c d
Output
1

Explanation: No two strings satisfy the predecessor condition, so each packet forms a chain of length 1. The final packet "d" yields a chain length of 1.

Example 4
Input
7 a aa aaa aaaa aaaaa aaaaaa aaaaaaa
Output
7

Explanation: Each string is obtained by appending one 'a' to the previous one, giving a chain of length 7 that ends with "aaaaaaa".

Constraints

  • 1 <= N <= 100000
  • 1 <= length of each string <= 1000
  • All strings consist only of lowercase English letters
  • All strings are distinct
  • The final packet is guaranteed to be present in the list
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Galactic Transmission 3 — Problem Statement & Solution Guide

StringsMediumMixed
TimeO(n·L^2)
|
SpaceO(n·L)

Problem Description

You are given a list of distinct packet strings and one of them is marked as the final packet. A packet A is considered a valid predecessor of packet B if B can be produced by inserting exactly one character at any position in A while keeping the relative order of the existing characters unchanged. Using only the packets supplied in the list, determine the maximum possible number of packets that can form a valid chain that ends with the final packet. The chain must start with any packet in the list and each subsequent packet must be a valid predecessor of the next one, with the last packet in the chain being the final packet. Output the length of the longest such chain.

Input format:

- The first line contains an integer N (1 ≤ N ≤ 10^5), the number of packets.

- The following N lines each contain a non‑empty string consisting of lowercase English letters. All strings are distinct.

- The final packet is guaranteed to be one of the N strings.

Output format:

- A single integer: the length of the longest valid predecessor chain that ends with the final packet.

The problem requires an efficient algorithm that can handle up to 10^5 packets and string lengths up to 10^3.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Galactic Transmission 3"

medium

WHY DOES IT MATTER?

The insertion‑chain pattern is a textbook example of dynamic programming on DAGs, illustrating how local optimality (best chain ending at a string) leads to a global optimum. It teaches how to transform a seemingly combinatorial problem into a manageable DP by exploiting a natural ordering (string length).

OPTIMIZATION CHALLENGE

The key insight is that every predecessor of a string can be obtained by deleting one character, which is a linear operation. By pre‑computing a hash set of all strings, we reduce predecessor lookup from O(n) to O(1), cutting the complexity from quadratic to near‑linear.

REAL-WORLD CONNECTION

In distributed systems, log replication often involves incremental snapshots where each snapshot is derived by adding a small delta to the previous one. Detecting the longest consistent chain of snapshots is analogous to finding the longest insertion chain, ensuring data integrity across nodes.

When explaining this to an interviewer, emphasize the topological order induced by string length and the two‑step DP: generate predecessors, look up their best chain, and update. Highlight that the algorithm is essentially a longest‑path in a DAG with O(n·L^2) time.

COMPLEXITY AT A GLANCE

⏱ Time:O(n·L^2)
💾 Space:O(n·L)

Core Theory — Why This Approach?

The problem reduces to finding the longest chain of strings where each string is obtained from its predecessor by inserting a single character. This is a classic longest‑path problem on a directed acyclic graph (DAG) where vertices are the given packets and an edge A→B exists if B can be formed by inserting one character into A. Because all strings are distinct and the insertion operation strictly increases length, the graph is acyclic and can be topologically sorted by string length. A naive approach would compare every pair of strings, yielding O(n^2·L) time (L is average length). For large n this is infeasible. The optimal paradigm sorts the strings by length, then for each string generates all possible predecessors by deleting one character and looks them up in a hash set. Dynamic programming stores the best chain length ending at each string, updating in O(1) per predecessor. This yields O(n·L^2) time and O(n·L) space, which is practical for n up to 10^5 and moderate string lengths.

Interview Questions on This Problem

Q1How would you modify this algorithm if the packets could be reordered arbitrarily, not just by insertion?

If reordering is allowed, the problem becomes finding the longest subsequence where each string is a subsequence of the next. This can be solved by dynamic programming over the sorted list of strings, but the predecessor check becomes O(L^2) per pair, leading to O(n^2·L^2). To keep it efficient, one could use suffix trees or bitmask DP for small alphabets, but the problem is inherently harder and often requires heuristic or approximation in practice.

Q2In a fintech platform, why is it important to detect such insertion chains in transaction logs?

Insertion chains can model incremental fraud patterns where a malicious transaction evolves by adding subtle changes. Detecting the longest chain helps identify the most sophisticated fraud sequence. The algorithm’s linearithmic behavior ensures it can run on streaming logs in real time, which is critical for compliance and risk mitigation.

Q3During a high‑growth startup interview, a candidate proposes a recursive DFS with memoization. What are the pros and cons of this approach compared to the iterative DP?

DFS with memoization is conceptually simple and naturally fits the DAG structure. However, it can suffer from deep recursion limits and stack overflow for long chains, and it may recompute predecessor generation multiple times if not carefully memoized. The iterative DP with sorting avoids recursion overhead, guarantees linear pass, and is easier to reason about for interviewers.

Examples

Example 1

Input

5
 a
 ab
 abc
 abcd
 abcde

Output

5

Explanation: Starting from "a", each string adds one character: a → ab → abc → abcd → abcde. This chain has length 5, which is the maximum possible.

Example 2

Input

6
 x
 xy
 xyz
 xz
 xyzq
 xyzqr

Output

5

Explanation: The longest chain is x → xy → xyz → xyzq → xyzqr. The string "xz" cannot be inserted into this chain because it would break the predecessor rule. Thus the maximum length is 5.

Example 3

Input

4
 a
 b
 c
 d

Output

1

Explanation: No two strings satisfy the predecessor condition, so each packet forms a chain of length 1. The final packet "d" yields a chain length of 1.

Example 4

Input

7
 a
 aa
 aaa
 aaaa
 aaaaa
 aaaaaa
 aaaaaaa

Output

7

Explanation: Each string is obtained by appending one 'a' to the previous one, giving a chain of length 7 that ends with "aaaaaaa".

Constraints

  • 1 <= N <= 100000
  • 1 <= length of each string <= 1000
  • All strings consist only of lowercase English letters
  • All strings are distinct
  • The final packet is guaranteed to be present in the list

Optimal Approach & Strategy

Sort strings by length, use a hash set for O(1) lookups, and for each string generate all strings formed by deleting one character. Update a DP map with the best chain length. This runs in O(n·L^2) time and O(n·L) space.

Brute Force Approach

Compare every pair of strings; for each pair check if one can be turned into the other by inserting a single character. Keep the longest chain found. This is O(n^2·L) time and O(1) extra space.

Verified Code Solutions

JavaScript Solution
Time: O(n·L^2)
const fs = require('fs');
const input = fs.readFileSync(0,'utf8').trim().split(/\s+/);
let idx=0;
function longestChain(msgs, target){
    const set = new Set(msgs);
    if(!set.has(target)) return 0;
    const all = msgs.concat([target]);
    all.sort((a,b)=>a.length-b.length);
    const dp = new Map();
    let ans=0;
    for(const s of all){
        let best=1;
        if(s.length>1){
            for(let i=0;i<s.length;i++){
                const pred = s.slice(0,i)+s.slice(i+1);
                if(dp.has(pred)) best = Math.max(best, dp.get(pred)+1);
            }
        }
        dp.set(s,best);
        if(s===target) ans=best;
    }
    return ans;
}
const n = parseInt(input[idx++]);
let msgs = [];
for(let i=0;i<n;i++) msgs.push(input[idx++]);
const target = input[idx++]||'';
console.log(longestChain(msgs, target).toString());

Asked in Top Tech Interviews

OracleAtlassian

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.