BackmediumStackAmazon

Warehouse Inventory Validation Solution

Problem Statement

Determine if a given warehouse inventory can be transformed into a desired inventory by removing items from the front of the inventory using a stack, where each item can only be removed once and the remaining items must be in the same order as they appear in the original inventory.

Example 1
Input
[1, 2, 3, 4, 5], [1, 2, 3, 4]
Output
false

Explanation: Step-by-step: Given the input inventory [1, 2, 3, 4, 5] and target [1, 2, 3, 4], we cannot remove items from the front of the inventory to match the target. The correct output is false.

Example 2
Input
[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]
Output
true

Explanation: Step-by-step: Given the input inventory [1, 2, 3, 4, 5] and target [5, 4, 3, 2, 1], we can remove items from the front of the inventory to match the target. We can remove 1, 2, 3, 4 from the front of the inventory to get [5, 4, 3, 2, 1]. The correct output is true.

Constraints

  • 1 <= inventory.length <= 1000
  • 1 <= target.length <= 1000
  • 0 <= inventory[i] <= 10000
  • 0 <= target[i] <= 10000
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Warehouse Inventory Validation — Problem Statement & Solution Guide

StackMediumMixed
TimeO(N)
|
SpaceO(N)

Problem Description

Determine if a given warehouse inventory can be transformed into a desired inventory by removing items from the front of the inventory using a stack, where each item can only be removed once and the remaining items must be in the same order as they appear in the original inventory.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Warehouse Inventory Validation"

medium

WHY DOES IT MATTER?

This pattern is essential because it models real-world systems where data is processed in a constrained order but can be temporarily buffered in a LIFO structure. It tests a candidate's ability to simulate stateful processes efficiently and recognize when a greedy approach is optimal. Understanding this pattern is crucial for solving problems involving queue simulation with stacks, valid parenthesis checking, and sequence validation in distributed systems.

OPTIMIZATION CHALLENGE

The key insight is that the stack operation is deterministic given the target sequence. You do not need to explore all possible push/pop combinations; instead, you can greedily pop from the stack when the top matches the target, and push from the source otherwise. This reduces the time complexity from exponential to linear, as each item is pushed and popped at most once.

REAL-WORLD CONNECTION

A practical analogy is a call center system where incoming calls are queued in a specific order but can be temporarily held in a priority buffer that behaves as a stack. Agents can only handle calls from the top of the buffer or directly from the queue. Validating if a specific sequence of calls can be handled by agents in a desired order is identical to this problem. Another analogy is a web server handling requests where some requests are processed immediately while others are buffered in a stack-like structure for later processing.

In an interview, clearly articulate the greedy choice: 'We must pop from the stack if the top matches the target, because delaying the pop would only block access to subsequent items that might be needed earlier in the target sequence.' This demonstrates a deep understanding of why the greedy approach is optimal and not just a heuristic.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(N)

Core Theory — Why This Approach?

The 'Warehouse Inventory Validation' problem is a classic application of the Stack data structure, specifically leveraging its Last-In-First-Out (LIFO) property to simulate a constrained removal process. The core theoretical challenge lies in verifying if a target sequence can be derived from a source sequence under specific operational constraints. Unlike simple permutation checks, this problem imposes an ordering constraint where items are removed from the front of the original inventory but processed through a stack, meaning the relative order of items that bypass the stack must remain identical to their original sequence. This transforms the problem into a validation of subsequence integrity combined with stack-based reordering capabilities.

Naive approaches, such as generating all possible permutations of the inventory and checking if the target exists among them, fail catastrophically on large inputs due to factorial time complexity O(N!). Even backtracking approaches that attempt to simulate every possible push/pop combination result in exponential time complexity, making them infeasible for inventories with more than 20-25 items. The optimal paradigm recognizes that the stack operation is deterministic given the target sequence: at any step, if the top of the stack matches the next required item in the target, we must pop it; otherwise, we must push the next available item from the source inventory. This greedy strategy ensures that we never make a suboptimal choice, as delaying a pop when the top matches the target would only block access to subsequent items that might be needed earlier in the target sequence.

The underlying algorithmic theory rests on the principle of monotonicity in stack operations relative to the target sequence. By maintaining a pointer to the current position in the target inventory and a pointer to the next available item in the source inventory, we can simulate the process in linear time. The key insight is that the stack acts as a temporary buffer that allows for local reordering, but it cannot reverse the global order of items that are not pushed onto the stack. Therefore, the validation reduces to checking if the target sequence can be constructed by interleaving items from the stack (in LIFO order) and items directly from the source (in FIFO order), ensuring that the direct items maintain their original relative order.

