Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Find Most Frequent Character

Find the most frequent nonspace character. Students build a frequency map, select by count, and understand the first-seen rule when maximum counts tie.

AdvancedPhase 5 - Category 5: Advanced String LogicExample 9 of 14
find-most-frequent-character.py
1# Take string input
2s = input("Enter a string: ")
3
4# Count frequency
5freq = {}
6for char in s:
7 if char != ' ': # Ignore spaces
8 freq[char] = freq.get(char, 0) + 1
9
10# Find most frequent
11if freq:
12 most_frequent = max(freq, key=freq.get)
13 print(f"Most frequent: {most_frequent} (appears {freq[most_frequent]} times)")
14else:
15 print("No characters found")

Output

Enter a string: hello
Most frequent: l (appears 2 times)

In this one

  • Exclude ordinary spaces
  • Select by dictionary value
  • Understand tied maxima

How it works

  1. 1

    Count each nonspace character.

  2. 2

    Guard an empty frequency dictionary.

  3. 3

    Choose max by freq.get and print its count.

Edge cases

What happens on equal maximum counts?

What happens on equal maximum counts?

The first encountered tied character is selected.

Are tabs ignored?

Are tabs ignored?

No. The code skips only ' '.

What's going on

Only ordinary space characters are skipped in the counting loop. freq maps each remaining character to its occurrence count.

max(freq, key=freq.get) chooses the key with the greatest count. Equal counts keep the first inserted key, so first appearance breaks ties. Tabs are not ordinary spaces and still count. Empty or all-space input leaves no key and uses the message branch.

What happens on equal maximum counts? The first encountered tied character is selected.

Are tabs ignored? No. The code skips only ' '.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does key=freq.get compare?

Pick an answer to check it.

Question 2

What happens on equal maximum counts?

Pick an answer to check it.

Questions people ask

What happens on equal maximum counts?

The first encountered tied character is selected.

Are tabs ignored?

No. The code skips only ' '.

What does key=freq.get compare?

Stored frequencies.