algoadvance

Leetcode 1636. Sort Array by Increasing Frequency

Problem Statement

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.

Example 1:

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.

Example 2:

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

Example 3:

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

Constraints:

  1. 1 <= nums.length <= 100
  2. -100 <= nums[i] <= 100

Clarifying Questions

  1. Q: Are there any constraints on the time complexity we need to aim for? A: Not explicitly, but a time complexity better than O(n^2) would be suitable for a problem of this size.

  2. Q: Are all elements in the given array integers within the given range? A: Yes.

  3. Q: Can the input array contain any duplicates? A: Yes, the input array can have duplicates.

Strategy and Approach

  1. Count Frequencies: Use a HashMap to count the frequency of each element in the array.
  2. Sort Based on Frequency and Value: Use a custom comparator to sort:
    • First, by increasing frequency.
    • If frequencies are the same, then by decreasing value.

Code

import java.util.*;

public class Solution {
    public int[] frequencySort(int[] nums) {
        // Step 1: Calculate Frequencies
        Map<Integer, Integer> freqMap = new HashMap<>();
        for (int num : nums) {
            freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
        }

        // Step 2: Custom Sorting
        Integer[] numsArray = Arrays.stream(nums).boxed().toArray(Integer[]::new);
        Arrays.sort(numsArray, (a, b) -> {
            int freqCompare = freqMap.get(a).compareTo(freqMap.get(b));
            if (freqCompare == 0) {
                return b.compareTo(a);  // If frequencies are the same, sort by value descending
            }
            return freqCompare;  // Else, sort by frequency ascending
        });

        // Convert boxed Integer array back to int array
        return Arrays.stream(numsArray).mapToInt(Integer::intValue).toArray();
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(Arrays.toString(sol.frequencySort(new int[]{1, 1, 2, 2, 2, 3}))); // Output: [3, 1, 1, 2, 2, 2]
        System.out.println(Arrays.toString(sol.frequencySort(new int[]{2, 3, 1, 3, 2}))); // Output: [1, 3, 3, 2, 2]
        System.out.println(Arrays.toString(sol.frequencySort(new int[]{-1, 1, -6, 4, 5, -6, 1, 4, 1}))); // Output: [5, -1, 4, 4, -6, -6, 1, 1, 1]
    }
}

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI