Skip to main content
Beginnercoding Verified

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

Quick answer

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

python
Loading editor…
Output

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 free

Hints

Reference solution

Count, then filter.

main.py
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).

main.py
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)?

Discussion