1. Sorting and Linear Scanning
Intuition
Sort s and t. Iterate through both sorted strings: the first index where s[i] != t[i] indicates t[i] is the extra character. If the loop completes without a mismatch, the extra character is the last element t[t.length - 1].
When to apply: Basic exploratory approach.
Algorithm
- Sort string
sand stringt. - Loop
ifrom0tos.length - 1: - If
s[i] != t[i], returnt[i]. - If no mismatch within loop, return
t[t.length - 1].
Sorting Both Strings & Linear Mismatch Search
2 of 2 questions left todayObservation: Sort both strings alphabetically
Observation: Sort both strings alphabetically. Compare s[0]='a' and t[0]='a'.
Decision: Elements match. Advance i and j.
Invariant: Prefix of length 1 matches identically.
#include <iostream>#include <string>#include <algorithm> class Solution {public: char findTheDifference(std::string s, std::string t) { std::sort(s.begin(), s.end()); std::sort(t.begin(), t.end()); for (int i = 0; i < (int)s.size(); ++i) { if (s[i] != t[i]) return t[i]; } return t.back(); }}; int main() { Solution sol; std::cout << sol.findTheDifference("abcd", "abcde") << std::endl; // __SF_TOKEN_A__ return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— Sorting strings of length N takes O(N log N) time. - Space complexity:
O(N) for sorted copies
Why Brute Force Doesn't Scale:
Bitwise XOR eliminates the need for data structures or sorting entirely.
Only a single primitive accumulator variable is needed.