Longest Browsing Session Touching at Most K Distinct Domains

Last updated: November 29, 2026

Quick Overview

Given a sequence of domain visits as a string of characters (one character per domain) and an integer k, return the length of the longest contiguous stretch containing at most k distinct domains.

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

0

0

0 solved


Given a sequence of domain visits as a string of characters (one character per domain) and an integer k, return the length of the longest contiguous stretch containing at most k distinct domains.

Framed around session analysis in Chrome history, this is a canonical Google sliding-window question. The interviewer checks that you maintain the window invariant with a count map, shrink correctly, and can explain why each element enters and leaves the window once.

What the Interviewer Expects
  • Uses a variable-size sliding window with a frequency map
  • Shrinks from the left until the invariant holds again
  • Deletes keys whose count drops to zero so len(map) is the distinct count
  • Argues O(n) total time
  • Handles k = 0 and empty input
Key Topics to Cover
Sliding Window
Hash Map
Two Pointers
Strings
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
  • The input is a stream and you cannot store it; can you still answer?
  • Return the longest stretch with exactly k distinct domains.
  • What if each visit has a duration and you want the maximum total duration instead of length?
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: string s (each character is a domain id), integer k at least 0.
  • Output: maximum length of a substring with at most k distinct characters.
  • Target O(n) time....
High-Level Design

Expand the right pointer one step at a time, adding s[right] to a counter. While the counter has more than k keys, move the left pointer forward, decrementing counts and deleting keys that reach zer...


Submit Your Answer
Markdown supported