🧠Top 10 Easy String-Based DSA Questions (With LeetCode Links)
Strings are one of the most asked topics in programming interviews. They are fundamental, simple to grasp, yet offer deep logical challenges. Whether you're preparing for placements or starting your DSA journey, these 10 easy-level problems on LeetCode will give you the perfect start.
🔟 Top 10 Easy-Level String Problems on LeetCode
-
Valid Anagram
🔗 LeetCode Link
📚 Tags: Hashing, SortingView Solutions
Python Solution
class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False char_count = {} for char in s: char_count[char] = char_count.get(char, 0) + 1 for char in t: if char not in char_count: return False char_count[char] -= 1 if char_count[char] < 0: return False return True
Java Solution
import java.util.HashMap; import java.util.Map; class Solution { public boolean isAnagram(String s, String t) { if (s.length() != t.length()) { return false; } Map<Character, Integer> charCount = new HashMap<>(); for (char c : s.toCharArray()) { charCount.put(c, charCount.getOrDefault(c, 0) + 1); } for (char c : t.toCharArray()) { if (!charCount.containsKey(c) || charCount.get(c) == 0) { return false; } charCount.put(c, charCount.get(c) - 1); } return true; } }
C++ Solution
#include <string> #include <unordered_map> #include <algorithm> // For std::sort class Solution { public: bool isAnagram(std::string s, std::string t) { if (s.length() != t.length()) { return false; } // Approach 1: Using Hash Map std::unordered_map<char, int> charCount; for (char c : s) { charCount[c]++; } for (char c : t) { if (charCount.find(c) == charCount.end() || charCount[c] == 0) { return false; } charCount[c]--; } return true; // Approach 2: Sorting (alternative, often slower for long strings) // std::sort(s.begin(), s.end()); // std::sort(t.begin(), t.end()); // return s == t; } };
C Solution
#include <stdbool.h> #include <string.h> #include <stdlib.h> // For calloc bool isAnagram(char * s, char * t){ int len_s = strlen(s); int len_t = strlen(t); if (len_s != len_t) { return false; } // Using an array as a frequency map for ASCII characters (0-255) // For lowercase English letters only, int freq[26] would suffice int freq[256] = {0}; for (int i = 0; i < len_s; i++) { freq[(unsigned char)s[i]]++; } for (int i = 0; i < len_t; i++) { if (freq[(unsigned char)t[i]] == 0) { return false; } freq[(unsigned char)t[i]]--; } return true; }
-
Reverse String
🔗 LeetCode Link
📚 Tags: Two Pointers, String ManipulationView Solutions
Python Solution
class Solution: def reverseString(self, s: list[str]) -> None: """ Do not return anything, modify s in-place instead. """ left, right = 0, len(s) - 1 while left < right: s[left], s[right] = s[right], s[left] left += 1 right -= 1
Java Solution
class Solution { public void reverseString(char[] s) { int left = 0; int right = s.length - 1; while (left < right) { char temp = s[left]; s[left] = s[right]; s[right] = temp; left++; right--; } } }
C++ Solution
#include <vector> #include <algorithm> // For std::swap class Solution { public: void reverseString(std::vector<char>& s) { int left = 0; int right = s.size() - 1; while (left < right) { std::swap(s[left], s[right]); left++; right--; } } };
C Solution
#include <string.h> // For strlen void reverseString(char* s, int sSize){ int left = 0; int right = sSize - 1; while (left < right) { char temp = s[left]; s[left] = s[right]; s[right] = temp; left++; right--; } }
-
Implement strStr()
🔗 LeetCode Link
📚 Tags: Brute Force, KMPView Solutions
Python Solution
class Solution: def strStr(self, haystack: str, needle: str) -> int: if not needle: return 0 n = len(haystack) m = len(needle) if m > n: return -1 for i in range(n - m + 1): if haystack[i:i+m] == needle: return i return -1
Java Solution
class Solution { public int strStr(String haystack, String needle) { if (needle.isEmpty()) { return 0; } return haystack.indexOf(needle); // Java's built-in function /* // Manual implementation int n = haystack.length(); int m = needle.length(); if (m > n) { return -1; } for (int i = 0; i <= n - m; i++) { boolean match = true; for (int j = 0; j < m; j++) { if (haystack.charAt(i + j) != needle.charAt(j)) { match = false; break; } } if (match) { return i; } } return -1; */ } }
C++ Solution
#include <string> class Solution { public: int strStr(std::string haystack, std::string needle) { if (needle.empty()) { return 0; } // C++ string::find is similar to Java's indexOf size_t found = haystack.find(needle); if (found != std::string::npos) { return found; } return -1; /* // Manual implementation int n = haystack.length(); int m = needle.length(); if (m > n) { return -1; } for (int i = 0; i <= n - m; ++i) { bool match = true; for (int j = 0; j < m; ++j) { if (haystack[i + j] != needle[j]) { match = false; break; } } if (match) { return i; } } return -1; */ } };
C Solution
#include <string.h> // For strstr int strStr(char * haystack, char * needle){ if (strlen(needle) == 0) { return 0; } char* result = strstr(haystack, needle); // C's built-in strstr if (result == NULL) { return -1; } return result - haystack; /* // Manual implementation int n = strlen(haystack); int m = strlen(needle); if (m > n) { return -1; } for (int i = 0; i <= n - m; i++) { int j; for (j = 0; j < m; j++) { if (haystack[i + j] != needle[j]) { break; } } if (j == m) { // If inner loop completed, a match was found return i; } } return -1; */ }
-
Valid Palindrome
🔗 LeetCode Link
📚 Tags: Two Pointers, StringView Solutions
Python Solution
class Solution: def isPalindrome(self, s: str) -> bool: cleaned_s = "" for char in s: if '0' <= char <= '9' or 'a' <= char <= 'z' or 'A' <= char <= 'Z': cleaned_s += char.lower() left, right = 0, len(cleaned_s) - 1 while left < right: if cleaned_s[left] != cleaned_s[right]: return False left += 1 right -= 1 return True # Simpler approach using list comprehension and built-in functions # s = "".join(filter(str.isalnum, s)).lower() # return s == s[::-1]
Java Solution
class Solution { public boolean isPalindrome(String s) { if (s.isEmpty()) { return true; } int left = 0; int right = s.length() - 1; while (left < right) { char lChar = s.charAt(left); char rChar = s.charAt(right); if (!Character.isLetterOrDigit(lChar)) { left++; } else if (!Character.isLetterOrDigit(rChar)) { right--; } else { if (Character.toLowerCase(lChar) != Character.toLowerCase(rChar)) { return false; } left++; right--; } } return true; } }
C++ Solution
#include <string> #include <cctype> // For isalnum, tolower class Solution { public: bool isPalindrome(std::string s) { int left = 0; int right = s.length() - 1; while (left < right) { if (!std::isalnum(s[left])) { left++; } else if (!std::isalnum(s[right])) { right--; } else { if (std::tolower(s[left]) != std::tolower(s[right])) { return false; } left++; right--; } } return true; } };
C Solution
#include <stdbool.h> #include <string.h> #include <ctype.h> // For isalnum, tolower bool isPalindrome(char * s){ int left = 0; int right = strlen(s) - 1; while (left < right) { if (!isalnum(s[left])) { left++; } else if (!isalnum(s[right])) { right--; } else { if (tolower(s[left]) != tolower(s[right])) { return false; } left++; right--; } } return true; }
-
Longest Common Prefix
🔗 LeetCode Link
📚 Tags: String, Prefix ScanView Solutions
Python Solution
class Solution: def longestCommonPrefix(self, strs: list[str]) -> str: if not strs: return "" # Take the first string as a reference prefix prefix = strs[0] for i in range(1, len(strs)): # While the current string doesn't start with the prefix, # shorten the prefix by one character from the end while strs[i].find(prefix) != 0: prefix = prefix[:-1] if not prefix: # If prefix becomes empty, no common prefix exists return "" return prefix
Java Solution
class Solution { public String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) { return ""; } String prefix = strs[0]; for (int i = 1; i < strs.length; i++) { while (strs[i].indexOf(prefix) != 0) { prefix = prefix.substring(0, prefix.length() - 1); if (prefix.isEmpty()) { return ""; } } } return prefix; } }
C++ Solution
#include <string> #include <vector> #include <algorithm> // For std::min class Solution { public: std::string longestCommonPrefix(std::vector<std::string>& strs) { if (strs.empty()) { return ""; } std::string prefix = strs[0]; for (int i = 1; i < strs.size(); ++i) { // Compare character by character int j = 0; while (j < prefix.length() && j < strs[i].length() && prefix[j] == strs[i][j]) { j++; } prefix = prefix.substr(0, j); // Update prefix to the common part if (prefix.empty()) { return ""; } } return prefix; } };
C Solution
#include <string.h> #include <stdlib.h> // For malloc, free #include <stdio.h> // For debugging, can be removed char * longestCommonPrefix(char ** strs, int strsSize){ if (strsSize == 0) { return strdup(""); // Return empty string if no strings } // The longest common prefix cannot be longer than the shortest string. // Start with the first string as the initial potential prefix. char *prefix = strdup(strs[0]); // Duplicate to modify for (int i = 1; i < strsSize; i++) { int current_prefix_len = strlen(prefix); int current_str_len = strlen(strs[i]); int j = 0; // Find the length of the common prefix between `prefix` and `strs[i]` while (j < current_prefix_len && j < current_str_len && prefix[j] == strs[i][j]) { j++; } // Truncate the prefix to the common part found prefix[j] = '\0'; // Null-terminate at the new length if (strlen(prefix) == 0) { // If at any point the prefix becomes empty, there's no common prefix free(prefix); // Free the allocated memory return strdup(""); } } return prefix; // Return the final common prefix }
-
Detect Capital
🔗 LeetCode Link
📚 Tags: String, Case HandlingView Solutions
Python Solution
class Solution: def detectCapitalUse(self, word: str) -> bool: # Case 1: All letters are capitals (e.g., "USA") if word.isupper(): return True # Case 2: All letters are not capitals (e.g., "leetcode") elif word.islower(): return True # Case 3: Only the first letter is capital (e.g., "Google") elif word[0].isupper() and word[1:].islower(): return True else: return False # Alternatively, using built-in methods directly: # return word.isupper() or word.islower() or (word[0].isupper() and word[1:].islower())
Java Solution
class Solution { public boolean detectCapitalUse(String word) { int n = word.length(); if (n == 0) return true; // Empty string fits all rules int capitalCount = 0; for (char c : word.toCharArray()) { if (Character.isUpperCase(c)) { capitalCount++; } } if (capitalCount == n) { // All capitals (USA) return true; } else if (capitalCount == 0) { // All lowercase (leetcode) return true; } else if (capitalCount == 1 && Character.isUpperCase(word.charAt(0))) { // First letter capital (Google) return true; } return false; } }
C++ Solution
#include <string> #include <cctype> // For isupper, islower class Solution { public: bool detectCapitalUse(std::string word) { int n = word.length(); if (n == 0) return true; int capitalCount = 0; for (char c : word) { if (std::isupper(c)) { capitalCount++; } } if (capitalCount == n) { // All capitals return true; } else if (capitalCount == 0) { // All lowercase return true; } else if (capitalCount == 1 && std::isupper(word[0])) { // First letter capital return true; } return false; } };
C Solution
#include <stdbool.h> #include <string.h> #include <ctype.h> // For isupper bool detectCapitalUse(char * word){ int n = strlen(word); if (n == 0) return true; int capitalCount = 0; for (int i = 0; i < n; i++) { if (isupper(word[i])) { capitalCount++; } } if (capitalCount == n) { // All capitals return true; } else if (capitalCount == 0) { // All lowercase return true; } else if (capitalCount == 1 && isupper(word[0])) { // First letter capital return true; } return false; }
-
To Lower Case
🔗 LeetCode Link
📚 Tags: String, Character ConversionView Solutions
Python Solution
class Solution: def toLowerCase(self, s: str) -> str: return s.lower() # Python's built-in string method # Manual implementation (less efficient for long strings due to concatenation) # result = [] # for char_code in s: # if 'A' <= char_code <= 'Z': # result.append(chr(ord(char_code) + 32)) # Convert to lowercase ASCII # else: # result.append(char_code) # return "".join(result)
Java Solution
class Solution { public String toLowerCase(String s) { return s.toLowerCase(); // Java's built-in string method /* // Manual implementation StringBuilder sb = new StringBuilder(); for (char c : s.toCharArray()) { if (c >= 'A' && c <= 'Z') { sb.append((char)(c + 32)); // Convert to lowercase ASCII } else { sb.append(c); } } return sb.toString(); */ } }
C++ Solution
#include <string> #include <algorithm> // For std::transform #include <cctype> // For std::tolower class Solution { public: std::string toLowerCase(std::string s) { // Using std::transform with std::tolower std::transform(s.begin(), s.end(), s.begin(), ::tolower); return s; /* // Manual implementation for (char &c : s) { if (c >= 'A' && c <= 'Z') { c = c + 32; // ASCII conversion } } return s; */ } };
C Solution
#include <string.h> #include <ctype.h> // For tolower char * toLowerCase(char * s){ int i = 0; while (s[i] != '\0') { s[i] = tolower(s[i]); // Use tolower from ctype.h i++; } return s; }
-
Check If Two String Arrays are Equivalent
🔗 LeetCode Link
📚 Tags: Arrays, StringView Solutions
Python Solution
class Solution: def arrayStringsAreEqual(self, word1: list[str], word2: list[str]) -> bool: return "".join(word1) == "".join(word2)
Java Solution
class Solution { public boolean arrayStringsAreEqual(String[] word1, String[] word2) { StringBuilder sb1 = new StringBuilder(); for (String s : word1) { sb1.append(s); } StringBuilder sb2 = new StringBuilder(); for (String s : word2) { sb2.append(s); } return sb1.toString().equals(sb2.toString()); } }
C++ Solution
#include <string> #include <vector> class Solution { public: bool arrayStringsAreEqual(std::vector<std::string>& word1, std::vector<std::string>& word2) { std::string s1 = ""; for (const std::string& s : word1) { s1 += s; } std::string s2 = ""; for (const std::string& s : word2) { s2 += s; } return s1 == s2; } };
C Solution
#include <stdbool.h> #include <string.h> #include <stdlib.h> // For malloc, free bool arrayStringsAreEqual(char ** word1, int word1Size, char ** word2, int word2Size){ // Calculate total length for word1 int totalLen1 = 0; for (int i = 0; i < word1Size; i++) { totalLen1 += strlen(word1[i]); } // Calculate total length for word2 int totalLen2 = 0; for (int i = 0; i < word2Size; i++) { totalLen2 += strlen(word2[i]); } // If total lengths are different, strings cannot be equal if (totalLen1 != totalLen2) { return false; } // Concatenate word1 strings char *s1 = (char *) malloc(sizeof(char) * (totalLen1 + 1)); if (s1 == NULL) return false; // Handle allocation failure s1[0] = '\0'; // Initialize as empty string for (int i = 0; i < word1Size; i++) { strcat(s1, word1[i]); } // Concatenate word2 strings char *s2 = (char *) malloc(sizeof(char) * (totalLen2 + 1)); if (s2 == NULL) { free(s1); // Free s1 if s2 allocation fails return false; } s2[0] = '\0'; // Initialize as empty string for (int i = 0; i < word2Size; i++) { strcat(s2, word2[i]); } // Compare the concatenated strings bool result = (strcmp(s1, s2) == 0); // Free allocated memory free(s1); free(s2); return result; }
-
Goal Parser Interpretation
🔗 LeetCode Link
📚 Tags: String, ParserView Solutions
Python Solution
class Solution: def interpret(self, command: str) -> str: return command.replace("()", "o").replace("(al)", "al") # Manual approach # result = [] # i = 0 # while i < len(command): # if command[i] == 'G': # result.append('G') # i += 1 # elif command[i:i+2] == '()': # result.append('o') # i += 2 # elif command[i:i+4] == '(al)': # result.append('al') # i += 4 # return "".join(result)
Java Solution
class Solution { public String interpret(String command) { return command.replace("()", "o").replace("(al)", "al"); /* // Manual approach StringBuilder sb = new StringBuilder(); for (int i = 0; i < command.length(); ) { if (command.charAt(i) == 'G') { sb.append('G'); i++; } else if (command.charAt(i + 1) == ')') { // Must be "()" sb.append('o'); i += 2; } else { // Must be "(al)" sb.append("al"); i += 4; } } return sb.toString(); */ } }
C++ Solution
#include <string> class Solution { public: std::string interpret(std::string command) { std::string result = ""; for (int i = 0; i < command.length(); ) { if (command[i] == 'G') { result += 'G'; i++; } else if (i + 1 < command.length() && command[i+1] == ')') { // "()" result += 'o'; i += 2; } else { // "(al)" result += "al"; i += 4; } } return result; } };
C Solution
#include <string.h> #include <stdlib.h> // For malloc, realloc, free char * interpret(char * command){ int len = strlen(command); // Max possible length is original length (if all 'G') // Min possible length is len/4 * 2 (if all '(al)') char *result = (char *)malloc(sizeof(char) * (len + 1)); if (result == NULL) return NULL; int res_idx = 0; for (int i = 0; i < len; ) { if (command[i] == 'G') { result[res_idx++] = 'G'; i++; } else if (command[i] == '(' && command[i+1] == ')') { result[res_idx++] = 'o'; i += 2; } else if (command[i] == '(' && command[i+1] == 'a') { // (al) result[res_idx++] = 'a'; result[res_idx++] = 'l'; i += 4; } } result[res_idx] = '\0'; // Null-terminate the result string // Reallocate to exact size if desired, though often not necessary for LeetCode // char* final_result = (char*)realloc(result, sizeof(char) * (res_idx + 1)); // return final_result != NULL ? final_result : result; return result; }
-
Merge Strings Alternately
🔗 LeetCode Link
📚 Tags: Two Pointers, StringView Solutions
Python Solution
class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: result = [] i, j = 0, 0 n1, n2 = len(word1), len(word2) while i < n1 and j < n2: result.append(word1[i]) result.append(word2[j]) i += 1 j += 1 # Append remaining characters from word1, if any while i < n1: result.append(word1[i]) i += 1 # Append remaining characters from word2, if any while j < n2: result.append(word2[j]) j += 1 return "".join(result)
Java Solution
class Solution { public String mergeAlternately(String word1, String word2) { StringBuilder result = new StringBuilder(); int i = 0, j = 0; int n1 = word1.length(); int n2 = word2.length(); while (i < n1 || j < n2) { if (i < n1) { result.append(word1.charAt(i)); i++; } if (j < n2) { result.append(word2.charAt(j)); j++; } } return result.toString(); } }
C++ Solution
#include <string> #include <algorithm> // For std::min, std::max class Solution { public: std::string mergeAlternately(std::string word1, std::string word2) { std::string result = ""; int i = 0, j = 0; int n1 = word1.length(); int n2 = word2.length(); while (i < n1 || j < n2) { if (i < n1) { result += word1[i]; i++; } if (j < n2) { result += word2[j]; j++; } } return result; } };
C Solution
#include <string.h> #include <stdlib.h> // For malloc, free char * mergeAlternately(char * word1, char * word2){ int len1 = strlen(word1); int len2 = strlen(word2); int mergedLen = len1 + len2; char *result = (char *)malloc(sizeof(char) * (mergedLen + 1)); if (result == NULL) return NULL; int i = 0, j = 0, k = 0; // i for word1, j for word2, k for result while (i < len1 && j < len2) { result[k++] = word1[i++]; result[k++] = word2[j++]; } // Append remaining characters from word1 while (i < len1) { result[k++] = word1[i++]; } // Append remaining characters from word2 while (j < len2) { result[k++] = word2[j++]; } result[k] = '\0'; // Null-terminate the string return result; }
📘 Tips for Solving String Problems
- Use two-pointer techniques for problems involving reversal or palindromes.
- Practice using hash maps to count frequencies.
- Be mindful of case sensitivity and empty strings.
🚀 What’s Next?
Once you're comfortable with these easy problems, level up with medium difficulty string questions like:
- Longest Palindromic Substring
- Group Anagrams
- Longest Substring Without Repeating Characters
📌 We’ll post those in a separate blog soon. Stay tuned!
🔗 Internal Links
- Top 10 Easy DSA Questions Overall
- DSA for Beginners – Complete Guide
- String Manipulation in C++ and Java – Explained
📚 Conclusion
These string problems are perfect for interview prep, campus placement, or brushing up your basics. Practice them consistently and your foundation will become stronger day by day.
💬 Have a question or doubt? Drop a comment below or connect on GitHub or LinkedIn. Happy Coding!