> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Sort Array by Increasing Frequency

> Tested Python solution for LeetCode 1636 with 22 pytest cases. Generate a practice environment with lcpy.

LeetCode 1636, [Easy](/catalog/easy). Topics: [Array](/catalog/topics/array), [Hash Table](/catalog/topics/hash-table), [Sorting](/catalog/topics/sorting). [View on LeetCode](https://leetcode.com/problems/sort-array-by-increasing-frequency/description/).

Generate this problem as a practice environment: tested reference solution, 22 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 1636   # by problem number
lcpy gen -s sort_array_by_increasing_frequency   # by problem name
```

## Problem

Given an array of integers `nums`, sort the array in **increasing** order based on the **frequency** of the values. If multiple values have the same frequency, sort them in **decreasing** order.

Return *the sorted array*.

### Examples

```
Input: nums = [1,1,2,2,2,3]
Output: [3,1,1,2,2,2]
Explanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.
```

```
Input: nums = [2,3,1,3,2]
Output: [1,3,3,2,2]
Explanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.
```

```
Input: nums = [-1,1,-6,4,5,-6,1,4,1]
Output: [5,-1,4,4,-6,-6,1,1,1]
```

### Constraints

* `1 <= nums.length <= 100`
* `-100 <= nums[i] <= 100`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/sort_array_by_increasing_frequency/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/sort_array_by_increasing_frequency/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import Counter


class Solution:
    # Time: O(n log n)
    # Space: O(n)
    def frequency_sort(self, nums: list[int]) -> list[int]:
        counts = Counter(nums)
        return sorted(nums, key=lambda num: (counts[num], -num))
```

## Complexity

| Time | Space |
| - | - |
| O(n log n) | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.