Validate Lens Order Sequence
At Lenskart, efficient order fulfillment is crucial for customer satisfaction. Every lens added or removed from an order needs to follow a strict Last-In, First-Out (LIFO) protocol to maintain inventory accuracy and streamline packaging. This problem simulates a sequence of lens handling operations and requires you to validate if the sequence adheres to LIFO principles.
You are given an array of integers, operations, representing a sequence of actions on a virtual stack of lenses. Your task is to implement a function that determines if this sequence of operations is valid according to LIFO rules.
Specifically:
operations[i] is a positive integer X (e.g., +5), it means lens X is added to the top of the stack.operations[i] is a negative integer -X (e.g., -5), it means lens X is removed from the top of the stack. For this operation to be valid, the stack must not be empty, and the lens currently at the top of the stack must be X. If either condition is not met, the entire sequence is invalid.Return true if the entire sequence of operations is valid, and false otherwise.
operations: number[] - An array of integers representing the sequence of lens handling actions.
+X (positive integer) indicates adding lens X.-X (negative integer) indicates removing lens X.boolean - true if the sequence is valid according to the rules, false otherwise.operations array: If the input array operations is empty, the sequence is trivially valid.operations[i] will never be 0.X is added multiple times (e.g., [1, 1]), both additions are valid, and X simply occupies a new position on the stack.-X occurs when the stack is empty, or the top element is not X, the sequence is immediately invalid.Examples
Example 1
Input:
operations = [1, 2, -2, -1]
Output:
true
Note:
Push 1, Push 2, Pop 2 (match), Pop 1 (match). All operations valid.
Example 2
Input:
operations = [1, 2, -1, -2]
Output:
false
Note:
Push 1, Push 2. Then try to Pop 1, but 2 is on top. Invalid operation.
Example 3
Input:
operations = [5, -5, 10]
Output:
true
Note:
Push 5, Pop 5 (match), Push 10. All operations valid.
Example 4
Input:
operations = [-3]
Output:
false
Note:
Attempt to pop -3 from an empty stack. Invalid operation.
Constraints
1 <= operations.length <= 10^4-10^5 <= operations[i] <= 10^5operations[i] != 0Loading editor...