Prepin
Log in

You have two strings, String A and String B. What is the method to count how many times a character from String B appears in String A?

Approach / Explanation

This question assesses your skills in string manipulation and analysis within a programming framework. You are provided with two strings, String A and String B , and your objective is to determine how many times each character from String B appears in String A. When addressing this question, concentrate on the process of comparing the characters from both strings and counting their occurrences. It is essential to showcase your ability to create effective algorithms or utilize existing string functions, depending on the programming language you choose. Your response should encompass the following: Comprehension of string manipulation techniques. Appropriate use of programming control structures (such as loops and conditionals). Development of a counting mechanism. Effective comparison of characters between the two strings. Keep in mind important aspects like case sensitivity, special characters, and whitespace.

Suggested Answer

In Python, one method involves constructing a dictionary in which the keys are the characters from String B, and the values represent the frequency of those characters in String A. def get_character_count ( A , B ) : count_dict = { char : A . count ( char ) for char in B } return count_dict This utilizes a dictionary comprehension that, for each character in B, computes its occurrence in A using A.count(char) and assigns the result to the appropriate key in the dictionary. Ultimately, this produces a dictionary containing the counts of the characters from B found in A.

Alternative Answer

In Java, you can also utilize a for loop to go through each character in String B and use the countMatches method from Apache Commons Lang's StringUtils class to tally the occurrences in String A. public class CharacterCount { public static void countCharacter ( String A , String B ) { for ( char c : B . toCharArray ( ) ) { int count = StringUtils . countMatches ( A , String . valueOf ( c ) ) ; System . out . println ( c + ": " + count ) ; } } } This approach involves converting String B into a character array and iterating over each character. For every character, it applies the StringUtils.countMatches method to determine how many times that character appears in String A, and then outputs the count.

Question Details

Difficulty & Category

Medium
technical

Companies

Google

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.