Intermediate Level

Implement the sortByFrequencyAscending method that sorts values by increasing frequency while resolving ties consistently.

The input contains an integer array nums and its length size. Your task is to sort the values by their frequency in ascending order.

Values that appear fewer times should come first. If two values have the same frequency, place the smaller value first. For example, [4,5,4,6,5,5] becomes [6,4,4,5,5,5].

Example 1

Input
nums (int[]) = [4,5,4,6,5,5]
size (int) = 6
Returns (int[]) [6,4,4,5,5,5]

Example 2

Input
nums (int[]) = [2,3,2,1]
size (int) = 4
Returns (int[]) [1,3,2,2]

Example 3

Input
nums (int[]) = [7,7,7]
size (int) = 3
Returns (int[]) [7,7,7]

First count how many times each value appears in the array.

Then sort the array using two rules. Compare frequency first, so the value with the smaller frequency comes first. If frequencies are equal, compare the actual values and put the smaller value first.

Pseudocode:

function sortByFrequencyAscending(nums, size):
    frequency = empty map
    for each value in nums:
        frequency[value]++
    sort nums using this rule:
        if frequency[a] != frequency[b]:
            a comes before b when frequency[a] < frequency[b]
        else:
            a comes before b when a < b
    return nums
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.