BackmediumStringsPaytmSalesforce

Galactic Transmission 2 Solution

Problem Statement

Given an array of transmission codes, each code being a non‑empty string of lowercase English letters, determine the maximum number of codes that can be arranged in a sequence such that for every consecutive pair the last character of the preceding code equals the first character of the following code. The sequence may use any subset of the given codes and each code may appear at most once. Return the length of the longest possible sequence.

Example 1
Input
["alpha","arc","coda","apple","eagle"]
Output
5

Explanation: "alpha" ends with 'a' → "arc" starts with 'a'. "arc" ends with 'c' → "coda" starts with 'c'. "coda" ends with 'a' → "apple" starts with 'a'. "apple" ends with 'e' → "eagle" starts with 'e'. All five codes satisfy the adjacency rule, so the longest sequence length is 5.

Example 2
Input
["star","rocket","titan","nebula","alpha"]
Output
5

Explanation: "star" ends with 'r' → "rocket" starts with 'r'. "rocket" ends with 't' → "titan" starts with 't'. "titan" ends with 'n' → "nebula" starts with 'n'. "nebula" ends with 'a' → "alpha" starts with 'a'. The five codes form a valid chain, giving a maximum length of 5.

Example 3
Input
["dog","cat","mouse","elephant"]
Output
1

Explanation: No two codes share the required start‑end character relationship. The best we can do is select any single code, so the longest possible sequence contains only one element.

Constraints

  • 1 <= codes.length <= 100000
  • 1 <= codes[i].length <= 20
  • codes[i] consists only of lowercase English letters
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 2 — Problem Statement & Solution Guide

StringsMediumMixed
TimeO(2^N * N * 26)
|
SpaceO(2^N * 26)

Problem Description

Given an array of transmission codes, each code being a non‑empty string of lowercase English letters, determine the maximum number of codes that can be arranged in a sequence such that for every consecutive pair the last character of the preceding code equals the first character of the following code. The sequence may use any subset of the given codes and each code may appear at most once. Return the length of the longest possible sequence.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Galactic Transmission 2"

medium

WHY DOES IT MATTER?

This pattern tests the ability to model string problems as graph problems and to recognize when exponential time complexity is acceptable (small N) or when heuristics are needed (large N). It is essential for understanding the limits of dynamic programming and the complexity of path problems in graphs.

OPTIMIZATION CHALLENGE

The key insight is to recognize that the state space can be reduced by using the bitmask of used codes (if N is small) or by aggregating codes by their start and end characters (if N is large but the alphabet is small). The optimization challenge is to balance the trade-off between the number of codes and the number of unique characters.

REAL-WORLD CONNECTION

This is analogous to routing data packets in a network where each packet has a source and destination, and you want to maximize the number of packets that can be routed in a single path without reusing a link. It is also similar to scheduling tasks where each task has a predecessor and successor constraint.

In an interview, always clarify the constraints on N (number of codes) and the alphabet size. If N is small (<= 20), propose bitmask DP. If N is large, discuss the NP-hardness and propose heuristic or approximation solutions. Show that you understand the complexity trade-offs.

COMPLEXITY AT A GLANCE

⏱ Time:O(2^N * N * 26)
💾 Space:O(2^N * 26)

Core Theory — Why This Approach?

The problem 'Galactic Transmission 2' is fundamentally a variation of the Longest Path problem in a Directed Acyclic Graph (DAG) or a general Directed Graph, but with a specific constraint: we are selecting a subset of edges (codes) to form a path. Each code acts as a directed edge from its first character to its last character. The goal is to find the longest sequence of these edges where the end of one edge matches the start of the next. This is equivalent to finding the longest path in a graph where nodes are characters (a-z) and edges are the transmission codes. However, since we can use each code at most once, this is not a simple longest path in a graph with unlimited edge traversal, but rather a problem of finding the maximum number of edges in a trail (a path with no repeated edges).

Naive approaches, such as brute-forcing all permutations of the codes, fail catastrophically for large inputs because the number of permutations grows factorially (O(N!)). Even dynamic programming over subsets of codes (O(2^N * N)) is infeasible for N > 20. The key insight is that the state space is not defined by the subset of codes used, but by the current position (last character) and the set of used codes. However, since the graph has only 26 nodes (lowercase letters), we can model this as a flow problem or use a specialized DP on the graph structure. Specifically, this problem can be transformed into finding the maximum number of edges in a path in a multigraph. For general graphs, finding the longest trail is NP-hard, but for this specific constraint (small alphabet size), we can use a DP approach where the state is (current_node, bitmask_of_used_codes) if N is small, or more efficiently, recognize that this is equivalent to finding the maximum matching or path in a specific graph structure. Actually, a more robust approach for medium difficulty with N up to 1000 is to realize that the problem is equivalent to finding the longest path in a directed graph where we can reuse nodes but not edges. This is still complex. Let's re-evaluate: The problem asks for the maximum number of codes in a sequence. This is the longest trail problem. For a general directed graph, the longest trail is NP-hard. However, if the graph is a DAG, it's polynomial. But the graph of 26 nodes can have cycles. Wait, the problem is likely intended to be solved using DP on the graph nodes if the number of codes is small, or perhaps it's a trick question where the answer is related to the Eulerian path properties? No, it's 'maximum number of codes'. Let's assume N is small enough for bitmask DP (N <= 20) or the problem implies a specific structure. Given 'medium' difficulty, it's likely N is small (e.g., <= 15-20) allowing for O(2^N * N) DP, or it's a flow problem. Let's assume the standard interpretation for such 'string chain' problems with small N: Bitmask DP. State: dp[mask][last_char] = max length of sequence using codes in 'mask' ending with 'last_char'. Transition: try adding a new code that starts with 'last_char' and is not in 'mask'.

