---
id: 537
lang: en
translation_of: index.md
source_sha256: badfc991a9ea336d11501a3c78e49b810c29126bc15e00d2380d80068dca5de9
title: "Counting Colors — Solution"
description: "Given a sequence A[] of length n, answer q queries, each asking for the number of distinct colors in an interval."
tags: ["OI","Segment Tree","Persistent Segment Tree"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes: []
---

## Problem Statement

Given a sequence A[] of length n, you need to answer q queries. Each query gives two endpoints and asks for the number of distinct colors in the interval. n, q < 1e5.

## Main Idea

Consider building a persistent segment tree, using positions as version indices and the compressed color values as indices, recording the prefix count of each color; then just subtract the version information.
