PAT Solution: 1084. Broken Keyboard


We give the solution for the programming ability test problem: 1084. Broken Keyboard. The naive solution takes O(M * N) time while using set or hash based method takes linear time O(M + N)

Broken Keyboard Problem Definition:

On a broken keyboard, some of the keys are worn out. So when you type some sentences, the characters corresponding to those keys will not appear on screen.

Now given a string that you are supposed to type, and the string that you actually type out, please list those keys which are for sure worn out.

Input Specification:

Each input file contains one test case. For each case, the 1st line contains the original string, and the 2nd line contains the typed-out string. Each string contains no more than 80 characters which are either English letters [A-Z] (case insensitive), digital numbers [0-9], or “_” (representing the space). It is guaranteed that both strings are non-empty.

Output Specification:

For each test case, print in one line the keys that are worn out, in the order of being detected. The English letters must be capitalized. Each worn out key must be printed once only. It is guaranteed that there is at least one worn out key.

Sample Input:


Sample Output:


Broken Keyboard Solutions:

1) For each character in the original string, we scan the whole printed string to determine if this character is in the second printed string or not. If the size of the first original string is M while the second string is of size N, the time complexity would be O(M * N)

2) Using set/hash table to store the characters in the second printed string, this step involves O(N) time, and for each character in the first original string, we test it whether it is the set or not in constant time for each character, this step takes O(M) time, so the total time complexity would be in linear O(M +N), the following code is accepted by the PAT OJ:

char upperCase(char c) {
	if (c <= 'z' && c >= 'a') return c + 'A' - 'a';
	return c;

int main() {
	std::unordered_set<char> setPrinted, setResults;

	std::string strOrignial, strPrinted;

	std::cin >> strOrignial;
	std::cin >> strPrinted;

	for (int i = strPrinted.size() - 1; i >= 0; --i)
	int nLength = strOrignial.size();
	char c;
	for (int i = 0; i < nLength; ++i) {
		c = upperCase(strOrignial[i]);
		if (1 != setPrinted.count(c) && 0 == setResults.count(c)) {
			std::cout << c;
	std::cout << std::endl;
	return 0;


To summarize, I give two solutions for the programming ability test problem 1084. Broken Keyboard. One is native and simple this takes O(M * N) time while the other one involving hash takes linear time in O(M + N)

Written on October 1, 2014