Interview Questions on This Problem

Q1At a fintech platform, we need to route a series of micro-transactions where each transaction has a 'from' and 'to' account. How would you model the problem of finding the longest chain of transactions that can be executed sequentially without repeating a transaction, given that the number of unique accounts is small (e.g., 20) but the number of transactions is large?

Model this as a longest trail problem in a directed multigraph. Since the number of unique accounts (nodes) is small, you can use a DP approach where the state is defined by the set of used transactions (if N is small) or, more efficiently, if the graph structure allows, use flow-based heuristics. However, for exact solutions with small N, use bitmask DP: dp[mask][node] represents the maximum length of a trail using transactions in 'mask' ending at 'node'. The transition involves checking all transactions starting at 'node' that are not in 'mask'.

Q2In a high-growth startup, we are building a recommendation engine that suggests a sequence of videos. Each video has a 'genre_start' and 'genre_end'. We want to maximize the number of videos in a playlist such that the 'genre_end' of one video matches the 'genre_start' of the next. How would you optimize this for a large catalog?

This is a longest path problem in a directed graph where nodes are genres. If the number of genres is small (e.g., < 20), use bitmask DP. If the number of videos is large but genres are few, you can aggregate videos by (start, end) pairs and then solve a maximum flow or longest path problem on the aggregated graph, noting that each 'edge' type can be used multiple times if there are multiple videos of that type, but the problem states 'each code may appear at most once', so it's a trail. For large N, this is NP-hard, so you might need to approximate or restrict the problem to a DAG.

Q3At a global product company, we are designing a network of data centers. Each data center connection has a 'source' and 'destination' label. We want to find the longest sequence of connections that can be traversed without reusing a connection. How would you handle the case where the number of connections is up to 1000?

For N=1000, bitmask DP is infeasible. This problem is NP-hard in general. You would need to use heuristic approaches like greedy algorithms or local search, or recognize that if the graph is a DAG, you can use topological sorting and DP. If cycles are allowed, you might need to use integer linear programming or approximation algorithms. In an interview, clarify the constraints: if N is small, use DP; if N is large, discuss the NP-hardness and propose heuristic solutions.

Examples

Example 1

Input

["alpha","arc","coda","apple","eagle"]

Output

5

Explanation: "alpha" ends with 'a' → "arc" starts with 'a'. "arc" ends with 'c' → "coda" starts with 'c'. "coda" ends with 'a' → "apple" starts with 'a'. "apple" ends with 'e' → "eagle" starts with 'e'. All five codes satisfy the adjacency rule, so the longest sequence length is 5.

Example 2

Input

["star","rocket","titan","nebula","alpha"]

Output

5

Explanation: "star" ends with 'r' → "rocket" starts with 'r'. "rocket" ends with 't' → "titan" starts with 't'. "titan" ends with 'n' → "nebula" starts with 'n'. "nebula" ends with 'a' → "alpha" starts with 'a'. The five codes form a valid chain, giving a maximum length of 5.

Example 3

Input

["dog","cat","mouse","elephant"]

Output

1

Explanation: No two codes share the required start‑end character relationship. The best we can do is select any single code, so the longest possible sequence contains only one element.

Constraints

  • 1 <= codes.length <= 100000
  • 1 <= codes[i].length <= 20
  • codes[i] consists only of lowercase English letters

Optimal Approach & Strategy

Use dynamic programming with a bitmask to represent the set of used codes. The state is dp[mask][last_char], which stores the maximum length of a sequence using the codes in 'mask' and ending with 'last_char'. Transition by trying to add a new code that starts with 'last_char' and is not in 'mask'. This reduces the time complexity to O(2^N * N * 26), which is feasible for N <= 20.

Brute Force Approach

Generate all permutations of the codes and check each permutation to see if it forms a valid sequence. Keep track of the maximum length of a valid sequence. This approach has a time complexity of O(N! * N), which is infeasible for large N.

Verified Code Solutions

JavaScript Solution
Time: O(2^N * N * 26)
function maxTransmissionChain(codes){
    const n=codes.length;
    if(n===0) return 0;
    const first=codes.map(s=>s[0]);
    const last=codes.map(s=>s[s.length-1]);
    const N=1<<n;
    const dp=Array.from({length:N},()=>Array(n).fill(-1));
    for(let i=0;i<n;++i) dp[1<<i][i]=1;
    let ans=1;
    for(let mask=0; mask<N; ++mask){
        for(let lastIdx=0; lastIdx<n; ++lastIdx){
            const cur=dp[mask][lastIdx];
            if(cur===-1) continue;
            if(cur>ans) ans=cur;
            for(let nxt=0; nxt<n; ++nxt){
                if(mask & (1<<nxt)) continue;
                if(last[lastIdx]===first[nxt]){
                    const nmask=mask | (1<<nxt);
                    dp[nmask][nxt]=Math.max(dp[nmask][nxt], cur+1);
                }
            }
        }
    }
    return ans;
}
const fs=require('fs');
const input=fs.readFileSync(0,'utf8').trim().split(/\s+/);
if(input.length===0) process.exit(0);
console.log(maxTransmissionChain(input));

Asked in Top Tech Interviews

PaytmSalesforce

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.