BackmediumStack Zomato

Validating Crate Stacking Sequences Solution

Problem Statement

Write a function to determine if a given sequence of crate stack operations is valid. A sequence of crate stack operations is valid if every crate added can be matched with a corresponding crate removal, and at no point is a crate removed from an empty stack or a crate added on top of another crate of the same type. The function should return true for valid sequences and false for invalid sequences.

Example 1
Input
['add_A', 'add_B', 'remove_A', 'add_C', 'remove_B', 'remove_C', 'remove_A']
Output
false

Explanation: Step-by-step: 1. 'add_A' adds A to the stack, count[A] = 1. 2. 'add_B' adds B to the stack, count[B] = 1. 3. 'remove_A' tries to remove A, but count[A] = 1, so it's valid. 4. 'add_C' adds C to the stack, count[C] = 1. 5. 'remove_B' tries to remove B, but count[B] = 1, so it's valid. 6. 'remove_C' tries to remove C, but count[C] = 1, so it's valid. 7. 'remove_A' tries to remove A, but count[A] = 1, so it's valid. However, the final stack should be empty, but it's not, so the sequence is invalid.

Example 2
Input
['add_A', 'add_A', 'remove_A', 'add_B', 'remove_B', 'remove_A']
Output
false

Explanation: Step-by-step: 1. 'add_A' adds A to the stack, count[A] = 1. 2. 'add_A' tries to add A again, but the top of the stack is already A, so it's invalid. 3. 'remove_A' tries to remove A, but count[A] = 1, so it's valid. 4. 'add_B' adds B to the stack, count[B] = 1. 5. 'remove_B' tries to remove B, but count[B] = 1, so it's valid. 6. 'remove_A' tries to remove A, but count[A] = 1, so it's valid. However, the final stack should be empty, but it's not, so the sequence is invalid.

Constraints

  • 1 <= sequence length <= 100
  • Each operation in the sequence is either 'add_X' or 'remove_X', where X is a crate type (A, B, C, etc.)
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free