Characters Count

Problem:
Suppose you are given a collection of strings like [swquiz,gkhive,testdriven ]. Each string shall have characters from ‘a’ to ‘z’, only lower case, there can be repetition of characters in a given string.
Write a program for following
1) Count of characters that are available in all the input strings
2) Count of characters that are available in at least on string.
For the above input strings output shall be 1, 11
Approach:
For ease, let us consider a,b,c,d are only characters in our char space.
If abc, acd are input strings.. solution shall be like
Imagine four bits [0][0][0][0] (Since we have 4 chars in our space. For actual problem 26 bits are required)
1<<0   => [0][0][0][1]  => represents char ‘a’ found in String
1<<1   => [0][0][1][0]  => represents char ‘b’ found in String
1<<2   => [0][1][0][0]  => represents char ‘c’ found in String
1<<3   => [1][0][0][0]  => represents char ‘d’ found in String
For each string, form four bits accordingly ..
‘abc’ means  [0][0][0][1] & [0][0][1][0]&[0][1][0][0] => [0][1][1][1]
‘acd’ means  [0][0][0][1] &[0][1][0][0]& [1][0][0][0] => [1][0][1][1]
Then [0][1][1][1] &  [1][0][1][1] =>  [0][0][1][1] (Number of ones is count of chars available in all Strings)
[0][1][1][1] |  [1][0][1][1] =>  [1][1][1][1] (Number of ones is count of chars available in at least one String)
Code:

Leave a comment

Your email address will not be published. Required fields are marked *