BackmediumStringsInfosys

Galactic Transmission Decoding Solution

Problem Statement

You are tasked with processing a raw data stream received from a deep-space probe. The stream is represented as a string s containing alphanumeric characters and underscores. You are also provided with a mapping codeMap that translates specific alien identifiers into human-readable strings. Your goal is to decode the transmission by replacing every occurrence of a key in codeMap within s with its corresponding value. If a segment of the string does not match any key in the dictionary, it must remain unchanged. The replacement should be performed greedily from left to right, ensuring that the longest possible match is prioritized if multiple keys could match at the same position. Note that keys in codeMap are unique and consist only of uppercase letters and underscores.

Example 1
Input
s = "X1_Y2_Z3", codeMap = {"X1": "Alpha", "Y2": "Beta", "Z3": "Gamma"}
Output
"Alpha_Beta_Gamma"

Explanation: 1. Start at index 0. 'X1' matches key 'X1' in codeMap. Replace with 'Alpha'. 2. Move to index 2. '_' is not a key, keep it. 3. Move to index 3. 'Y2' matches key 'Y2'. Replace with 'Beta'. 4. Move to index 5. '_' is not a key, keep it. 5. Move to index 6. 'Z3' matches key 'Z3'. Replace with 'Gamma'. 6. Final string: 'Alpha_Beta_Gamma'.

Example 2
Input
s = "AB_C", codeMap = {"AB": "12", "A": "1"}
Output
"12_C"

Explanation: 1. Start at index 0. Check for longest match. 'AB' is a key. 'A' is also a key. Prioritize longest match 'AB'. 2. Replace 'AB' with '12'. 3. Move to index 2. '_' is not a key, keep it. 4. Move to index 3. 'C' is not a key, keep it. 5. Final string: '12_C'.

Example 3
Input
s = "UNKNOWN_CODE", codeMap = {"CODE": "DATA"}
Output
"UNKNOWN_DATA"

Explanation: 1. Start at index 0. 'UNKNOWN' does not match any key. Keep characters individually until a match is found or end of string. 2. At index 8, 'CODE' matches key 'CODE'. 3. Replace 'CODE' with 'DATA'. 4. Final string: 'UNKNOWN_DATA'.

Example 4
Input
s = "AAB", codeMap = {"AA": "X", "A": "Y"}
Output
"XB"

Explanation: 1. Start at index 0. 'AA' is a key. 'A' is a key. Prioritize 'AA'. 2. Replace 'AA' with 'X'. 3. Move to index 2. 'B' is not a key, keep it. 4. Final string: 'XB'.

Constraints

  • 1 <= s.length <= 10^5
  • 1 <= codeMap.size <= 10^4
  • 1 <= key.length <= 10
  • s consists of uppercase English letters, digits, and underscores.
  • Keys in codeMap consist of uppercase English letters and underscores.
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 Decoding — Problem Statement & Solution Guide

StringsMediumMixed
TimeO(N * M + K * L)
|
SpaceO(K * L)

Problem Description

You are tasked with processing a raw data stream received from a deep-space probe. The stream is represented as a string s containing alphanumeric characters and underscores. You are also provided with a mapping codeMap that translates specific alien identifiers into human-readable strings. Your goal is to decode the transmission by replacing every occurrence of a key in codeMap within s with its corresponding value. If a segment of the string does not match any key in the dictionary, it must remain unchanged. The replacement should be performed greedily from left to right, ensuring that the longest possible match is prioritized if multiple keys could match at the same position. Note that keys in codeMap are unique and consist only of uppercase letters and underscores.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Galactic Transmission Decoding"

medium

WHY DOES IT MATTER?

This pattern is essential for parsing protocols, log analysis, and natural language processing where tokens must be identified and transformed. It tests the ability to move from brute-force substring checks to efficient state-machine or tree-based matching.

OPTIMIZATION CHALLENGE

The key insight is to avoid checking all possible substrings. Instead, use a Trie (prefix tree) to traverse the string character by character. If a path in the Trie ends at a terminal node, a match is found. This reduces the search space from exponential to linear relative to the string length and key depth.

REAL-WORLD CONNECTION

This is analogous to how web browsers parse HTML or how network routers parse packet headers. Just as a router must identify the protocol type (TCP, UDP) from the first few bytes to route the packet, the decoder must identify the alien identifier to apply the correct translation rule.

During the interview, explicitly mention the 'longest match' ambiguity. If the problem doesn't specify, assume longest match is preferred. Show that you can implement a Trie to handle this efficiently, demonstrating knowledge of advanced string data structures.

COMPLEXITY AT A GLANCE

⏱ Time:O(N * M + K * L)
💾 Space:O(K * L)

Core Theory — Why This Approach?

The problem of decoding a string by replacing specific substrings based on a mapping is fundamentally a pattern matching and string reconstruction challenge. A naive approach would involve iterating through every possible substring of the input string s and checking if it exists in codeMap. This results in a time complexity of O(N^2 * K), where N is the length of the string and K is the average length of keys, which is computationally expensive for large data streams. The inefficiency stems from redundant comparisons and the lack of a structured way to identify valid tokens in the stream.

