KatInterview

Finding Consecutive Duplicates in Subarrays

Data Structure DesignModel answer
MediumModel answerData Structure Designarray-scanningpreprocessingrange-queries

Last updated

Design data structures to efficiently detect sequences of identical elements in an array and answer queries about their presence in suffixes.

You're given an array arr of comparable elements with indices 0 through len-1, and a threshold value k.

Part 1: Implement a function that computes the longest sequence of identical adjacent elements anywhere in arr.

Part 2: Implement a function that returns whether arr contains any sequence of at least k identical adjacent elements. Analyze time and space complexity.

Part 3: Design a system to handle repeated queries of this form: given a starting index start, does the subarray from start to the end contain a sequence of at least k identical adjacent elements? Discuss your preprocessing strategy, choice of data structures (such as precomputed arrays, segment trees, or sparse tables), and the complexity trade-offs for queries and updates.

Explain correctness, handle edge cases, and discuss how your design changes if:

  • The threshold k varies per query
  • The array supports insertions at the end
  • The array supports arbitrary element updates
  • Queries ask about arbitrary ranges [left, right] instead of just suffixes

Hints

Hint 1

Track the length of identical elements ending at each position as you scan

Hint 2

For suffix queries, consider scanning backwards and storing what you find at each position

Hint 3

Think about what happens when you need to merge information from two adjacent segments