count distinct slices in an array
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Counting distinct slices means finding how many contiguous subarrays contain only unique values. A brute-force solution checks all slices but becomes too slow for large arrays.
The standard approach uses a sliding window with a set or frequency map to expand and shrink while maintaining uniqueness. This reduces runtime to linear complexity for typical constraints.
Clear boundary handling is essential because off-by-one mistakes are common in window algorithms.
Core Sections
Define success and failure conditions
Ambiguous requirements create fragile implementations. Start by writing what success looks like and what should happen on failure. For transfer commands, define expected destination layout. For algorithms, define complexity and edge-case behavior. For dependency errors, define supported version matrix and fallback handling.
One representative input and expected output pair should exist before coding. This baseline keeps changes measurable and reviewable.
Build a minimal baseline implementation
Use the smallest code path that demonstrates correct behavior. Keep side effects explicit and avoid hidden assumptions tied to local machine configuration.
If production needs extra features, layer them after baseline validation rather than mixing all concerns at once.
Validate the critical path end to end
Run one short smoke check that exercises the full path through your implementation.
Then add one targeted negative-path test for the highest-risk operational failure. This practice shortens incident diagnosis time.
Operational hardening checklist
Before rollout, capture the exact commands used for verification and the expected output signatures. Keep rollback instructions near the implementation so responders can recover quickly under pressure.
Add concise logging around decisions and boundary changes. Logs should include enough context for diagnosis but avoid noisy repetition.
Document assumptions explicitly, including supported platform behavior, runtime versions, and performance bounds. Explicit assumptions reduce future maintenance risk and prevent hidden drift.
Regression strategy
Every bug fix should add at least one regression test that failed before the fix. This turns one-time debugging effort into durable reliability and lowers the chance of repeated failures in future refactors.
Deployment verification and rollback
Treat this implementation as an operational workflow, not only a code snippet. Before release, run a scripted verification that confirms expected output in local and CI environments using the same command shape. Differences between environments often reveal hidden assumptions about path layout, credentials, package versions, or data distribution.
Write rollback instructions alongside the implementation. A rollback should include exact command steps, expected recovery signal, and scope of impact. During incidents, clear rollback guidance shortens downtime and reduces risky improvisation.
Capture one known failure signature in tests or logs. Recognizable signatures help responders map symptoms to likely root causes quickly and avoid repetitive exploratory debugging.
Common Pitfalls
- Brute-force nested loops time out on large arrays.
- Forgetting to move left boundary past duplicates overcounts slices.
- Using set removal incorrectly can drop values still inside the window.
- Not applying required cap limits can violate problem constraints.
- Missing tests for repeated blocks hides edge-case errors.
Summary
- Use sliding-window logic to count distinct slices efficiently.
- Track window boundaries carefully to avoid off-by-one bugs.
- Choose set or last-seen index map based on clarity needs.
- Apply problem-specific caps during accumulation.
- Validate with arrays containing clustered duplicates.
Related reading
- Count number of 1's in binary representation
- Count number of points inside a circle fast
- Count number of subsets with sum equal to k
- Count number of times each bit is set in a range of integers
- Count Number of Triples in an array that are collinear
- Count of co-prime pairs from two arrays in less than On2 complexity
- Count points in a rectangle
- Count points inside triangle fast

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.