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.
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.
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.
Master coding challenges related to Stack and solve the [Backup] Validating Crate Stacking Sequences problem optimally.
No dry run loaded.
🚀 Practice this problem
Run code, get AI hints & track streak