AlgoMaster Logo
AlgoMasterMatch Pub/Sub Topic Subscriptionsmedium

Match Pub/Sub Topic Subscriptions

medium

In topic-based publish/subscribe systems, publishers send messages to hierarchical topics and subscribers register patterns. The broker must decide which patterns match each published topic without requiring publishers to know who the subscribers are.

Topics and subscriptions contain non-empty levels separated by /. Subscriptions may use two wildcard levels:

  • + matches exactly one topic level.
  • # matches zero or more remaining topic levels and appears only as the final subscription level.

Design a TopicMatcher class:

  • TopicMatcher() creates a stateless matcher.
  • int[] matchingSubscriptions(String topic, String[] subscriptions) returns the indices of every matching subscription in ascending input order.

A literal subscription level must equal the complete topic level at the same position. When a subscription has no #, it must consume exactly the same number of levels as the topic. Preserve duplicate subscriptions as separate indices, and do not mutate the inputs.

Example 1:

Input:

Output:

Explanation: In home/+/temp, + consumes kitchen. In home/#, # consumes kitchen/temp. The three + levels in +/+/+ consume all three topic levels. The remaining literal subscription differs at the last level.

Example 2:

Input:

Output:

Explanation: The literal pattern and the + pattern both consume exactly two levels. a/# also matches because # accepts the remaining b level. The final subscription is longer than the topic.

Constraints

  • 1 <= topic.length <= 10^4
  • 0 <= subscriptions.length <= 10^4
  • 1 <= subscriptions[i].length <= 10^4
  • The combined length of all subscriptions in one call is at most 10^5.
  • Topic and subscription levels are non-empty and separated by /.
  • + and # occupy complete levels; # appears only as the last level.
  • At most 100 calls are made to matchingSubscriptions.
Hints

Loading...
CallReturns
new TopicMatcher()null
matchingSubscriptions("home/kitchen/temp", ["home/+/temp","home/#","home/kitchen/humidity","+/+/+"])[0,1,3]

The plus wildcard matches kitchen, the hash wildcard matches the remaining subtree, and the three plus wildcards consume all three levels.

Run checks these cases. Submit also runs a larger hidden set.