Letters in Common
You will need to write a function that takes a string of words, separated by spaces, and determines how many letters in common each word has with the others. Capitalization and punctuation can be ignored. Please see the test cases below for some examples of what your program should output.
For example, if given the string “hello hi”, the result should be 1, as “h” is the only letter in common between the two words. The letter’s position in the string also does not matter: “apple rad” should also give 1, even though “a” appears in different places in the words.
Input
The first line of the input is the number of string to compress, n. The next n lines consist of a list of words separated by spaces. The strings only contain lowercase letters, with no punctuation or special characters.
Output
The output should be n lines with the number of letters in common on each line.
Sample Input
3
january february march
last
funny punny runny
Sample Output
2
4
3
Samples
Python
# returns the number of letters in common
# input is a list of strings
def num_letters_in_common(input):
#### WRITE CODE HERE ####
pass
num_cases = int(input())
for _ in range(num_cases):
print(num_letters_in_common(input().split(" ")))
Java
import java.util.Scanner;
class Sample {
public static int num_letters_in_common(String input[]) {
return 0;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num_cases = Integer.parseInt(scan.nextLine());
for (int t = 0; t < num_cases; t++) {
String input = scan.nextLine().split(" ");
System.out.println(num_letters_in_common(input));
}
}
}
Real Test Cases
Solutions
Python Solution
# returns the number of letters in common
# input is a list of strings
def num_letters_in_common(input):
letters = set(input[0])
for word in input[1:]:
letters.intersection_update(set(word))
return len(letters)
num_cases = int(input())
for _ in range(num_cases):
print(num_letters_in_common(input().split(" ")))
Java Solution
import java.util.HashSet;
import java.util.Scanner;
class Sample {
public static HashSet<Character> string_to_set(String input) {
HashSet<Character> letters = new HashSet<>();
for (int i = 0; i < input.length(); i++) {
letters.add(input.charAt(i));
}
return letters;
}
public static int num_letters_in_common(String input[]) {
HashSet<Character> letters = string_to_set(input[0]);
for (int i = 1; i < input.length; i++) {
letters.retainAll(string_to_set(input[i]));
}
return letters.size();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num_cases = Integer.parseInt(scan.nextLine());
for (int t = 0; t < num_cases; t++) {
System.out.println(num_letters_in_common(scan.nextLine().split(" ")));
}
}
}