Problem overview
The method FindTheDifference receives two strings. t contains every letter of s, shuffled, plus exactly one extra letter at some position. The method returns that extra letter as a char.
With s = "abcd" and t = "abcde", the answer is 'e'. With s = "" and t = "y", nothing was shuffled and the answer is 'y'. The strings hold only lowercase letters, and s has at most 1000 of them.
Approach: compare letter counts
The extra letter is a letter of t, so it is enough to look at the letters of t one at a time and ask whether each one is the extra one.
A first idea is to check whether the letter appears in s at all. That fails when the added letter is one s already contains. For s = "aab" and t = "abab", every letter of t is in s, yet the added letter is the second 'b'.
The reliable test is a count. A letter is the extra one exactly when it appears more times in t than in s. For every other letter the counts are equal, because t is a shuffle of s plus one letter. Only one letter can have different counts, so the first mismatch found is the answer.
Counting a letter means walking a whole string, and the method does that for every letter of t. With n letters in s, that is about n letters times two walks of length n or so: O(n²). It is the simplest correct solution and a good starting point. Storing the counts once in a dictionary, or cancelling letters with XOR, brings the time down to O(n); those are other lessons.
Step by step
- Write a counting helper.
CountChar(string s, char c)returns how many timescappears ins. It sits aboveFindTheDifferenceon the sameSolutionclass, and the main method calls it twice per letter. - Start a counter at 0, an
intnamedcount. - Loop over the string with
foreach (char ch in s). Looping over astringgives its characters one at a time. - Compare each character with the one being counted:
ch == c. Forcharvalues,==compares the characters themselves. - Add one to
countwhen they match. - Return
countafter the loop. - In
FindTheDifference, loop overt. The extra letter is guaranteed to be there, so these are the only candidates. - Compare the counts. If
CountChar(s, i) != CountChar(t, i), the letteriappears more often int, so it is the extra one. - Return
ifrom inside theif, and return a placeholder after the loop. C# requires every path through a method with a return type to return a value. The constraints guarantee that the loop always finds the letter, so the finalreturn ' 'is never reached on valid input; it only satisfies the compiler.
The solution in C#
class Solution {
public int CountChar(string s, char c) {
int count = 0;
foreach (char ch in s) {
if (ch == c) {
count++;
}
}
return count;
}
public char FindTheDifference(string s, string t) {
foreach (char i in t) {
if (CountChar(s, i) != CountChar(t, i)) {
return i;
}
}
return ' ';
}
}
The C# details worth knowing:
charis a single UTF-16 code unit. It has its own literal syntax,'e'with single quotes, while"e"with double quotes is a one-letterstring. The method returns achar, so the answer is'e'.- Which letter is returned. The loop walks
tfrom the left and returns the first letter whose counts differ. When the extra letter is a repeat of one already ins, every copy of that letter has the same counts, so the result is still that letter. Fors = "aab"andt = "abab"the method returns'b'. - The helper is reused.
CountChar(s, i)andCountChar(t, i)are called with the same letter on both strings, so the two counts are directly comparable. - The helper's name. It is a
publicmethod onSolutionnext to the one the tests call. C# method names are case-sensitive, soCountCharandcountCharare different names.
Complexity
Time: O(n²), where n is the length of the strings. The loop runs at most n + 1 times. Each iteration calls CountChar twice, and each call walks a whole string of n or n + 1 letters. With n up to 1000, that is a couple of million steps, which is fast. The same code would be too slow for strings of millions of letters.
Space: O(1). The method keeps only a few int and char variables.
Edge cases and common mistakes
- Empty
s. Withs = ""andt = "y",CountChar(s, 'y')is 0 andCountChar(t, 'y')is 1, so the method returns'y'. - The extra letter repeats a letter of
s.s = "zz"andt = "zzz"returns'z'. Checking whether a letter is present insgets this wrong, which is why the lesson compares counts. - Counting only in
sor only int. One count alone says nothing. The test is the difference between the two. - Forgetting the final return. Without
return ' ', the compiler reports that not all code paths return a value. - Using double quotes for a letter.
CountChar(s, "a")doesn't compile because"a"is astring, not achar.
Testing
s = "abcd",t = "abcde"gives'e'.s = "",t = "y"gives'y'.s = "aab",t = "baab"gives'b'.s = "ab",t = "bca"gives'c'.
