Sort by Frequency, Then Value
Updated
Problem statement
You are given an integer array nums. Sort it by how many times each value appears:
- A value that appears fewer times comes before a value that appears more times.
- If two values appear the same number of times, the smaller value comes first.
Keep every copy. A value that appears k times shows up k times in a row in the answer. Return the sorted array.
Function
frequencySort(nums: int[]) → int[]Examples
Example 1
nums = [4,6,4,2,6,6]return = [2,4,4,6,6,6]2 appears once, 4 twice and 6 three times, so the answer lists them in that order.
Example 2
nums = [5,-1,5,-1,3,3,7]return = [7,-1,-1,3,3,5,5]7 appears once, so it comes first. -1, 3 and 5 each appear twice, so they follow in increasing order: -1, then 3, then 5.
Example 3
nums = [12,3,12,3]return = [3,3,12,12]Both values appear twice. The smaller value, 3, goes first.
Constraints
1 <= nums.length <= 2000-10^9 <= nums[i] <= 10^9
More C3.ai interview questions
- Drop Recent Duplicate MessagesOA · Seen Oct 2026
- Maximum K-Star SumOA · Seen Oct 2026
- Largest Square Sub-Grid Within a Sum LimitOA · Seen Jan 2023
- Prefix Scores With the Running MaximumOA · Seen Jan 2023
- Tree Node With Maximum BeautyOA · Seen Nov 2022
- Count Vowel Strings With Follow RulesOA · Seen Apr 2022
- Photo Album Insert OrderOA · Seen Apr 2022
- Count Distinct Binary Search TreesOA · Seen Mar 2022
- Count Palindromic Subsequences of Length KOA · Seen Mar 2022
- Fewest Turns to Open a Wheel LockPHONE SCREEN · Seen Nov 2024
Similar questions at other companies
- Count User Mentions in Chat MessagesRamp · OARamp interview questions
- Word Frequency Counts in Alphabetical OrderAbridge · OAAbridge interview questions
- Minimum Magic Stones After MergesElevenLabs · OAElevenLabs interview questions
- Items SortAkuna Capital · OAAkuna Capital interview questions
- Count Cross-Array Target-Sum PairsVisa · OAVisa interview questions
- Array Rank TransformTata Consultancy Services · OATata Consultancy Services interview questions
- Find Max Health SumAmazon · OA
- Influencers SquadTikTok · OATikTok interview questions
- Count Teams Outscoring a Target TeamBloomberg LP · OABloomberg LP interview questions
- Count Soldiers with a Next-Rank SuperiorMarshall Wace · OAMarshall Wace interview questions