Program to Find Out a Sequence with Equivalent Frequencies in Python


Suppose we have a list of numbers. We have to find the length of the longest sequence of numbers such that when we delete a number from the sequence, each number occurs the same number of times.

So, if the input is like numbers = [2, 4, 4, 7, 7, 6, 6], then the output will be 7.

To solve this, we will follow these steps −

  • num_freq := a new map

  • freq_freq := a new map

  • diff_freq := a new set

  • result := 1

  • for each index I and value num in nums, do

    • cur_freq := num_freq[num]

    • num_freq[num] := num_freq[num] + 1

    • freq_freq[cur_freq] := freq_freq[cur_freq] − 1

    • freq_freq[cur_freq + 1] := freq_freq[cur_freq + 1] + 1

    • add cur_freq + 1 into diff_freq

    • if cur_freq is in diff_freq, and freq_freq[cur_freq] is same as 0, then

      • delete cur_freq from diff_freq

    • df_list := a new list by taking elements of diff_freqs

    • if size of df_list is same as 1, then

      • result := i + 1

    • otherwise when size of df_list is same as 2, and (when any of [|freq_freq[df_list[0]] - freq_freq[df_list[1]]| ,freq_freq[df_list[0]], freq_freq[df_list[1]] ) is 1 ), and (when any of [|df_list[0] - df_list[1]|, df_list[0], df_list[1]]) is 1), then

      • result := i + 1

  • return result

Let us see the following implementation to get better understanding −

Example

 Live Demo

from collections import defaultdict
class Solution:
   def solve(self, nums):
      num_freq = defaultdict(int)
      freq_freq = defaultdict(int)
      diff_freq = set()
      result = 1
      for i, num in enumerate(nums):
         cur_freq = num_freq[num]
         num_freq[num] += 1
         freq_freq[cur_freq] −= 1
         freq_freq[cur_freq + 1] += 1
         diff_freq.add(cur_freq + 1)
         if cur_freq in diff_freq and freq_freq[cur_freq] == 0:
            diff_freq.remove(cur_freq)
         df_list = list(diff_freq)
         if len(df_list) == 1:
            result = i + 1
         elif (
            len(df_list) == 2
            and any(
               x == 1
               for x in [
                  abs(freq_freq[df_list[0]] − freq_freq[df_list[1]]),
                  freq_freq[df_list[0]],
                  freq_freq[df_list[1]],
               ]
            )
            and any(x == 1 for x in [abs(df_list[0] − df_list[1]), df_list[0], df_list[1]])
            ):
            result = i + 1
      return result
ob = Solution()
print(ob.solve([2, 4, 4, 7, 7, 6, 6]))

Input

numbers = [2, 4, 4, 7, 7, 6, 6]

Output

7

Updated on: 26-Dec-2020

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements