Python dictionary, set and counter to check if frequencies can become same (original) (raw)

Last Updated : 31 Oct, 2025

Given a string of lowercase alphabets, the task is to determine whether it is possible to remove at most one character so that the frequency of every distinct character becomes the same.

**Examples:

Input : "xyyz"
Output : Yes

**Explanation: Remove one 'y', frequencies become {'x':1, 'y':1, 'z':1}

Input: "xxxxyyzz"
Output: No

**Explanation: It’s not possible to make all character frequencies equal by removing only one character.

Approach:

1. **Count frequencies of all characters using Counter(). This gives a dictionary where keys are characters and values are their frequencies.

2. **Extract frequency values and convert them into a set. A set removes duplicates, helping identify distinct frequencies.

3. **Check conditions:

Python Implementation:

Python `

from collections import Counter

s = 'xxxyyzzt'

freq = Counter(s) same = list(set(freq.values()))

if len(same) > 2: print('No') elif len(same) == 2 and abs(same[1] - same[0]) > 1: print('No') else: print('Yes')

`

**Explanation: