SyntaxPilot
Courses/C++ Coding Questions/Lesson 5
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C++ Coding Questions · Lesson 5 of 30

String questions I

reverse a string (two pointers, std::reverse)palindrome ignoring case and spaces (isalnum, tolower)count vowels and words; cin >> vs getline

These are the notes for C++ Coding Questions, episode 5, placement practice for people who finished the SyntaxPilot C++ course. Strings, part one: reversing a string (two pointers and std::reverse), checking a palindrome while ignoring case, spaces and punctuation, and counting vowels and words, with the input traps behind them: cin >> vs getline, and the leftover newline.

Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.

Every program was compiled with g++ -Wall -O2 -std=c++17 main.cpp -o main (g++ 13.3, Linux x86-64), the SyntaxPilot compiler's C++ command with warnings on, and every output below is real.

Real-life pictures

In real life In C++
A teacher says "stand in reverse order"; if every student swaps with their mirror partner, the second half swaps everyone back swapping s[i] and s[n-1-i] for every i leaves the string unchanged
One student at the front and one at the back swap, step inwards, and stop when they meet two pointers l and r, while (l < r)
Malayalam, Nitin, Never odd or even read the same both ways once you ignore case and spaces a palindrome check with isalnum and tolower
Count the people in a queue, not the gaps between them count words, not spaces

Two input tools: cin >> and getline

cin >> s getline(cin, s)
reads one word one whole line
spaces skips them before the word, stops at the next one keeps them
the newline at the end left in the input read and thrown away
on hello world "hello" "hello world"

Q1: Reverse a line of text

Problem. Read a line and print it backwards.

Input Output
hello world dlrow olleh
ab ba
x x
(empty line) (empty line)

Edge cases: spaces inside the line, one letter, an empty line.

The obvious attempt

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s;
    cin >> s;
    int n = s.size();
    for (int i = 0; i < n; i++)
        swap(s[i], s[n - 1 - i]);
    cout << s << "\n";
    return 0;
}

Input hello world:

hello

Two bugs.

  1. cin >> s reads one word: it stops at the space, so s is only "hello".
  2. The loop swaps s[i] with s[n - 1 - i] for every i. The first half reverses the string; the second half swaps every pair back. (Run it on one word: hello → hello.)

Fix: getline and two pointers

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s;
    getline(cin, s);
    int l = 0, r = (int)s.size() - 1;
    while (l < r) {
        swap(s[l], s[r]);
        l++;
        r--;
    }
    cout << s << "\n";
    return 0;
}

Input hello world:

dlrow olleh

l starts at the front, r at the back; swap, step both inwards, stop when they meet. Each pair is swapped once.

Why (int)s.size() - 1? s.size() returns an unsigned type (size_t). For an empty string, s.size() - 1 would wrap around to a huge number (18446744073709551615). Casting to int first gives −1, and while (0 < -1) simply doesn't run.

The library: std::reverse

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main() {
    string s;
    while (getline(cin, s)) {
        reverse(s.begin(), s.end());
        cout << "[" << s << "]\n";
    }
    return 0;
}

Input (5 lines: hello world, ab, x, an empty line, I love chai):

[dlrow olleh]
[ba]
[x]
[]
[iahc evol I]

reverse(first, last) from <algorithm> reverses any range in place. The brackets show the empty line clearly.

Complexity: O(n) time (each character moves once), O(1) extra space (in place).

Q2: Palindrome, ignoring case and spaces

Problem. For each line, print whether it is a palindrome when only letters and digits count and upper and lower case are the same.

Input Output
madam palindrome
Malayalam palindrome
Never odd or even palindrome
A man, a plan, a canal: Panama palindrome
hello not

Edge cases: an empty line, only punctuation (!!), two letters.

The obvious attempt: compare with the reverse

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main() {
    string s;
    while (getline(cin, s)) {
        string t = s;
        reverse(t.begin(), t.end());
        cout << s << (s == t ? " -> palindrome\n" : " -> not\n");
    }
    return 0;
}

Input:

madam -> palindrome
Malayalam -> not
Never odd or even -> not
A man, a plan, a canal: Panama -> not

Why: 'M' and 'm' are different characters (codes 77 and 109), and spaces and punctuation are compared too.

Clean it first: isalnum and tolower (from <cctype>)

Function Returns
isalnum(c) non-zero if c is a letter or digit
isalpha(c) / isdigit(c) letter / digit
isupper(c) / islower(c) capital / small letter
tolower(c) / toupper(c) the small / capital version (other characters unchanged), as an int

