> For the complete documentation index, see [llms.txt](https://liuzhenglaichn.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://liuzhenglaichn.gitbook.io/algorithm/discretization.md).

# Discretization

When the number range is very large and the numbers are very sparse, we can discretize the input numbers so that we can keep the ordering of the numbers while saving them in a much smaller array.

For example, the input array is:

```
-10000, 0, 10000
```

If we need to create an array covering the range we need to create one with length 20001, but actually there are just 3 numbers in it.

We can turn it into

```
0, 1, 2
```

with the following mapping

```
-10000 -> 0
0      -> 1
10000  -> 2
```

## Implementation

```cpp
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(N)
vector<int> discretize(vector<int> &input) {
    set<int> s(input.begin(), input.end()); // In this way, we dedupe the data and sort them
    unordered_map<int, int> m; // mapping from old number to new number
    int id = 0;
    for (int n : s) m[n] = id++;
    vector<int> output(input.size());
    for (int i = 0; i < input.size(); ++i) output[i] = m[input[i]];
    return output;
}
```

## Problem

* [327. Count of Range Sum (Hard)](https://leetcode.com/problems/count-of-range-sum) **When using with BIT**
* [699. Falling Squares (Hard)](https://leetcode.com/problems/falling-squares/)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://liuzhenglaichn.gitbook.io/algorithm/discretization.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
