Sorting Elements of an Array by Frequency | GeeksForGeeks | Problem of the Day

Поділитися
Вставка
  • Опубліковано 5 лис 2024

КОМЕНТАРІ • 2

  • @mathematics3398
    @mathematics3398  2 місяці тому

    Table of Contents
    0:00 Problem Statement
    0:43 Solution
    2:40 Pseudo Code
    6:57 Code

  • @mathematics3398
    @mathematics3398  2 місяці тому

    from functools import cmp_to_key
    class Solution:
    def compare(self, x, y):
    if x[0] > y[0]:
    return 1
    elif x[0] < y[0]:
    return -1
    else:
    if x[1] < y[1]:
    return 1
    return -1
    def sortByFreq(self,arr):
    freq = dict()
    for element in arr:
    if element in freq:
    freq[element] += 1
    else:
    freq[element] = 1
    temp = []
    for key, value in freq.items():
    temp.append([value, key])
    #print(temp)
    temp = sorted(temp, key=cmp_to_key(self.compare), reverse=True)
    #print(temp)
    ans = [0 for _ in range(len(arr))]
    i = 0
    for x in temp:
    f = x[0]
    while f:
    ans[i] = x[1]
    f -= 1
    i += 1
    return ans