Attempt: print the cleaned string

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main() {
    string s;
    getline(cin, s);
    for (char c : s)
        if (isalnum(c)) cout << tolower(c);
    cout << "\n";
    return 0;
}

Input Never odd:

110101118101114111100100

Why: tolower comes from C: it takes and returns an int, the character's code. cout << int prints the number: 'n' = 110, 'e' = 101, 'v' = 118, ...

Fix: char(tolower(c)). And pass (unsigned char)c: a char can be negative (for example bytes of non-English text), and passing a negative value other than EOF to these functions is undefined behaviour.

Fix: build a clean copy and compare

#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
using namespace std;

int main() {
    string s;
    while (getline(cin, s)) {
        string clean = "";
        for (char c : s)
            if (isalnum((unsigned char)c)) clean += char(tolower((unsigned char)c));
        string t = clean;
        reverse(t.begin(), t.end());
        cout << clean << (clean == t ? " -> palindrome\n" : " -> not\n");
    }
    return 0;
}

Input (the four lines and hello):

madam -> palindrome
malayalam -> palindrome
neveroddoreven -> palindrome
amanaplanacanalpanama -> palindrome
hello -> not

Correct, but it builds two extra strings per line: O(n) extra memory.

Better: two pointers that skip

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

bool isPal(const string& s) {
    int l = 0, r = (int)s.size() - 1;
    while (l < r) {
        unsigned char a = s[l], b = s[r];
        if (!isalnum(a)) { l++; continue; }
        if (!isalnum(b)) { r--; continue; }
        if (tolower(a) != tolower(b)) return false;
        l++;
        r--;
    }
    return true;
}

int main() {
    string s;
    while (getline(cin, s))
        cout << "[" << s << "]" << (isPal(s) ? " -> palindrome\n" : " -> not\n");
    return 0;
}

Input (Malayalam, Never odd or even, A man, a plan, a canal: Panama, hello, an empty line, !!, ab):

[Malayalam] -> palindrome
[Never odd or even] -> palindrome
[A man, a plan, a canal: Panama] -> palindrome
[hello] -> not
[] -> palindrome
[!!] -> palindrome
[ab] -> not

Skip what isn't a letter or digit from either side, compare the rest in lower case, step inwards. An empty line or only punctuation counts as a palindrome (nothing to compare), which is the usual convention (LeetCode 125). O(n) time, O(1) extra space.

Q3: Count vowels and words

Problem. Read t, then t lines. For each line print the number of vowels (a, e, i, o, u in either case) and the number of words.

Line Vowels Words
I love chai 5 3
Chai is hot 4 3
OK 1 1

The obvious attempt

#include <iostream>
#include <string>
using namespace std;

int main() {
    int t;
    cin >> t;
    while (t--) {
        string s;
        getline(cin, s);
        int vowels = 0, spaces = 0;
        for (char c : s) {
            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') vowels++;
            if (c == ' ') spaces++;
        }
        cout << "vowels " << vowels << ", words " << spaces + 1 << "\n";
    }
    return 0;
}

Input:

3
I love chai
  Chai   is  hot  
OK

Output:

vowels 0, words 1
vowels 4, words 3
vowels 4, words 10

Three bugs.

  1. The leftover newline. cin >> t reads 3 and stops before the newline. The first getline reads the rest of that line: an empty string. Every line shifts by one and OK is never read.
  2. Capital vowels. 'I' is not 'i': compare tolower(c).
  3. Words ≠ spaces + 1. Leading, trailing and repeated spaces: 9 spaces is not 10 words. Count the words themselves.

Fix: cin.ignore(), tolower, and stringstream

#include <iostream>
#include <string>
#include <sstream>
#include <cctype>
using namespace std;

int main() {
    int t;
    cin >> t;
    cin.ignore();
    while (t--) {
        string s;
        getline(cin, s);
        int vowels = 0;
        for (char c : s) {
            char lc = tolower((unsigned char)c);
            if (lc == 'a' || lc == 'e' || lc == 'i' || lc == 'o' || lc == 'u') vowels++;
        }
        stringstream ss(s);
        string word;
        int words = 0;
        while (ss >> word) words++;
        cout << "vowels " << vowels << ", words " << words << "\n";
    }
    return 0;
}

Same input:

vowels 5, words 3
vowels 4, words 3
vowels 1, words 1

Input 2 / (empty line) / AEIOU aeiou:

