Skip to content
CodeKruPro

Count each character

Coding problemEasy-MediumAsked in: Capgemini, Infosys, TCS, Wipro

Given a string s, count how many times each character occurs.

Return one entry per distinct character, in the order the characters first appear in s. Write each entry as the character, an equals sign and the count: for "hello" the answer is ["h=1", "e=1", "l=2", "o=1"].

Skip spaces. Upper and lower case are different characters. An empty string gives an empty list.

Examples

Example 1
Input: s = "hello"
Output: ["h=1","e=1","l=2","o=1"]
Example 2
Input: s = "a b a"
Output: ["a=2","b=1"]
Spaces are skipped.
Example 3
Input: s = "AaA"
Output: ["A=2","a=1"]

Constraints

  • The length of s is between 0 and 100,000
  • s holds printable ASCII characters only

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in