The key is not solving many questions, but recognizing patterns like hashing, two pointers, and sliding window. Once these are clear, most string problems become much easier to handle.
Table of Contents
Valid Anagram
You are given two strings. You need to check whether both strings contain the same characters with the same frequency, regardless of their order. If they do, return True; otherwise, return False.
# Python program to show valid anagrams
def is_anagram(s, t):
if len(s) != len(t):
return False
count = {}
for ch in s:
count[ch] = count.get(ch, 0) + 1
for ch in t:
if ch not in count:
return False
count[ch] -= 1
if count[ch] 0:
return False
return True
# Test cases
print(is_anagram("listen", "silent"))
print(is_anagram("hello", "world"))
Output:
True
False
Explanation:
This code counts the frequency of each character in the first string and then reduces the count using the second string. If all counts match and never go negative, the strings are anagrams.
Palindrome Check (Two Pointers)
You are given a string. You need to check whether it reads the same forward and backward. If it does, return True; otherwise, return False.
# Python program to check palindrome
def is_palindrome(s):
left, right = 0, len(s) - 1
while left right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
# Test cases
print(is_palindrome("madam"))
print(is_palindrome("hello"))
Output:
True
False
Explanation:
This code uses two pointers, one from the start and one from the end, and compares characters. If all pairs match, the string is a palindrome.
Longest Substring Without Repeating Characters
You are given a string. You need to find the length of the longest substring that contains only unique characters, with no repetitions.
# Python program to find longest substring without repeating characters
def longest_unique_substring(s):
char_set = set()
left = 0
max_length = 0
for right in range(len(s)):
while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
max_length = max(max_length, right - left + 1)
return max_length
# Test cases
print(longest_unique_substring("abcabcbb"))
print(longest_unique_substring("bbbbb"))
Output:
3
1
Explanation:
This code uses a sliding window with a set to keep track of unique characters. The window expands until a duplicate appears and shrinks to remove it.
Group Anagrams
You are given a list of strings. You need to group together all strings that are anagrams of each other and return them as separate groups.
# Python program to group anagrams
from collections import defaultdict
def group_anagrams(strs):
groups = defaultdict(list)
for word in strs:
key = ''.join(sorted(word))
groups[key].append(word)
return list(groups.values())
# Test case
words = ["eat", "tea", "tan", "ate", "nat", "bat"]
print(group_anagrams(words))
Output:
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
Explanation:
This code sorts each string and uses the sorted version as a key in a dictionary. Words with the same sorted form are grouped together.
String Compression
You are given a string. You need to compress it by replacing consecutive repeating characters with the character followed by its count.
# Python program to compress strings
def compress_string(s):
if not s:
return ""
result = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1
else:
result.append(s[i - 1] + str(count))
count = 1
result.append(s[-1] + str(count))
return "".join(result)
# Test case
print(compress_string("aaabbc"))
Output:
a3b2c1
Explanation:
This code counts consecutive repeating characters and builds a new string by appending the character along with its count.
Find All Anagrams in a String
You are given two strings: a main string and a pattern. You need to find all starting indices in the main string where the substring is an anagram of the pattern.
# Python program to find all anagrams in a string
def find_anagrams(s, p):
from collections import Counter
p_count = Counter(p)
window = Counter()
result = []
k = len(p)
for i in range(len(s)):
window[s[i]] += 1
if i = k:
if window[s[i - k]] == 1:
del window[s[i - k]]
else:
window[s[i - k]] -= 1
if window == p_count:
result.append(i - k + 1)
return result
# Test case
print(find_anagrams("cbaebabacd", "abc"))
Output:
[0, 6]
Explanation:
This code uses a sliding window with frequency counters. It compares the current window with the target pattern and records starting indices when they match.
Minimum Window Substring
This is a slightly advanced but very common interview problem. You are given two strings. You need to find the smallest substring in the first string that contains all the characters of the second string. If no such substring exists, return an empty string.
# Python program to find minimum window substring
def min_window(s, t):
from collections import Counter
t_count = Counter(t)
window = {}
have, need = 0, len(t_count)
res = [-1, -1]
res_len = float("inf")
left = 0
for right in range(len(s)):
char = s[right]
window[char] = window.get(char, 0) + 1
if char in t_count and window[char] == t_count[char]:
have += 1
while have == need:
if (right - left + 1) res_len:
res = [left, right]
res_len = right - left + 1
window[s[left]] -= 1
if s[left] in t_count and window[s[left]] t_count[s[left]]:
have -= 1
left += 1
l, r = res
return s[l:r+1] if res_len != float("inf") else ""
# Test case
print(min_window("ADOBECODEBANC", "ABC"))
Output:
Explanation:BANC
This code uses a sliding window and tracks required characters using a frequency map. It expands to include all characters and shrinks to find the smallest valid window.
Conclusion
String problems become much easier once you recognize common patterns like hashing, two pointers, and sliding window. Instead of memorizing solutions, focus on understanding how and why they work.With consistent practice and clear thinking, even new problems start to feel familiar and manageable.
Frequently Asked Questions
1. How do I choose the right pattern?2. Do I need advanced algorithms like KMP?Identify the problem type - use hashing for counts, sliding window for substrings, and two pointers for comparisons.
3. Why is sliding window difficult?No, basic approaches are enough for most interviews.
4. How many problems should I solve?It is difficult it involves dynamic movement of pointers, but it becomes easier with practice.
5. Which topics are most important?Around 10–15 good problems covering patterns are enough.
6. Why does my code fail sometimes?Hashing, sliding window, two pointers, and substring problems.
7. Is Python good for string problems?You are likely missing edge cases like empty or repeated strings.
8. How can I solve faster in interviews?Yes, it is simple and efficient due to built-in data structures.
9. Can I use AI during preparation?Focus on pattern recognition instead of solving from scratch.
10. What is the most common mistake?Yes, but use it to learn and debug, not to copy solutions.
Not recognizing patterns and overcomplicating simple problems.
0 Comments