Welcome to the first of a series of tutorials on C++ interview questions. In this series, I will be documenting various problems and my solutions to them, as well as my reasoning and explanation of the code written. I do not assume programming expertise, but as I will not be going over basic syntax, the ability to understand basic code is necessary to follow these tutorials. These should not be taken as the only way to solve a problem, but rather just my solution to the problem. All of the solution code can be found on my GitHub here. Part 1 focuses on string-related problems that you might come across for an interview.


Reversing Strings

Our first problem will be an approach to string reversal. This one is a simple and straightforward problem. Here's a look at the code:

#include <cstdio>
#include <string> // we will be using the C++ STL string object

using namespace std;

int main()
{	// string to be reversed
	string str = "Reverse me.";

	/*  begin iterating through string
		we will start with the length of the string minus one, and iterate backwards through each char
	*/
	for (int i = str.length() - 1; i >= 0; i--)
	{
		// print the resulting char in the string at index i
		printf("%c", str[i]);
	}

	return 0;
}

We first declare our string str to be reversed, then using a for loop, we set our iterator to the length of the string minus one (strings start from 0 just like an array, do not forget this if you are taking a pre-employment assessment!), and begin counting down. All we need to do is print the results at str[i] and our output will be our string reversed.

Something to note: we could store this string in a variable if we so chose, but for simplicity's sake I opted just to print the result instead. We will be seeing an example of storing the string and using the data next, however.


Testing If a String is a Palindrome

A palindrome is any string of characters which, when spelled backwards or forwards, is the same. Now that we've seen reversing strings, we can easily test if a string is a palindrome. Here's an example:

#include <iostream>
#include <string> // we will be using the C++ STL string object

using namespace std;

string reverse_string(string &str) {

	string reversed;

	/*  begin iterating through string
	we will start with the length of the string minus one, and iterate backwards through each char
	*/
	for (int i = str.length() - 1; i >= 0; i--)
	{
		// store current char in the sequence at the back of the reversed string
		reversed.push_back(str[i]);
	}

	return reversed;
}

int main()
{
	string test_string = "tacocat";
	string other_test = "not palindrome";

	if (test_string == reverse_string(test_string))
	{
		puts("test_string is a palindrome");
	}
	else
	{
		puts("test_string is not a palindrome");
	}

	
	return 0;
}

This time, I've separated out the reversal portion into its own function reverse_string(). The function takes a reference to a string &str so that our loop does not have to copy the string, and can save us a little memory. We use the same technique, only this time instead of directly printing the reversal we are storing the results in our local variable reversed to be returned. Back in our main() function, we set up our string to be tested, and a simple if branch allows us to check if the string is a match or not.


Count Repeated Characters of a String

In this practice, we're going to count all of the characters in a string. So for an example input string "Hello"  we should expect the output: h: 1 e: 1 l: 2 o: 1. Firstly we will declare our necessary variables:

string repeat = "Count all of my chars"; // string to be tested
map<char, int> chars; // associative array for holding key:value pairs of chars and the num of times they are repeated
map<char, int>::iterator it; // iterator for searching map for specific chars

We have our string, as well as a map of chars. A map is a data structure which holds key/value pairs such as a name and age: 'John Doe' : 31. This is the perfect structure to allow us to map each character to a value. We also declare at iterator to search through our map in order to determine if we have found a character, or reached the end of the map.  Now we will loop over the string and begin storing our data:

// begin iterating through each char (c) of repeat
for (char &c : repeat) {
	// search for current char
	it = chars.find(c);
 
	if (it != chars.end()) { // char is found
		it->second++;
	}
	else {
		chars.insert(std::pair<char, int>(c, 1)); // first instance of this char found, insert char to map with a value of 1
	}
}

We are using a direct loop over each char in the string repeat. We set out iterator it to find the current char. If it does not return an iterator to the end of the map, then we have found our char so we can increment the value second (in C++ maps, the data member second refers to the value of the current element in the map and first would refer to the key). If our iterator does reach the end, then we can insert the char into the map as a pair, with a value of 1.

The last thing we need to do is iterate over our map, and stream the data to output:

for (const auto &key : chars) {
		cout << "Character: " << key.first << " " << "Count: " << key.second << "\n";
	}

Here is what the entire program looks like:

#include <cstdio>
#include <iostream>
#include <string>
#include <map>
using namespace std;
 
int main()
{
	string repeat = "Count all of my chars"; // string to be tested
	map<char, int> chars; // associative array for holding key:value pairs of chars and the num of times they are repeated
	map<char, int>::iterator it; // iterator for searching map for specific chars
	
	// begin iterating through each char (c) of repeat
	for (char &c : repeat) {
		// search for current char
		it = chars.find(c);
 
		if (it != chars.end()) { // char is found
			it->second++;
		}
		else {
			chars.insert(std::pair<char, int>(c, 1)); // first instance of this char found, insert char to map with a value of 1
		}
	}
 
	for (const auto &key : chars) {
		cout << "Character: " << key.first << " " << "Count: " << key.second << "\n";
	}
 
	return 0;
}

We've taken a good look at a few string problems, and hopefully this will get us thinking about how to tackle various other string operations that we might come across in an interview or pre-employment assessment. I'll be adding a Part 2 interview series on a topic to be determined next. Stay tuned, and keep practicing.