Yes, C++ is a great choice for coding interviews as it allows you to demonstrate object-oriented and low-level programming proficiency. It also offers a wide range of data structures and algorithms that are useful for solving interview questions.
Crack the top 40 C++ coding interview questions
C++ is a popular OOP programming language used across the tech industry. Companies like Microsoft, LinkedIn, Amazon, and PayPal list C++ as their main programming language with others for coding interviews.
Overall, C++ is a must-have skill for modern developers interested in these large companies.
Today, we’ll go through the top 40 C++ coding interview questions used to test C++. By the end, you’ll have the confidence and hands-on experience to approach any C++ interview confidently.
Here’s what we’ll cover today:
Grokking Coding Interview Patterns in C++
With thousands of potential questions to account for, preparing for the coding interview can feel like an impossible challenge. Yet with a strategic approach, coding interview prep doesn’t have to take more than a few weeks. Stop drilling endless sets of practice problems, and prepare more efficiently by learning coding interview patterns. This course teaches you the underlying patterns behind common coding interview questions. By learning these essential patterns, you will be able to unpack and answer any problem the right way — just by assessing the problem statement. This approach was created by FAANG hiring managers to help you prepare for the typical rounds of interviews at major tech companies like Apple, Google, Meta, Microsoft, and Amazon. Before long, you will have the skills you need to unlock even the most challenging questions, grok the coding interview, and level up your career with confidence. This course is also available in JavaScript, Python, Go, and C++ — with more coming soon!
Solution Explanation
On line 6 in the outer loop, int i=1; runs once, i<n; gets executed times and i+=3 is executed
times.
In the inner loop, int j=1; gets executed times in total. j<n; executes times and j+=2 gets executed times.
For more information, see our line by line breakdown:
| Statement | Number of Executions |
|---|---|
int n = 10; |
1 |
int sum = 0; |
1 |
float pie = 3.14; |
1 |
int i=1; |
1 |
i<n; |
+ 1 |
i+=3 |
|
cout << pie << endl; |
|
int j=1; |
|
j<n; |
|
j+=2 |
|
sum += 1; |
|
cout << sum << endl; |
Added together, the runtime complexity is
Now convert this to Big O.
- Drop the leading constants:
- Drop lower order terms:
2. Nested Loop with Multiplication#
Find the Big O complexity of the following code:
int main() {
int n = 10; //n can be anything
int sum = 0;
float pie = 3.14;
int var = 1;
while (var < n){
cout << pie << endl;
for (int j=0; j<var; j++)
sum+=1;
var*=2;
}
cout<<sum;
}
Solution Explanation
| Statement | Number of executions |
|---|---|
int n = 10; |
1 |
int sum = 0; |
1 |
float pie = 3.14; |
1 |
int var = 1; |
1 |
while(var < n) |
2 |
cout << pie << endl |
2 |
int j=0; |
2 |
j<var; |
|
j++ |
|
sum+=1; |
|
var*=2; |
2 |
cout<<sum; |
1 |
Runtime complexity: 2
Big O:
3. Common mistakes with nested loop#
Find the Big O complexity of the following code:
for( int i=0; i<array.length; i++){
for(int j=0; j<10000; j++)
{
// some useful work done here.
}
}
Solution Explanation
This is a “gotcha” question that tests if you really understand Big O.
Even if they’re nested, the inner loop’s number of executions is not dependent on the input. It will always execute the same number of times.
A common mistake is to answer . Big O calculates for asymptotic behavior therefore, we remove constants like 10,000.
The correct answer is then .
Solution Explanation
The for loop from lines 6-8 calculates the average of the contents of the array. It’s complexity is .
The do-while loop from lines 14-24 is tricky. It may seem that the complexity is because of the nested loops.
In fact ,we have to account for two possibilities.
- The average calculated for the given input array also occurs in the array.
- The average is a float and doesn’t appear in the array.
If the average is a float then the nested while loop on lines 16-17 will increment the value of the variable j to the size of the input array. Also, the do-while condition will become false.
The complexity in this case will be
If the average does appear in the array and the array consists of all the same numbers, then the nested while loop of lines 16-17 will not run. The if clause of lines 20-23 will kick-in and increment j to the size of the array as the outer do-while loop iterates.
Hence the overall complexity of the snippet is .
5. Recursive Complexity#
Find the Big O complexity of the following code:
int recursiveFun1(int n)
{
if (n <= 0)
return 1;
else
return 1 + recursiveFun1(n-1);
}
int recursiveFun2(int n)
{
if (n <= 0)
return 1;
else
return 1 + recursiveFun2(n-5);
}
int recursiveFun3(int n)
{
if (n <= 0)
return 1;
else
return 1 + recursiveFun3(n/5);
}
void recursiveFun4(int n, int m, int o)
{
if (n <= 0)
{
printf("%d, %d\n",m, o);
}
else
{
recursiveFun4(n-1, m+1, o);
recursiveFun4(n-1, m, o+1);
}
}
int recursiveFun5(int n)
{
for (i = 0; i < n; i += 2) {
// do something
}
if (n <= 0)
return 1;
else
return 1 + recursiveFun5(n-5);
}
Solution
For this one, it’s best to break down the problem function by function.
int recursiveFun1(int n)
{
if (n <= 0)
return 1;
else
return 1 + recursiveFun1(n-1);
}
This function is called n times before reaching base case. It therefore has a Big O complexity of .
int recursiveFun2(int n)
{
if (n <= 0)
return 1;
else
return 1 + recursiveFun2(n-5);
}
This function is called n-5 times and simplifies to with Big O.
int recursiveFun3(int n)
{
if (n <= 0)
return 1;
else
return 1 + recursiveFun3(n/5);
}
The complexity here is because of every time we divide by 5 before calling the function.
void recursiveFun4(int n, int m, int o)
{
if (n <= 0)
{
printf("%d, %d\n",m, o);
}
else
{
recursiveFun4(n-1, m+1, o);
recursiveFun4(n-1, m, o+1);
}
}
Here the complexity is because each function calls itself twice unless recurred n times.
int recursiveFun5(int n)
{
for (i = 0; i < n; i += 2) {
// do something
}
if (n <= 0)
return 1;
else
return 1 + recursiveFun5(n-5);
}
Finally, the for loop executes times because i iterates by 2 and the recursion takes since the loop is called recursively.
Together, they have a complexity of or .
Data Structures#
6. Find the Smallest common number#
Problem statement:
“Given three integer arrays sorted in ascending order, return the smallest number that is common in all three arrays. Return -1 if there is no common number.”
Hints:
- The arrays are already sorted so their smallest element is at index 0.
- Use three pointers
Solution and Breakdown
Time complexity:
We use three iterators simultaneously to traverse each of the arrays. Each pointer starts at the 0th index because that is the smallest in the list.
The program first looks to see if the 0th element is shared. Then, we’ll return that value.
Otherwise, we’ll see which iterator amongst the three points to the smallest value and will increment that iterator so that it will point to the next index. We have found the solution when all iterators match.
If any of the three iterators reaches the end of the array before its finds a common number, we’ll return -1.
7. Move All Zeros to the Beginning of the Array#
Problem Statement
“Given an integer array, move all elements that are 0 to the left while maintaining the order of other elements in the array. The array must be modified in-place.”
Hints:
- Use reader/writer indexes
- You cannot use a simple chronological sort as elements other than zeros must maintain their position.
Solution and Breakdown
Time complexity:
We keep two markers: read_index and write_index. Both start pointed to the end of the array.
While moving read_index towards the start of the array:
If read_index points to 0, we that skip element.
If read_index points to a non-zero value, we write the value at read_index to the write_index and then decrement write_index.
Once read_index reaches the end of the array, we assign zeros based on the location of write_index. Any values on or before write_index must be zeros.
8. Reverse Even Nodes in a Linked List#
Problem Statement
“Given a singly linked list, reverse the nodes at even indices (starting at 1).”
Hint:
- Create a list for even numbers
Solution and breakdown
Time Complexity:
We will create two lists comprising of nodes at even and odd indices.
We avoid copying data of elements or reallocating memory to improve efficiency.
We push extracted nodes to the head of list_even to reverse their order while merging.
Once the two lists are in the correct order, we merge their nodes alternately to create our solution.
9. Sort a Linked List Using Merge Sort#
Problem Statement
“Given the head pointer of a linked sort, sort the linked list in ascending order using merge sort, and return the new head pointer of sorted linked list.”
Hint:
- Divide and Conquer
Solution and Breakdown
Time Complexity:
Mergesort is a commonly asked for in interviews. First, you divide the list into smaller lists, then sort each smaller list, and finally combine the sorted lists.
In the dividing step, we split our input linked list in half until there is a linked list of size 1 or 0. Linked lists of size 1 and 0 are always sorted.
In the combining step, we merge sorted lists until we have a completely sorted list.
10. Count of Palindromic Substrings#
Problem Statement
“Find the total number of palindromic substrings within a given string.”
Hint:
- This problem is a variation on the “Longest Subsequence” question type.
Solution and Breakdown
Time Complexity:
This solution uses a boolean table with a column for each letter. If the X and Y column are the same letter, the table returns that space as true. Otherwise, it returns false.
Here it is step-by-step:
- Maintain a boolean
table[n][n]filled from the bottom up. - If the substring is a palindrome, the value of
table[i][j]is true. Otherwise the value is false. - To calculate
table[i][j], we check the value oftable[i+1][j-1]. If the value is true andstr[i]is same asstr[j], then the substring is a palindrome and we maketable[i][j]true. - Otherwise, the value of
table[i][j]is made false. - We then fill the table that was previously for the substring of
length = 1andlength =2.
Answer any C++ interview problem by learning the patterns behind common questions
With thousands of potential questions to account for, preparing for the coding interview can feel like an impossible challenge. Yet with a strategic approach, coding interview prep doesn’t have to take more than a few weeks. Stop drilling endless sets of practice problems, and prepare more efficiently by learning coding interview patterns. This course teaches you the underlying patterns behind common coding interview questions. By learning these essential patterns, you will be able to unpack and answer any problem the right way — just by assessing the problem statement. This approach was created by FAANG hiring managers to help you prepare for the typical rounds of interviews at major tech companies like Apple, Google, Meta, Microsoft, and Amazon. Before long, you will have the skills you need to unlock even the most challenging questions, grok the coding interview, and level up your career with confidence. This course is also available in JavaScript, Python, Go, and C++ — with more coming soon!
11. Reverse Words in a Sentence#
Problem Statement
“Reverse the order of words in a given string.”
Hints:
- The problem asks for reversing word order, not letters within the word.
- Each word will be separated by spaces
Solution and Breakdown
Time Complexity:
The program works in two stages:
- Reverse the entire string
- Reverse each word in-place
Stage 2 works by setting a pointer for the beginning of the word, start, at the on element 0 or the first element after a space.
We also set another pointer for the end of the word, end, on the element right before the next space.
Both pointers then iterate toward each other, swapping values on each element.
Once the pointers are on the same element, the word has be correctly reversed and our pointers move to the next word.
Our program is complete once all words have been reversed back to their proper order.
12. Reverse First k Elements of Queue#
Problem Statement
“Implement the function myQueue reverseK(myQueue queue, int k) which takes a queue and a number k as input and reverses the first k elements of the queue.”
Solution and Breakdown
Time Complexity:
First we dequeue the first k elements from the front of the queue and push them in the stack we created on line 9 with stack.push(queue.dequeue()).
Once all the k values have been pushed to the stack, we start popping them and sequentially enqueuing them on line 14. We’ll queue them to the back using queue.enqueue(stack.pop()). At the end of this step, we will be left with an empty stack and the k reversed elements will be appended to the back of the queue.
Finally on line 19 we’ll move the resersed elements to the front of the queue usings queue.enqueue(queue.dequeue()). Each element is first dequeued from the back.
13. Zigzag Traversal#
Problem Statement:
"Given a binary tree, populate an array to represent its zigzag level order traversal.
You should populate the values of all nodes of the first level from left to right, then right to left for the next level, alternating in the same way for all levels."
Hints:
- This question is an iteration of the “Binary Tree Level Order Traversal” question type
Solution and Breakdown
Time Complexity:
- We start by pushing the
rootnode to the queue. - We then iterate through the queue until the queue is empty.
- In each iteration, we first count the elements in the queue (let’s call it
levelSize). We will have this many nodes in the current level. - Next, remove
levelSizenodes from the queue and push their value in an array to represent the current level. - After removing each node from the queue, insert both of its children into the queue.
- If the queue is not empty, flip the direction of the traversal and repeat from step 3 for the next level.
14. Determine if an Undirected Graph is a Tree#
Problem Statement:
“Create function bool isTree(Graph g) that takes a graph as input and returns if the passed graph is a tree.”
A graph is a tree if:
- There are no cycles.
- All nodes of the graph are reachable from all other nodes of the graph, directly or through traversal.
Hints:
- This can be solved using either Depth First Search or Breadth First Search
Solution and Breakdown
Time Complexity:
We have to check both conditions to determine if the graph is a tree.
To check the first condition, we start from the source and visit every adjacent vertex using recursive calls. If we come across any vertex that has already been visited and it is not the parent of the current vertex, then there is a cycle.
If we do not find such an adjacent for any vertex, we say that there is no cycle and the first condition is met.
For the second condition, we traverse all the vertices on the graph using recursive calls to check if they’re reachable from the source.
If we find any vertex that is not visited, we conclude that vertex is not reachable from the source. Therefore, the graph is not connected and does not met our second tree condition.
15. Word Formation From a Vector Using a Trie#
Problem Statement:
“Implement the isFormationPossible() function, which finds whether a given word can be formed by combining two elements from a vector.”
Solution and Breakdown
Time Complexity:
First, we’ll make a trie using the words passed in the C++ vector.
Then, we check if there is a word in the trie which can become a part for the searched word. In the case of “helloworld”, we can find “he” in the trie.
Since there can be multiple elements that would serve as each part of a word, we have to check for applicable part.
If we find a part of the word that matches our searched word, we lookup the remaining word in the trie using the searchNode function.
If this substring exists within our searched word, we have found a solution.
Recursion#
16. Shuffle an Array of Integers#
Problem Statement:
“Given an integer array of size n, create a program to recursively shuffle the array so no two elements remain next to each other. Do not use extra space in your solution.”
Hints:
- You can create the brute force solution first before refactoring to the recursive solution.
- Divide and Conquer
Solution and Breakdown
Time Complexity:
The program divides the given array into half (arr1[] and arr2[]) and then swaps the second element of arr1[] with the first element of arr2[].
Keep doing this recursively for all of arr1 and arr2.
We have a recursive utility function shuffleArrayRecursive() recursively called within the shuffler() function.
- Line 7-8: If there are only 2 elements, there is no need to do anything. This serves as the base case of our recursive call.
- Line 11-17: Divide the given array into two smaller subarrays of equal length, and find the middle of those subarrays.
- Line 20-21: Swap the elements from the right subarray (
arr1[]) to the left subarray (arr2[]). - Line 25-26: Make recursive calls to the function, with updated arguments, as calculated by finding the middle on Line 11-17.
17. Minimum Steps to Collect Coin Stacks#
Problem Statement:
“Given an integer arrays representing the height of each stack of coins and the number of coin stacks, calculate the minimum number of straight lines that pass through all the coins (minimum number of steps to collect these coins).”
Hints:
- Divide and Conquer
Solution and Breakdown
Time Complexity:
First we start horizontally from the bottom, we can get rid of the lowest coin row and collect the maximum possible number of coins since the bottom rows are guaranteed to be filled.
We’ll work on coin stacks from left, stackl, to right, stackr, in each recursion step.
Save the height of the smallest stack to m. Remove m horizontal lines, after which the stack will have two parts remaining: l to m and m + 1 to r. We’ll use these as subarrays.
We then make a recursive call on each subarray to repeat horizontal coin collection.
Since coins may also be collected using vertical lines, we then choose the minimum of the result of recursive calls and r – l.
Using (r – l) vertical lines, we can always collect all coins vertically.
18. Find the Number of Vowels in a String#
Problem Statement:
“Create a function totalVowels that takes a string text parameter and returns the number of vowels within the string.”
Solution and Breakdown
Time Complexity:
Provided that the length of the text string is not yet 0, we move to the recursive case.
The first step in the function is to create a count variable, set to 0 which will be incremented each time a vowel is found.
To keep uniformity, we take the element of text at position index and convert it to uppercase.
This reduces the different checks we will have in the subsequent if conditions.
Then we equate the changed element to a variable, single to keep the code clean.
The if condition checks if single is equal to any of the vowels. If it is, then it increments count by 1.
After that the return statement simply calls on the recursive function again, totalVowels(), adding the result of the subsequent recursive call to the last value of count.
Note that this time, the len is reduced by 1 and the index is incremented by 1 to avoid an infinite loop.
Solution and Breakdown
Time Complexity:
This problem follows the Fibonacci number pattern.
The only difference is that in Fibonacci numbers every number is a sum of the two preceding numbers, whereas in this problem every count is a sum of three preceding counts. Here is the recursive formula for this problem:
CountWays(n) = CountWays(n-1) + CountWays(n-2) + CountWays(n-3), for n >=3
We also recognized that we’d have several overlapping subproblems and thus created a memoization table to save time.
20. Largest Sum Subarray#
Problem Statement:
“Given an array, find the contiguous subarray with the largest sum.”
Hints:
- Use Kadane’s algorithm
- Your program only needs to return the sum of the values, not the indexes of the subarray.
Solution and Breakdown
Time Complexity:
Kadane’s algorithm scans the entire array and at each position finds the maximum sum of the subarray ending there.
This is achieved by keeping a current_max summing up to the current index and a global_max that contains the largest sum found by that point. Whenever current_max is greater than global_max, we set global_max to that new highest value.
Since the values must be contiguous, we can discontinue any possible combination if elements if the sum of the current subarray goes down i.e. we encounter a negative number.
20 more C++ interview questions#
- Rod Cutting Problem
- Rotate an Array of N Elements
- Stock Buy Sell to Maximize Profits
- Cyclic Sort
- Find K-Sum Subsets
- Search in a Sorted Infinite Array
- Reverse Alternate K Nodes in a Singly Linked List
- Kth Smallest Number in M Sorted Lists
- Find the Missing Number in a Linked List
- Minimum Deletions in a String to create a Palindrome
- Balanced Parentheses Problem
- Longest Substring with K Distinct Characters
- Convert Binary Tree to Doubly Linked List
- Sliding Window Median Problem
- Topological Sort a Graph
- Alien Dictionary Problem
- Prime Number Checker
- Find the Closest Pair of Points in Euclidean Space
- Knapsack Problem
- Equal Subset Sum Partition Problem
Wrapping up and next steps#
Congratulations on finishing those 40 questions!
The best way to prepare for coding interviews is the practice you’re doing right now. Soon, you’ll know all the question types you could encounter at your next interview.
To help you prepare for interviews, Educative has created the course Grokking Coding Interview Patterns in C++. You’ll learn the 24 patterns behind every coding interview question, so you can be prepared to answer any problem you might face using C++.
Simplify your coding interview prep today! Get a structured, pattern-based approach to solving any coding interview question, without having to drill endless practice problems.
Happy learning!
Continue reading about coding interviews#
Frequently Asked Questions
Is C++ good for coding interviews?
Is C++ good for coding interviews?
How to prepare for a C++ coding interview?
How to prepare for a C++ coding interview?