vowels 0, words 0
vowels 10, words 2
  • cin.ignore() throws away one character: the newline left by cin >> t. (If the line after the number might contain extra spaces, cin.ignore(numeric_limits<streamsize>::max(), '\n') from <limits> throws away everything up to and including the newline.)
  • stringstream ss(s) (from <sstream>) lets you read from a string exactly like from cin. ss >> word skips any number of spaces and reads one word, so while (ss >> word) words++; counts words correctly.

Complexity: O(n) time per line; O(1) for the vowels, O(n) for the stringstream's copy of the line.

Complexity summary

Program Time Extra space
reverse, two pointers / std::reverse O(n) O(1)
palindrome, clean copy + reverse O(n) O(n)
palindrome, two pointers that skip O(n) O(1)
vowels, one pass O(n) O(1)
words, stringstream O(n) O(n)

Common mistakes (and the real results)

Mistake What you see Why Fix
cin >> s; for a line only hello >> stops at a space getline(cin, s)
swap s[i], s[n-1-i] for every i the string is unchanged each pair swapped twice while (l < r)
s.size() - 1 on an empty string a huge number size() is unsigned (int)s.size() - 1
compare s with its reverse Malayalam -> not case, spaces count isalnum, tolower
cout << tolower(c); 110101118... tolower returns an int char(tolower((unsigned char)c))
cin >> t; then getline the first line is empty the newline is left behind cin.ignore();
words = spaces + 1 10 words for 3 extra spaces stringstream >> word

Your turn: capitalise every word (solution)

Problem. Make the first letter of every word a capital and the rest small, keeping the spaces exactly.

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main() {
    string s;
    while (getline(cin, s)) {
        for (int i = 0; i < (int)s.size(); i++) {
            unsigned char c = s[i];
            bool starts = (i == 0 || s[i - 1] == ' ');
            s[i] = starts ? char(toupper(c)) : char(tolower(c));
        }
        cout << s << "\n";
    }
    return 0;
}

Input i LOVE chai / hello WORLD / x:

I Love   Chai
Hello World
 X

A character starts a word if it is the first one or the one before it is a space. toupper on a space leaves it alone. O(n) time, O(1) extra space.

Practice questions (with solutions)

1. Reverse only the vowels (hello → holle). Two pointers that skip consonants.

Solution
#include <iostream>
#include <string>
#include <cctype>
#include <utility>
using namespace std;

bool isVowel(char c) {
    char lc = tolower((unsigned char)c);
    return lc == 'a' || lc == 'e' || lc == 'i' || lc == 'o' || lc == 'u';
}

int main() {
    string s;
    while (getline(cin, s)) {
        int l = 0, r = (int)s.size() - 1;
        while (l < r) {
            if (!isVowel(s[l])) { l++; continue; }
            if (!isVowel(s[r])) { r--; continue; }
            swap(s[l], s[r]);
            l++;
            r--;
        }
        cout << s << "\n";
    }
    return 0;
}

Input hello / SyntaxPilot / chai:

holle
SyntoxPilat
chia

2. Count upper case, lower case, digits and other characters.

Solution
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main() {
    string s;
    getline(cin, s);
    int upper = 0, lower = 0, digits = 0, other = 0;
    for (char ch : s) {
        unsigned char c = ch;
        if (isupper(c)) upper++;
        else if (islower(c)) lower++;
        else if (isdigit(c)) digits++;
        else other++;
    }
    cout << "upper " << upper << ", lower " << lower << ", digits " << digits << ", other " << other << "\n";
    return 0;
}

Input Chai at 5 PM, OK?:

upper 5, lower 5, digits 1, other 6

3. Is one string the reverse of another? Compare a[i] with b[n - 1 - i], no copy needed.

Solution
#include <iostream>
#include <string>
using namespace std;

bool isReverseOf(const string& a, const string& b) {
    if (a.size() != b.size()) return false;
    int n = a.size();
    for (int i = 0; i < n; i++)
        if (a[i] != b[n - 1 - i]) return false;
    return true;
}

int main() {
    string a, b;
    while (cin >> a >> b)
        cout << a << " " << b << (isReverseOf(a, b) ? " -> yes\n" : " -> no\n");
    return 0;
}

Input abc cba chai iahc ab abc:

abc cba -> yes
chai iahc -> yes
ab abc -> no

Mini project: a line analyser

For each line: words, vowels, the reversed line, and whether it is a palindrome.

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
using namespace std;

bool isPal(const string& s) {
    int l = 0, r = (int)s.size() - 1;
    while (l < r) {
        unsigned char a = s[l], b = s[r];
        if (!isalnum(a)) { l++; continue; }
        if (!isalnum(b)) { r--; continue; }
        if (tolower(a) != tolower(b)) return false;
        l++;
        r--;
    }
    return true;
}

