Longest Browsing Session With At Most K Distinct Categories

Last updated: November 29, 2026

Quick Overview

Given a user's clickstream as a list of category IDs in time order, return the length of the longest contiguous stretch that touches at most K distinct categories.

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

0

0

0 solved


Given a user's clickstream as a list of category IDs in time order, return the length of the longest contiguous stretch that touches at most K distinct categories.

Shows up in Flipkart's DSA screening round, framed around personalization: the recommendations team wants the longest focused browsing streak per session. The interviewer checks a correct variable size sliding window with a frequency map and clean shrink logic.

What the Interviewer Expects
  • Recognize the variable size sliding window pattern
  • Maintain category counts inside the window and shrink when distinct count exceeds K
  • Explain why each index enters and leaves the window at most once
  • Handle K = 0 and an empty stream
  • State O(n) time and O(K) space
Key Topics to Cover
sliding window
frequency map
two pointers
clickstream
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 also return the start and end timestamps of the best window?
  • What changes if events arrive as an unbounded stream and you must answer at any time?
  • How would you find the shortest window that covers all K given categories?
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: list of category IDs (strings or ints) for one session, and integer K.
  • Output: max length of a contiguous subarray with at most K distinct values.
  • Sessions can be long (thousands of e...
High-Level Design

Keep a window [left, right] and a map from category to its count inside the window. Extend right one step at a time. Whenever the map has more than K keys, advance left, decrementing counts an...


Submit Your Answer
Markdown supported