Back to Practice Dashboard
Python BasicsEasy

Sorting elements of an array by frequency

Learn how to solve the 'Sorting elements of an array by frequency' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

Write a function sort_by_frequency(arr) that sorts elements of the array by their frequency in descending order. If two elements have the same frequency, the smaller element comes first. Return the sorted array as a list.

Constraints
  • 1 <= len(arr) <= 10^5
  • -10^6 <= arr[i] <= 10^6

Examples

Example 1
Input
arr = [1, 1, 2, 2, 2, 3]
Output
[2, 2, 2, 1, 1, 3]
Explanation

2 appears 3 times (most frequent), 1 appears 2 times, 3 appears 1 time.

Example 2
Input
arr = [4, 4, 5, 5, 6]
Output
[4, 4, 5, 5, 6]
Explanation

4 and 5 both appear 2 times; 4 < 5 so 4 comes first. 6 appears once.

Example 3
Input
arr = [9, 9, 9]
Output
[9, 9, 9]
Explanation

Only one distinct element.

Need a Hint?
Use simple arithmetic operators (like modulo `%`, division `//`), conditional checks, or loops to inspect number properties.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor