Write a function that returns the frequency of characters in a string, keeping only characters that appear more than twice.
ReportedSource: GeeksforGeeks interview experience: Deloitte Product Engineering Analyst 2024
Count characters with a dict/Counter in one pass, then keep entries with count > 2. O(n). Clarify spaces, case and output order.
Constraints
- Input: one line with the string s (may be empty). It has lowercase letters and digits only, no spaces.
- 0 <= len(s) <= 100000.
- Output: one line "char=count" for each character that appears more than twice, in order of first appearance. Print none if there is no such character.
Sample I/O
in: aaabbbbc
out: a=3 b=4
in: aabbcc
out: none
in: xyxyxy1
out: x=3 y=3
Sign up to run your code in the sandbox.
Sign up to run code and get an AI review
You can read and edit the challenge freely — running it in the sandbox and getting AI feedback need a free account.
Sign up freeHints
Reference solution
Count, then filter.
from collections import Counter
def frequent_chars(s):
counts = Counter(s)
return {ch: n for ch, n in counts.items() if n > 2}
frequent_chars('aaabbbbc') # {'a': 3, 'b': 4}
Without libraries (shows the logic).
def frequent_chars(s):
counts = {}
for ch in s:
counts[ch] = counts.get(ch, 0) + 1
return {ch: n for ch, n in counts.items() if n > 2}
Complexity. O(n) time, O(k) space where k is the number of distinct characters.
Clarify with the interviewer. Ignore spaces? Case-insensitive (s.lower())? Output order (dicts keep first-appearance order in Python 3.7+; sort by frequency with sorted(..., key=lambda kv: -kv[1]) if needed)?