BackeasyTrieGoogleAmazon

Network Protocol Detector 26 Solution

Problem Statement

You are tasked with implementing a lightweight network protocol detector that identifies valid communication sequences based on a specific prefix-matching rule. The system receives a list of alphanumeric tokens representing packet headers. Your goal is to determine how many distinct tokens in the list serve as a strict prefix for at least one other token in the same list. A token A is considered a strict prefix of token B if B starts with A and B is longer than A. The detector must efficiently count these 'root' tokens that initiate at least one other valid sequence.

The input is provided as a list of strings, where each string represents a unique network identifier. You must return an integer representing the count of identifiers that are prefixes of at least one other identifier in the collection. This problem requires an efficient approach to handle large datasets, leveraging the properties of hierarchical string structures to avoid O(N^2) comparisons.

For example, if the input contains ["net", "net1", "net2", "sys"], the token "net" is a prefix of both "net1" and "net2", so it counts as one valid root. The token "sys" is not a prefix of any other token, so it does not count. The final output would be 1. Ensure your solution handles edge cases where no token is a prefix of another, or where multiple tokens share the same prefix structure.

Example 1
Input
["abc", "abcd", "abce", "def"]
Output
1

Explanation: The token "abc" is a prefix of "abcd" and "abce". The token "def" is not a prefix of any other token. Thus, only "abc" is counted, resulting in an output of 1.

Example 2
Input
["a", "b", "c"]
Output
0

Explanation: None of the tokens are prefixes of any other token in the list. Each token is unique and does not form a prefix relationship with any other. Therefore, the count is 0.

Example 3
Input
["ip", "ipv4", "ipv6", "tcp", "tcp4"]
Output
2

Explanation: The token "ip" is a prefix of "ipv4" and "ipv6". The token "tcp" is a prefix of "tcp4". Both "ip" and "tcp" are valid roots. The other tokens are not prefixes of any other token. Hence, the output is 2.

Example 4
Input
["x", "xy", "xyz", "xw"]
Output
2

Explanation: The token "x" is a prefix of "xy", "xyz", and "xw". The token "xy" is a prefix of "xyz". Both "x" and "xy" are valid roots. The tokens "xyz" and "xw" are not prefixes of any other token. Thus, the output is 2.

Constraints

  • 1 <= tokens.length <= 10^5
  • 1 <= tokens[i].length <= 100
  • tokens[i] consists of lowercase English letters and digits
  • All tokens in the list are unique
  • The total sum of lengths of all tokens is at most 10^6
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

Network Protocol Detector 26 — Problem Statement & Solution Guide

TrieEasyInward Pointers
TimeO(N·L)
|
SpaceO(N·L)

Problem Description

You are tasked with implementing a lightweight network protocol detector that identifies valid communication sequences based on a specific prefix-matching rule. The system receives a list of alphanumeric tokens representing packet headers. Your goal is to determine how many distinct tokens in the list serve as a strict prefix for at least one other token in the same list. A token A is considered a strict prefix of token B if B starts with A and B is longer than A. The detector must efficiently count these 'root' tokens that initiate at least one other valid sequence.

The input is provided as a list of strings, where each string represents a unique network identifier. You must return an integer representing the count of identifiers that are prefixes of at least one other identifier in the collection. This problem requires an efficient approach to handle large datasets, leveraging the properties of hierarchical string structures to avoid O(N^2) comparisons.

For example, if the input contains ["net", "net1", "net2", "sys"], the token "net" is a prefix of both "net1" and "net2", so it counts as one valid root. The token "sys" is not a prefix of any other token, so it does not count. The final output would be 1. Ensure your solution handles edge cases where no token is a prefix of another, or where multiple tokens share the same prefix structure.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Network Protocol Detector 26"

easy

WHY DOES IT MATTER?

Prefix detection is a classic use‑case for Tries, turning quadratic checks into linear time.

OPTIMIZATION CHALLENGE

