Add Peek Support to a Paged Product Catalog Iterator

Last updated: November 29, 2026

Quick Overview

You are given an iterator over catalog items that only supports next() and has_next(). Wrap it in a class that also supports peek(), returning the next item without consuming it.

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

0

0

0 solved


You are given an iterator over catalog items that only supports next() and has_next(). Wrap it in a class that also supports peek(), returning the next item without consuming it.

Catalog ingestion code at Amazon often needs one-item lookahead, for example to group consecutive items by seller. The interviewer checks that you cache exactly one element and keep has_next consistent with the cache.

What the Interviewer Expects
  • Cache one lookahead item and a flag for whether it is filled
  • peek fills the cache if empty and returns it
  • next returns the cached item if present, otherwise delegates
  • has_next is true if the cache is filled or the source has more
  • All operations O(1)
Key Topics to Cover
iterators
lookahead
wrapper design
API contracts
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
  • How would you support peeking k items ahead?
  • How would you make it generic over any iterable in Python?
  • How would you handle a source iterator whose has_next is expensive (a network call)?
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: an object with next() and has_next(). Output: a wrapper exposing peek(), next(), has_next(). Items can be any value including None, so the cache must use a separate flag instead of ch...

High-Level Design

Keep self._has_peeked and self._peeked. peek() pulls from the source into the cache when it is empty. next() drains the cache first. has_next() returns True if the cache is filled or the sou...


Submit Your Answer
Markdown supported