Strings Problems
Strings Problems
Here are 20 problems each for easy, intermediate, and difficult levels that involve string
manipulation in Python:
### Easy
1. **Reverse a string.**
```python
def reverse_string(s):
return s[::-1]
```
```python
def is_palindrome(s):
return s == s[::-1]
```
```python
def count_vowels(s):
vowels = "aeiouAEIOU"
```
```python
def to_uppercase(s):
return s.upper()
```
def remove_spaces(s):
```
```python
def is_digit(s):
return s.isdigit()
```
```python
vowels = "aeiouAEIOU"
s = s.replace(vowel, ch)
return s
```
```python
def string_length(s):
return len(s)
```
```python
return s.count(sub)
```
10. **Convert a string to lowercase.**
```python
def to_lowercase(s):
return s.lower()
```
```python
return s.startswith(sub)
```
```python
return s.endswith(sub)
```
```python
return s.find(sub)
```
```python
def split_string(s):
return s.split()
```
15. **Join a list of words into a single string.**
```python
def join_words(words):
```
```python
def capitalize_words(s):
return s.title()
```
```python
def is_identifier(s):
return s.isidentifier()
```
```python
```
```python
def count_words(s):
return len(s.split())
```
def swap_case(s):
return s.swapcase()
```
### Intermediate
```python
def string_permutations(s):
```
```python
```
```python
def to_title_case(s):
```
```python
def longest_word(s):
words = s.split()
return max(words, key=len)
```
```python
def char_frequency(s):
return Counter(s)
```
```python
def remove_duplicates(s):
```
```python
import re
def is_valid_palindrome(s):
return s == s[::-1]
```
```python
def sort_words(s):
words = s.split()
words.sort()
return ' '.join(words)
```
```python
def first_non_repeating_char(s):
count = Counter(s)
for char in s:
if count[char] == 1:
return char
return None
```
```python
def longest_common_prefix(strs):
if not strs:
return ""
prefix = strs[0]
for s in strs[1:]:
prefix = prefix[:-1]
if not prefix:
return ""
return prefix
```
11. **Check if a string contains another string (without using the in keyword).**
```python
return s.find(sub) != -1
```
```python
result = ""
for char in s:
if char.isalpha():
else:
result += char
return result
```
```python
def count_case(s):
```
14. **Check if a string is a valid password (at least 8 characters, contains both letters and
numbers).**
```python
def is_valid_password(s):
if len(s) < 8:
return False
```
```python
def convert_to_number(s):
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
return None
```
```python
def second_most_frequent_char(s):
count = Counter(s)
most_common = count.most_common()
```
```python
```
```python
def are_rotations(s1, s2):
```
19. **Remove leading and trailing whitespaces from a string without using strip().**
```python
def remove_whitespaces(s):
start = 0
end = len(s) - 1
start += 1
end -= 1
return s[start:end+1]
```
```python
def longest_palindrome(s):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return s[left+1:right]
longest = ""
for i in range(len(s)):
odd_palindrome = expand_around_center(s, i, i)
return longest
```
### Difficult
1. **Implement a function to find all the anagrams of a string within another string.**
```python
result = []
p_count = Counter(p)
s_count = Counter(s[:len(p)-1])
s_count[s[i]]
+= 1
if s_count == p_count:
result.append(i-len(p)+1)
s_count[s[i-len(p)+1]] -= 1
if s_count[s[i-len(p)+1]] == 0:
del s_count[s[i-len(p)+1]]
return result
```
```python
for w in words:
cur += [w]
num_of_letters += len(w)
```
3. **Implement a function to find the smallest window in a string containing all characters of
another string.**
```python
if not t or not s:
return ""
dict_t = Counter(t)
required = len(dict_t)
l, r = 0, 0
formed = 0
window_counts = {}
char = s[r]
window_counts[char] = window_counts.get(char, 0) + 1
formed += 1
char = s[l]
if r - l + 1 < ans[0]:
ans = (r - l + 1, l, r)
window_counts[char] -= 1
l += 1
r += 1
```
```python
m, n = len(s1), len(s2)
if i == 0:
dp[i][j] = j
elif j == 0:
dp[i][j] = i
dp[i][j] = dp[i-1][j-1]
else:
return dp[m][n]
```
```python
return s
index, step = 0, 1
for char in s:
res[index] += char
if index == 0:
step = 1
step = -1
index += step
return ''.join(res)
```
```python
def decode_string(s):
stack = []
current_string = ""
k=0
for char in s:
if char.isdigit():
k = k * 10 + int(char)
stack.append((current_string, k))
current_string, k = "", 0
else:
current_string += char
return current_string
```
7. **Implement a function to check if a string matches a given pattern (with '.' and '*').**
```python
dp[0][0] = True
if pattern[i-1] == '*':
dp[0][i] = dp[0][i-2]
dp[i][j] = dp[i-1][j-1]
return dp[-1][-1]
```
```python
def eval_rpn(tokens):
stack = []
stack.append(int(token))
else:
b, a = stack.pop(), stack.pop()
if token == '+':
stack.append(a + b)
stack.append(a - b)
stack.append(a * b)
else:
stack.append(int(a / b))
return stack[0]
```
9. **Implement a function to find the longest substring with at most two distinct characters.**
```python
def length_of_longest_substring_two_distinct(s):
if len(s) < 3:
return len(s)
left, right = 0, 0
hashmap = defaultdict()
max_len = 2
if len(hashmap) < 3:
hashmap[s[right]] = right
right += 1
if len(hashmap) == 3:
del_idx = min(hashmap.values())
del hashmap[s[del_idx]]
left = del_idx + 1
return max_len
```
10. **Implement a function to find the longest substring without repeating characters.**
```python
def length_of_longest_substring(s):
char_index = {}
left = max_len = 0
for right, char in enumerate(s):
left = char_index[char] + 1
char_index[char] = right
return max_len
```
11. **Implement a function to find all starting indices of substring(s) in s that is a concatenation of
each word in words exactly once and without any intervening characters.**
```python
return []
word_count = Counter(words)
res = []
for i in range(word_len):
left = i
cur_count = Counter()
count = 0
if word in word_count:
cur_count[word] += 1
count += 1
cur_count[s[left:left + word_len]] -= 1
count -= 1
left += word_len
if count == num_words:
res.append(left)
else:
cur_count.clear()
count = 0
left = j + word_len
return res
```
```python
dp = [False] * (len(s) + 1)
dp[0] = True
for j in range(i):
dp[i] = True
break
return dp[-1]
```
13. **Implement a function to check if a given string is an interleaving of two other strings.**
```python
return False
dp[0][0] = True
return dp[-1][-1]
```
14. **Implement a function to find the longest substring with at most k distinct characters.**
```python
if k == 0:
return 0
left, right = 0, 0
hashmap = defaultdict()
max_len = 0
hashmap[s[right]] = right
right += 1
if len(hashmap) > k:
del_idx = min(hashmap.values())
del hashmap[s[del_idx]]
left = del_idx + 1
return max_len
```
15. **Implement a function to check if a string can be constructed by taking a substring of it and
appending multiple copies of the substring together.**
```python
def repeated_substring_pattern(s):
return (s + s)[1:-1].find(s) != -1
```
16. **Implement a function to find all valid IP addresses from a given string.**
```python
def restore_ip_addresses(s):
def is_valid(segment):
res = []
res.append(f"{s[:i]}.{s[i:j]}.{s[j:k]}.{s[k:]}")
return res
```
```python
def remove_invalid_parentheses(s):
def is_valid(s):
count = 0
for char in s:
if char == '(':
count += 1
if count < 0:
return False
return count == 0
level = {s}
while True:
if valid:
return valid
```
```python
def string_to_integer(s):
s = s.strip()
if not s:
return 0
negative = False
if s[0] == '-':
negative = True
s = s[1:]
s = s[1:]
result = 0
for char in s:
if not char.isdigit():
break
19. **Implement a function to check if a string can be segmented into a space-separated sequence
of one or more dictionary words using Trie.**
```python
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
node = self.root
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
node = self.root
return False
node = node.children[char]
return node.is_end
trie.insert(word)
def can_break(start):
if start == len(s):
return True
node = trie.root
return False
node = node.children[s[i]]
return True
return False
return can_break(0)
```
20. **Implement a function to find the minimum number of characters to be inserted to form a
palindrome.**
```python
def min_insertions_palindrome(s):
if i == 0 or j == 0:
L[i][j] = 0
L[i][j] = L[i-1][j-1] + 1
else:
return L[m][n]
rev = s[::-1]
n = len(s)
l = lcs(s, rev, n, n)
return n - l
```
These problems should provide a comprehensive set of challenges for learning and practicing string
manipulation in Python.