Longest Window With Equal Purchases and Returns in an Order Log

Last updated: November 29, 2026

Quick Overview

Given a sequence of order events where 1 means a purchase and 0 means a return, find the length of the longest contiguous window containing the same number of purchases and returns.

Amazon
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Given a sequence of order events where 1 means a purchase and 0 means a return, find the length of the longest contiguous window containing the same number of purchases and returns.

Asked in Amazon technical screens in the context of retail analytics on order logs. The interviewer is looking for the prefix-sum plus first-occurrence hash map trick, and for whether you see why a plain sliding window does not work here.

What the Interviewer Expects
  • Map returns to -1 so a balanced window has sum zero
  • Use a hash map from prefix sum to its first index
  • Seed the map with prefix 0 at index -1
  • Explain why a two-pointer window fails (sums are not monotonic)
  • Analyze O(n) time and O(n) space
Key Topics to Cover
Prefix Sums
Hash Map
Arrays
First Occurrence
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Return the start and end indices of the window, not just its length.
  • How would you count all balanced windows instead of finding the longest?
  • Generalize to three event types (purchase, return, exchange) all equal in count.
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input is a list of 0s and 1s, length up to 1e5. Output the maximum length of a contiguous subarray with equal counts of 0 and 1, or 0 if none exists....

High-Level Design

Treat a purchase as +1 and a return as -1. A window (i, j] is balanced exactly when prefix[j] == prefix[i]. To make the window as long as possible, remember only the first index where each pre...


Submit Your Answer
Markdown supported