Skip to content
DSA interview 11 min read

Top String Interview Questions with Solutions (C++, Java, JS, Python)

This page gathers the string interview questions that interviewers reach for most: anagrams, palindromes, sliding-window substring problems, and stack-based parsing. Each entry gives the problem, the approach, the complexity, and a full solution in C++, Java, JavaScript, and Python via the language switcher. New to strings as a data structure? Start with the strings introduction.

Pattern preview: Most string questions reduce to four ideas — frequency counting with a hash map, two pointers from both ends, a sliding window for substrings, and a stack for matching. Spot the pattern and the code writes itself.

1. Valid Anagram

Question. Given two strings s and t, return true if t is an anagram of s (same characters, same counts).

Approach. If the lengths differ they cannot match. Otherwise count characters in s, then decrement while scanning t; any count going negative means a mismatch.

Complexity. O(n) time, O(1) space for a fixed alphabet (O(k) for k distinct characters).

#include <string>
#include <unordered_map>

bool isAnagram(const std::string& s, const std::string& t) {
    if (s.size() != t.size()) return false;
    std::unordered_map<char, int> cnt;
    for (char c : s) cnt[c]++;
    for (char c : t) if (--cnt[c] < 0) return false;
    return true;
}

2. Valid Palindrome

Question. Return true if a string is a palindrome considering only alphanumeric characters and ignoring case.

Approach. Two pointers from both ends. Skip non-alphanumeric characters, then compare lowercased characters; move inward.

Complexity. O(n) time, O(1) space.

#include <string>
#include <cctype>

bool isPalindrome(const std::string& s) {
    int i = 0, j = (int)s.size() - 1;
    while (i < j) {
        while (i < j && !std::isalnum((unsigned char)s[i])) i++;
        while (i < j && !std::isalnum((unsigned char)s[j])) j--;
        if (std::tolower((unsigned char)s[i]) != std::tolower((unsigned char)s[j]))
            return false;
        i++; j--;
    }
    return true;
}

3. Longest Substring Without Repeating Characters

Question. Find the length of the longest substring with all distinct characters.

Approach. A sliding window. Track the last index where each character appeared; when you hit a repeat that lies inside the window, jump the window’s start just past it. The window [start, i] is always duplicate-free.

Complexity. O(n) time, O(k) space (k distinct characters).

#include <string>
#include <unordered_map>
#include <algorithm>

int lengthOfLongestSubstring(const std::string& s) {
    std::unordered_map<char, int> last;
    int best = 0, start = 0;
    for (int i = 0; i < (int)s.size(); i++) {
        auto it = last.find(s[i]);
        if (it != last.end() && it->second >= start) start = it->second + 1;
        last[s[i]] = i;
        best = std::max(best, i - start + 1);
    }
    return best;
}

4. Group Anagrams

Question. Group a list of strings so that anagrams of each other land in the same group.

Approach. Two anagrams share a sorted-character signature. Use that sorted string as a hash-map key and bucket each word under it.

Complexity. O(n · k log k) time for n words of length up to k, O(n · k) space.

#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>

std::vector<std::vector<std::string>> groupAnagrams(std::vector<std::string>& strs) {
    std::unordered_map<std::string, std::vector<std::string>> groups;
    for (const std::string& s : strs) {
        std::string key = s;
        std::sort(key.begin(), key.end());
        groups[key].push_back(s);
    }
    std::vector<std::vector<std::string>> res;
    for (auto& kv : groups) res.push_back(kv.second);
    return res;
}

5. Valid Parentheses

Question. Given a string of ()[]{}, decide if every bracket is closed by the correct type in the correct order.

Approach. Use a stack. Push opening brackets; on a closing bracket, the top must be its matching opener. The string is valid only if the stack ends empty.

Complexity. O(n) time, O(n) space.

#include <string>
#include <stack>
#include <unordered_map>

bool isValid(const std::string& s) {
    std::stack<char> st;
    std::unordered_map<char, char> match = {{')', '('}, {']', '['}, {'}', '{'}};
    for (char c : s) {
        if (c == '(' || c == '[' || c == '{') st.push(c);
        else {
            if (st.empty() || st.top() != match[c]) return false;
            st.pop();
        }
    }
    return st.empty();
}

6. Reverse Words in a String

Question. Reverse the order of words in a sentence, collapsing extra spaces (" the sky ""sky the").

Approach. Split on whitespace, drop empties, reverse the list, and re-join with single spaces.

Complexity. O(n) time, O(n) space.

#include <string>
#include <sstream>
#include <vector>
#include <algorithm>

std::string reverseWords(const std::string& s) {
    std::istringstream iss(s);
    std::vector<std::string> words;
    std::string w;
    while (iss >> w) words.push_back(w);
    std::reverse(words.begin(), words.end());
    std::string res;
    for (size_t i = 0; i < words.size(); i++) {
        if (i) res += ' ';
        res += words[i];
    }
    return res;
}

7. Longest Common Prefix

Question. Find the longest common prefix shared by an array of strings (empty if none).

Approach. Start with the first string as the candidate prefix; for each remaining string, shrink the prefix to the matching leading characters. Stop early if it becomes empty.

Complexity. O(n · m) time for n strings of length up to m, O(1) extra space.

#include <vector>
#include <string>

std::string longestCommonPrefix(const std::vector<std::string>& strs) {
    if (strs.empty()) return "";
    std::string prefix = strs[0];
    for (size_t i = 1; i < strs.size(); i++) {
        size_t j = 0;
        while (j < prefix.size() && j < strs[i].size() && prefix[j] == strs[i][j]) j++;
        prefix = prefix.substr(0, j);
        if (prefix.empty()) break;
    }
    return prefix;
}

Pitfall: With Unicode, “characters” are not bytes — a fixed 26-slot count or a naive index can break on accented or emoji input. Clarify the alphabet during the interview and prefer a hash map when in doubt.

Keep practicing

You now have the core string toolkit: frequency counts, two pointers, sliding windows, sorted-signature hashing, and stacks. Practice more on the string exercises, then tackle tree & graph interview questions.

Last updated June 25, 2026
Was this helpful?