mediumStackPattern: Stack
Constrained Message Ordering Solution
Problem Statement
Given a stack of capacity `n` and a list of messages with their corresponding node identifiers, rearrange the messages to be sent while respecting the stack capacity constraint.
Examples
Example 1:
Input:[['A', 1], ['B', 3], ['C', 5], ['D', 7]]
Output:[]
Explanation: The messages are reordered to maintain the order of node identifiers for capacity 4
Example 2:
Input:[['F', 7], ['G', 3], ['H', 5]]
Output:[]
Explanation: The messages are reordered with capacity 3 to respect the stack constraint
Constraints
- The stack capacity is given as a separate input
- Messages are represented as arrays containing the message label and its corresponding node identifier
- The stack can hold up to `n` elements before it overflows
Time: O(n log n) Space: O(n)
Reserve space for the messages in the result array, and enqueue them based on their order while maintaining a stack to track available capacity
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
def constrain_message_ordering(messages, capacity) -> list[tuple[str, int]]: messages.sort(key=lambda x: x[1], reverse=True) result = [] available_capacity = capacity for message, node_identifier in messages: if available_capacity > 0: result.append((message, node_identifier)) available_capacity -= 1 return result