Here's a cheatsheet for choosing the right algorithm for string problems, focusing on the most asked interview string problems in Microsoft interviews:

ProblemAlgorithmTime ComplexitySpace Complexity
Longest Substring Without Repeating CharactersSliding WindowO(n)O(min(n, m))
Longest Palindromic SubstringDynamic ProgrammingO(n^2)O(n^2)
Anagram DetectionHashingO(n)O(n)
String CompressionRun-Length EncodingO(n)O(n)
KMP AlgorithmKMPO(n + m)O(m)
Rabin-Karp AlgorithmRabin-KarpO(n + m)O(1)
Find Duplicate CharactersHashingO(n)O(n)
First Non-Repeating CharacterHashingO(n)O(n)
Reverse a StringTwo PointersO(n)O(1)
Palindrome CheckTwo PointersO(n)O(1)
Here's a brief explanation of each algorithm:
  • Sliding Window: Useful for substring problems, especially with contiguous sequences.
  • Dynamic Programming: Suitable for problems with overlapping subproblems or optimal substructure.
  • Hashing: Effective for fast lookup or counting.
  • KMP Algorithm: Efficient for pattern matching in strings.
  • Rabin-Karp Algorithm: Uses hashing for pattern matching.
  • Two Pointers: Useful for comparing or manipulating two strings.
This cheatsheet should help you quickly recall the most suitable algorithm for common string problems in Microsoft interviews.