Sort Array by Increasing Frequency — LeetCode 1636 Python Solution

EasyArrayHash TableSorting
Problem
#1636
Pattern
Sorting
Reading time
2 min

The 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.

Example

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.

Python solution

Python
class Solution:
    def frequencySort(self, nums: List[int]) -> List[int]:
        cnt = Counter(nums)
        return sorted(nums, key=lambda x: (cnt[x], -x))

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1636. Sort Array by Increasing Frequency is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1636. Sort Array by Increasing Frequency?
LeetCode 1636. Sort Array by Increasing Frequency is rated Easy on LeetCode.
What is the time complexity of LeetCode 1636. Sort Array by Increasing Frequency?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1636. Sort Array by Increasing Frequency?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1636. Sort Array by Increasing Frequency cover?
LeetCode 1636. Sort Array by Increasing Frequency is tagged Array, Hash Table and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview