Skip to content

1636. Sort Array by Increasing Frequency #62

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

To solve this problem, we can follow these steps:

  1. Count the frequency of each value in the input array.
  2. Use a custom comparator to sort the values based on their frequency first, and if the frequencies are the same, sort by value in decreasing order.

Let's implement this solution in PHP: 1636. Sort Array by Increasing Frequency

<?php
// Test cases
$nums1 = [1,1,2,2,2,3];
$nums2 = [2,3,1,3,2];
$nums3 = [-1,1,-6,4,5,-6,1,4,1];

print_r(frequencySort($nums1)); // Output: [3, 1, 1, 2, 2, 2]
print_r(frequencySort($nums2)); // Output: [1, 3, 3, 2, 2]
print_r(frequencySort($nums3)); // Output: [5, -1, 4, 4, -6, -6, 1, 1, 1]
?>

Explanation:

  1. array_count_values($nums):
    • This function counts the …

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
1 participant