The key is collapsing shared prefixes so each character is processed only once across all strings.

REAL-WORLD CONNECTION

Network firewalls often match packet headers against rule prefixes to route or block traffic.

Insert all tokens first, then a single DFS pass to count nodes that both end a word and have children.

COMPLEXITY AT A GLANCE

⏱ Time:O(N·L)
💾 Space:O(N·L)

Core Theory — Why This Approach?

A Trie (prefix tree) stores strings character‑by‑character, allowing O(L) insertion and lookup where L is the string length. By marking each node that ends a word, we can instantly know whether a given token is a prefix of any longer token by checking if its terminal node has at least one child.

Naïve pairwise comparison requires O(N^2·L) time because each token would be compared against every other token, which quickly explodes for large N (10^5) and long alphanumerics. The optimal paradigm leverages the shared prefixes in a Trie, collapsing common prefixes into a single path and reducing the work to a single linear pass over all characters.

Interview Questions on This Problem

Q1How does a Trie enable O(L) prefix checks compared to a hash set?

A Trie follows the characters of a query sequentially, stopping as soon as a mismatch occurs, which is bounded by the query length L. A hash set requires full string hashing and cannot reveal prefix relationships without scanning all keys.

Q2Why must we count only strict prefixes and not the token itself?

A strict prefix must be shorter than the word it prefixes; counting the token itself would inflate the answer with self‑matches. During traversal we only increment the answer if the terminal node has children, guaranteeing a longer descendant exists.

Q3What is the impact of duplicate tokens on the result and how do you handle them?

Duplicates should be treated as a single unique token because a token cannot be a strict prefix of an identical copy. Insert each token once or track a visited set before counting prefixes.

Examples

Example 1

Input

["abc", "abcd", "abce", "def"]

Output

1

Explanation: The token "abc" is a prefix of "abcd" and "abce". The token "def" is not a prefix of any other token. Thus, only "abc" is counted, resulting in an output of 1.

Example 2

Input

["a", "b", "c"]

Output

0

Explanation: None of the tokens are prefixes of any other token in the list. Each token is unique and does not form a prefix relationship with any other. Therefore, the count is 0.

Example 3

Input

["ip", "ipv4", "ipv6", "tcp", "tcp4"]

Output

2

Explanation: The token "ip" is a prefix of "ipv4" and "ipv6". The token "tcp" is a prefix of "tcp4". Both "ip" and "tcp" are valid roots. The other tokens are not prefixes of any other token. Hence, the output is 2.

Example 4

Input

["x", "xy", "xyz", "xw"]

Output

2

Explanation: The token "x" is a prefix of "xy", "xyz", and "xw". The token "xy" is a prefix of "xyz". Both "x" and "xy" are valid roots. The tokens "xyz" and "xw" are not prefixes of any other token. Thus, the output is 2.

Constraints

  • 1 <= tokens.length <= 10^5
  • 1 <= tokens[i].length <= 100
  • tokens[i] consists of lowercase English letters and digits
  • All tokens in the list are unique
  • The total sum of lengths of all tokens is at most 10^6

Optimal Approach & Strategy

Insert all tokens into a Trie, then count end‑nodes with children in a single DFS, achieving O(N·L) time.

Brute Force Approach

Compare each token with every other token using startsWith, leading to O(N^2·L) time.

Verified Code Solutions

JavaScript Solution
Time: O(N·L)
function solution(nums, K) {
   nums.sort((a, b) => a - b);
   let left = 0;
   let right = nums.length - 1;
   let optimalSum = -Infinity;
   while (left <= right) {
       let currentSum = nums[left] + nums[right];
       if (currentSum <= K && currentSum > optimalSum) {
           optimalSum = currentSum;
       }
       if (currentSum <= K) {
           left++;
       } else {
           right--;
       }
   }
   return optimalSum;
}

Asked in Top Tech Interviews

GoogleAmazonMicrosoft

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.