Interview Questions on This Problem

Q1At a fintech platform like Stripe, how would you validate if a sequence of transaction reversals can be processed given a constraint that reversals must be handled in a specific order but can be temporarily buffered in a queue-like structure that actually behaves as a stack due to legacy system limitations?

This is a direct application of the stack validation pattern. You would simulate the processing by iterating through the target reversal sequence. For each target reversal, check if it is at the top of the stack; if so, pop it. If not, push the next available transaction from the source sequence onto the stack until the target reversal is either found at the top or the source is exhausted. If the source is exhausted and the target reversal is not at the top, the sequence is invalid. This approach runs in O(N) time and O(N) space, ensuring efficient validation even for high-volume transaction logs.

Q2In a high-growth engineering startup building a real-time inventory management system, how would you ensure that a batch of item removals requested by a warehouse robot can be executed given that the robot can only access items from the front of the conveyor belt but can use a temporary holding area that behaves as a stack?

Model the conveyor belt as the source sequence and the holding area as a stack. The robot's requested removal order is the target sequence. Use a greedy simulation: for each item in the target sequence, if it is at the top of the stack, remove it. Otherwise, move items from the conveyor belt to the stack until the target item is at the top or the belt is empty. If the belt is empty and the target item is not at the top, the request is impossible. This ensures the robot's path is valid without needing to pre-compute all possible paths, which would be computationally infeasible for large inventories.

Q3At a global product company like Amazon, how would you validate if a sequence of package pickups from a sorting facility can be achieved given that packages are fed into a sorter in a specific order but can be temporarily held in a stack-like buffer before being dispatched in a desired order?

This is a stack permutation validation problem. The feeding order is the source sequence, and the desired dispatch order is the target sequence. Simulate the process by maintaining a stack for the buffer and a pointer to the next package to be dispatched. For each package in the dispatch order, if it is at the top of the stack, dispatch it. Otherwise, feed packages from the source into the stack until the desired package is at the top or the source is exhausted. If the source is exhausted and the desired package is not at the top, the dispatch order is invalid. This O(N) solution is critical for optimizing sorting facility throughput and ensuring that dispatch orders are feasible before they are committed to the system.

Examples

Example 1

Input

[1, 2, 3, 4, 5], [1, 2, 3, 4]

Output

false

Explanation: Step-by-step: Given the input inventory [1, 2, 3, 4, 5] and target [1, 2, 3, 4], we cannot remove items from the front of the inventory to match the target. The correct output is false.

Example 2

Input

[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]

Output

true

Explanation: Step-by-step: Given the input inventory [1, 2, 3, 4, 5] and target [5, 4, 3, 2, 1], we can remove items from the front of the inventory to match the target. We can remove 1, 2, 3, 4 from the front of the inventory to get [5, 4, 3, 2, 1]. The correct output is true.

Constraints

  • 1 <= inventory.length <= 1000
  • 1 <= target.length <= 1000
  • 0 <= inventory[i] <= 10000
  • 0 <= target[i] <= 10000

Optimal Approach & Strategy

Simulate the process using a stack by greedily popping from the stack when the top matches the target and pushing from the source otherwise. This approach runs in O(N) time and O(N) space, as each item is processed exactly once.

Brute Force Approach

Generate all possible permutations of the original inventory and check if the desired inventory is among them. This approach has a time complexity of O(N!) and is infeasible for large inventories.

Verified Code Solutions

JavaScript Solution
Time: O(N)
/**
 * @param {number[]} inventory
 * @param {number[]} desired
 * @return {boolean}
 */
var validateInventory = function(inventory, desired) {
    const stack = [];
    let j = 0;
    for (let i = 0; i < inventory.length; i++) {
        stack.push(inventory[i]);
        while (stack.length > 0 && stack[stack.length - 1] === desired[j]) {
            stack.pop();
            j++;
            if (j === desired.length) return true;
        }
    }
    return j === desired.length;
};

// Example usage
const inventory = [1, 2, 3, 4, 5];
const desired = [1, 2, 3, 4];
console.log(validateInventory(inventory, desired));

Asked in Top Tech Interviews

Amazon

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.