Interview Questions on This Problem

Q1How would you handle overlapping keys in the codeMap, such as 'ab' and 'abc', when decoding a string like 'abc'?

You must define a priority rule, typically longest-match-first. Use a Trie or sort keys by length in descending order to ensure that 'abc' is matched before 'ab'. This prevents partial decoding that leads to incorrect results.

Q2In a distributed system, if the codeMap is updated dynamically, how would you ensure consistency in decoding without stopping the stream?

Implement a versioned mapping system where each transmission includes a map version ID. The decoder uses the specific version of the map associated with that version ID. This ensures that historical data is decoded with the correct rules, while new data uses the updated map.

Q3What is the trade-off between using a Hash Map vs. a Trie for this decoding problem?

A Hash Map offers O(1) average lookup but requires generating all substrings to check for matches, leading to O(N^2) complexity. A Trie allows for linear-time scanning O(N * M) where M is the max key length, as it matches characters sequentially, making it superior for large strings with many potential matches.

Examples

Example 1

Input

s = "X1_Y2_Z3", codeMap = {"X1": "Alpha", "Y2": "Beta", "Z3": "Gamma"}

Output

"Alpha_Beta_Gamma"

Explanation: 1. Start at index 0. 'X1' matches key 'X1' in codeMap. Replace with 'Alpha'. 2. Move to index 2. '_' is not a key, keep it. 3. Move to index 3. 'Y2' matches key 'Y2'. Replace with 'Beta'. 4. Move to index 5. '_' is not a key, keep it. 5. Move to index 6. 'Z3' matches key 'Z3'. Replace with 'Gamma'. 6. Final string: 'Alpha_Beta_Gamma'.

Example 2

Input

s = "AB_C", codeMap = {"AB": "12", "A": "1"}

Output

"12_C"

Explanation: 1. Start at index 0. Check for longest match. 'AB' is a key. 'A' is also a key. Prioritize longest match 'AB'. 2. Replace 'AB' with '12'. 3. Move to index 2. '_' is not a key, keep it. 4. Move to index 3. 'C' is not a key, keep it. 5. Final string: '12_C'.

Example 3

Input

s = "UNKNOWN_CODE", codeMap = {"CODE": "DATA"}

Output

"UNKNOWN_DATA"

Explanation: 1. Start at index 0. 'UNKNOWN' does not match any key. Keep characters individually until a match is found or end of string. 2. At index 8, 'CODE' matches key 'CODE'. 3. Replace 'CODE' with 'DATA'. 4. Final string: 'UNKNOWN_DATA'.

Example 4

Input

s = "AAB", codeMap = {"AA": "X", "A": "Y"}

Output

"XB"

Explanation: 1. Start at index 0. 'AA' is a key. 'A' is a key. Prioritize 'AA'. 2. Replace 'AA' with 'X'. 3. Move to index 2. 'B' is not a key, keep it. 4. Final string: 'XB'.

Constraints

  • 1 <= s.length <= 10^5
  • 1 <= codeMap.size <= 10^4
  • 1 <= key.length <= 10
  • s consists of uppercase English letters, digits, and underscores.
  • Keys in codeMap consist of uppercase English letters and underscores.

Optimal Approach & Strategy

Construct a Trie from the keys in codeMap and traverse the input string s character by character, matching against the Trie nodes. When a terminal node is reached, replace the matched substring with the corresponding value and reset the traversal, achieving O(N * M) time complexity.

Brute Force Approach

Iterate through every starting index of the string and check all possible substrings against the keys in codeMap using a hash map. This leads to O(N^2 * K) time complexity due to redundant substring generation and comparison.

Verified Code Solutions

JavaScript Solution
Time: O(N * M + K * L)
/**
 * Decodes a galactic transmission string by replacing keys from codeMap.
 * 
 * @param {string} s - The raw transmission string.
 * @param {Object} codeMap - A map of alien identifiers to human-readable strings.
 * @return {string} The decoded string.
 */
function decodeTransmission(s, codeMap) {
    if (!s || Object.keys(codeMap).length === 0) {
        return s;
    }

    // Find the maximum key length to limit substring checks
    let maxKeyLen = 0;
    for (const key in codeMap) {
        if (key.length > maxKeyLen) {
            maxKeyLen = key.length;
        }
    }

    let result = "";
    let i = 0;

    while (i < s.length) {
        let matched = false;
        // Check for matches starting at position i, from longest to shortest key
        for (let len = Math.min(maxKeyLen, s.length - i); len >= 1; --len) {
            const key = s.substring(i, i + len);
            if (codeMap.hasOwnProperty(key)) {
                result += codeMap[key];
                i += len;
                matched = true;
                break;
            }
        }
        if (!matched) {
            result += s[i];
            i++;
        }
    }

    return result;
}

// Example usage
const s = "X1_Y2_Z3";
const codeMap = { "X1": "Alpha", "Y2": "Beta", "Z3": "Gamma" };
console.log(decodeTransmission(s, codeMap));

Asked in Top Tech Interviews

Infosys

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.