Finding Consecutive Duplicates in Subarrays
Data Structure DesignModel answerLast 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
kvaries 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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Finding Consecutive Duplicates in Subarrays
Core Insight
A sequence of identical elements forms when arr[i] == arr[i-1]. We track sequence lengths by incrementing a counter during equality and resetting to 1 otherwise.
Part 1: Maximum Sequence Length
Scan left-to-right maintaining two values:
current: length of the sequence ending at this positionmaximum: best length seen so far
Code:
def longest_sequence(arr):
if not arr:
return 0
maximum = current = 1
for i in range(1, len(arr)):
current = current + 1 if arr[i] == arr[i-1] else 1
maximum = max(maximum, current)
return maximum
Complexity: O(n) time, O(1) space where n = array length.
Correctness: Every sequence ends somewhere. When it ends, current holds its full length, so tracking the maximum of current captures the answer.
Part 2: Threshold Detection
Same approach, but exit immediately when current reaches k:
def contains_sequence_of_length(arr, k):
if k <= 0:
return True
if k > len(arr):
return False
current = 1
for i in range(1, len(arr)):
current = current + 1 if arr[i] == arr[i-1] else 1
if current >= k:
return True
return False
Complexity: O(n) worst-case, but exits early when a qualifying sequence is found. O(1) space.
Part 3: Suffix Queries
Approach
Scan right-to-left during preprocessing. At each position j, compute:
forward[j]: length of the sequence starting atjextending rightwardsuffix_max[j]: longest sequence anywhere inarr[j:]
Recurrence:
forward[j] = forward[j+1] + 1 if arr[j] == arr[j+1]
= 1 otherwise
suffix_max[j] = max(forward[j], suffix_max[j+1])
Why this works: In the suffix starting at position j:
- The leftmost sequence may be truncated on its left edge. Its length within the suffix is exactly
forward[j]. - All other sequences start at positions where
arr[pos] != arr[pos-1], soforward[pos]captures their full length. - Therefore
max(forward[pos])for allpos >= jgives the correct answer, which is whatsuffix_max[j]computes.
Query: For starting index start, return suffix_max[start] >= k in O(1).
Complexity: O(n) preprocessing, O(n) space, O(1) per query.
Space Optimization for Fixed k
Instead of storing arrays, store a single integer last_valid:
- During the right-to-left scan, record the rightmost position where
forward[j] >= k - Query: return
start <= last_valid
This reduces space to O(1) while keeping O(1) queries.
Extensions
Variable k per Query
Store the full suffix_max array. Each query compares suffix_max[start] against the provided k.
Append-Only Array
Maintain last_valid as described above. When appending elements:
- Extend the sequence length from the previous last element
- If the new sequence length reaches
k, updatelast_validto include the new positions
Cost: O(1) per append, no rebuild needed.
Arbitrary Updates
Precomputed arrays become expensive to maintain (one update can cascade through the entire array). Use a segment tree instead:
Each node stores:
length: number of elements in this segmentleft_seq: sequence length touching the left boundaryright_seq: sequence length touching the right boundarymax_seq: longest sequence inside this segmentleft_val,right_val: first and last element values
Merging two children L and R:
left_seq = L.left_seq + R.left_seqif L is entirely one sequence (L.left_seq == L.length) andL.right_val == R.left_val; otherwiseleft_seq = L.left_seqright_seq: computed symmetricallymax_seq = max(L.max_seq, R.max_seq, L.right_seq + R.left_seq if L.right_val == R.left_val)
Complexity: O(n) build, O(log n) per update or query.
Arbitrary Range Queries
For queries on [left, right] (not just suffixes), also precompute backward[j] (sequence length ending at j) and build a sparse table for range-max queries over backward.
Query [left, right]:
- Let
end_left = left + forward[left] - 1 - If
end_left >= right, returnright - left + 1 - Otherwise return
max(forward[left], range_max_backward(end_left+1, right))
Complexity: O(n log n) preprocessing, O(1) per query, but no updates possible.
Trade-offs Summary
| Scenario | Structure | Query | Update | Space |
|---|---|---|---|---|
| Static, fixed k | Single index | O(1) | N/A | O(1) |
| Static, variable k | Precomputed arrays | O(1) | N/A | O(n) |
| Append-only | Incremental index | O(1) | O(1) | O(1) |
| Mutable | Segment tree | O(log n) | O(log n) | O(n) |
| General ranges, static | Sparse table | O(1) | N/A | O(n log n) |
Edge Cases
- Empty array: Maximum sequence length is 0
- Single element: Maximum sequence length is 1
- k > array length: Always returns false
- start == array length: Suffix is empty, return false (unless k <= 0)
- Out of bounds indices: Raise an error
- Floating point comparisons: Be aware that
NaN != NaN, so consecutive NaN values won't form a sequence under standard equality
Common Mistakes
- Forgetting that sequences at suffix boundaries may be cut off on the left
- Using forward scans for suffix queries (captures sequences that extend past the suffix boundary)
- Not considering that updating one element can affect multiple sequence computations
- Assuming O(1) updates are possible with precomputed arrays (they generally require O(n) repair)