int main() {
    int t;
    cin >> t;
    cin.ignore();
    while (t--) {
        string s;
        getline(cin, s);
        int vowels = 0;
        for (char c : s) {
            char lc = tolower((unsigned char)c);
            if (lc == 'a' || lc == 'e' || lc == 'i' || lc == 'o' || lc == 'u') vowels++;
        }
        stringstream ss(s);
        string word;
        int words = 0;
        while (ss >> word) words++;
        string rev = s;
        reverse(rev.begin(), rev.end());
        cout << "[" << s << "] words " << words << ", vowels " << vowels
             << ", reversed [" << rev << "], " << (isPal(s) ? "palindrome" : "not a palindrome") << "\n";
    }
    return 0;
}

Input 2 / Never odd or even / I love chai (with extra spaces):

[Never odd or even] words 4, vowels 6, reversed [neve ro ddo reveN], palindrome
[  I love   chai ] words 3, vowels 5, reversed [ iahc   evol I  ], not a palindrome

Quick quiz

#include <iostream>
#include <string>
using namespace std;

int main() {
    int n;
    string s;
    cin >> n;
    getline(cin, s);
    cout << n << " [" << s << "]\n";
    return 0;
}

Input:

5
chai time

(A) 5 [] (B) 5 [chai time] (C) 5 [chai] (D) a compile error

Answer

(A) 5 []. cin >> n reads 5 and leaves the newline; getline reads up to that newline: an empty string. With cin.ignore(); before getline it prints 5 [chai time].

Output:

5 []

Interview questions

  1. Difference between cin >> s and getline(cin, s)? >> reads one word (stops at whitespace, leaves the newline); getline reads the whole line and consumes the newline.
  2. Why does getline after cin >> n return an empty string? The newline after the number is still in the input; use cin.ignore() (or getline(cin >> ws, s) if empty lines don't matter).
  3. Reverse a string in place. Two pointers swapping until they meet, or std::reverse. O(n), O(1).
  4. Check a palindrome ignoring non-alphanumeric characters with O(1) memory. Two pointers that skip with isalnum and compare with tolower.
  5. Why does cout << tolower('A') print 97? tolower returns an int; cast with char(...).
  6. Why cast to unsigned char before isalnum/tolower? A negative char is undefined behaviour for the <cctype> functions.
  7. Count words in a sentence with irregular spaces. stringstream and >>, or count the positions where a non-space follows a space (or the start).
  8. What does std::reverse need? Two bidirectional iterators: reverse(s.begin(), s.end()).

Glossary

Term Meaning Example
String A sequence of characters (std::string) "hello"
Character code The number a character is stored as (ASCII) 'a' = 97, 'n' = 110
Two pointers Two indexes moving through the data, often from both ends towards each other l and r
In place Changing the data itself, without a copy reverse(s.begin(), s.end())
std::reverse Reverses a range, from <algorithm> reverse(s.begin(), s.end())
Palindrome Reads the same forwards and backwards Malayalam, Nitin
Alphanumeric A letter or a digit isalnum('7') is true
<cctype> C header with isalnum, isdigit, tolower, toupper #include <cctype>
tolower / toupper Small / capital version of a character, returned as int char(tolower('N')) = 'n'
getline(cin, s) Read a whole line including spaces "hello world"
cin >> Read one whitespace-separated value "hello"
Whitespace Spaces, tabs and newlines ' ', '\t', '\n'
Leftover newline The '\n' that cin >> leaves in the input getline then reads ""
cin.ignore() Throw away the next input character after cin >> t
stringstream A string you can read from like cin, from <sstream> stringstream ss(s); ss >> word;
size_t The unsigned type size() returns s.size() - 1 wraps on ""
Vowel a, e, i, o, u (either case) 5 in "I love chai"
O(n) Work grows in step with the length one pass over the string
O(1) extra space A fixed amount of memory, whatever the input size two indexes

Summary

  • getline(cin, s) reads a whole line; cin >> s reads one word. After cin >> t, call cin.ignore() before getline.
  • Reverse with two pointers that stop when they meet (while (l < r)), or std::reverse. Swapping every pair undoes itself.
  • Palindrome ignoring case and spaces: two pointers that skip non-isalnum characters and compare tolower. tolower returns an int: wrap it in char(...) and pass (unsigned char)c.
  • Words: count them with stringstream >> word, not spaces + 1.

Next episode: String questions II: anagram check (sorting vs a counting array), the first non-repeating character, and the frequency of every character (map vs array).