Are you preparing for an upcoming programming interview? Here we have compiled a list of general programming interview questions that will help you prepare. Every year, thousands of computer science graduates face technical interviews organized by IT companies for the role of senior and junior developers.
Programming interviews are designed to test the developer's proficiency in data structures, algorithms, logic building, and problem-solving rather than just knowledge of a specific programming language.
Programming Interview Questions
In the following section, we will discuss top programming interview questions and answers, which will give you a good idea of what type of software developer interview questions you can expect during an interview. These Interview Questions and Answers are divided into the following three categories:
- Basic Programming Interview Questions
- Intermediate Programming Interview Questions
- Advanced Programming Interview Questions
Basic Programming Interview Questions
1. Name the most common errors that can occur during the execution of a program?
- Logical Error: If there is a mistake in the program source code, it could lead to a logical error. If there is a logical error in the program, then the program's output could show unexpected behavior or crash the program. For instance, if we use if (x=1) instead of if (x==1), this could raise a logical error.
- Runtime Error: This type of error occurs during runtime; thus, it is also known as a compile-time error. The logical error is an example of a runtime error.
- Syntax Error: This error occurs when there is a mistake while writing code. For instance, a syntax error results when the developer forgets to put a semicolon at the end of the statement or closes a bracket.
2. What is the difference between syntax and semantic errors?
A syntax error occurs if there is a grammatical mistake in the code. This means that if the code does not follow the writing rules of the program, then there would be a syntax error. If there is a syntax error in the program, the code will not compile.
Syntax Error Example:
for(int i=0; i< 10; i++)
{
cout<<i;
cout<<endl;
// syntax error because there are no closing curly brackets
A semantic error occurs during the execution of the code and after the code compilation. If the program returns an unexpected output, this means there is a semantic error in the code. Some examples of semantic errors are incorrect variable types or sizes, non-existent variables, and subscripts out of range.
Semantic Error Example:
void fun (int a)
{ a=b;
}
// We have not defined b
3. How do you define an algorithm?
An algorithm is a finite set of steps or instructions that can be used to solve a problem. An algorithm should be clear, efficient, unambiguous, and finite.
4. What is a low-level programming language?
Low-level programming requires no translator, such as a compiler or interpreter, and the system processor can directly execute its code. Machine code (or binary code) and assembly code are examples of low-level programming.
5. What is a high-level programming language?
A high-level programming language is a human-readable language and does require a translator so that the system processor can execute it.
6. What are keywords?
Keywords are the reserved words used in programming languages that perform specific tasks. Each programming language has a set of reserved keywords. For instance, C++ has 64 keywords, Java has 51 keywords, and Python has 33 keywords.
7. What are loops?
A loop is a basic structure in every high-level programming language that is used to repeat a defined set of statements repeatedly until the condition becomes false. There are three major types of loops in programming:
1. for Loop Example:
for(int i=0; i<10; i++)
{
cout<<i;
cout<<endl;
}
2. while Loop
int i=0;
while( i < 10) {
cout <<i;
cout<<endl;
a++;
}
3. do while Loop
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 10);
8. What is an array?
An array is a collection of similar elements where each element is stored sequentially. Arrays use indexing to access every element, and the indexing starts from 0 and goes up to n-1, where n is the total number of elements present in the array.
9. What is debugging?
It removes all the errors and exceptions that occurred in the program during the compile-time or runtime.
10. What is the difference between break and continue statements?
break | continue |
It ends or terminates the complete loop. | It skips only one iteration. |
Break takes execution out of the loop. | Program execution remains in the loop until the loop condition becomes false. |
It can be used when we have a specific condition from the loop and do not want more iterations. | The continue statement is used when we want to skip some specific conditions inside the loop. |
It can be used with switch statements. | Continue can not be used with switch statements. |
11. What are identifiers?
Identifiers are the names given by the programmer to program elements, such as variable names, class names, and function names. There are some specific sets of rules - depending on the chosen programming language - that the developers need to follow while naming a program element.
12. Can we use a keyword as an identifier?
No, we cannot use a keyword as an identifier. If we try to do so, then the compiler will throw a syntax error.
13. What are arithmetic operators, and on which data type can they operate?
Arithmetic operators perform operations on numeric data types, such as integers, float, and doubles.
14. Where do we use the relational operators, and what value do they return?
Relational operators are used to compare two values and always return a Boolean value, i.e., True or False.
15. What is machine code?
The machine code is a set of instructions that do not require any translator and is directly processed by the microprocessor. It is available in binary form and considered low-level code.
Intermediate Programming Interview Questions
16. What will happen if we use a break statement inside a nested loop?
If we use the break statement inside a nested loop, then it will bring program execution only out from that loop where it is initialized. For instance, suppose we have a child loop inside a parent loop, and there is a break statement inside the child loop.
Then, when the compiler executes the break statement, the program execution will be thrown out from the child loop, but we still remain in the parent loop. Thus, the outer loop will not be affected by the break statement if the break statement is inside the inner loop.
17. What is a data structure?
Data structure refers to a way or technique used to organize collective data in a specific manner. There are various data structures in the programming world, and each has its significance and operations.
18. What are linear and non-linear data structures?
If all the elements in a data structure are organized sequentially, then it would be considered as a linear data structure. Arrays, linked lists, and queues are examples of linear data structures.
In a non-linear data structure, all the elements are not organized sequentially. Graphs and trees are examples of non-linear data structures.
19. When do we use for loop, and when do we use the while loop?
If we are sure about the number of times we want to execute a particular code set, then we use the for a loop. However, if the number of execution of the code is not certain, then we use the while loop.
20. Why use the do-while loop if we have the while loop?
When we want to execute a set of code at least once, even if the condition is false at the initial state, we use the do while loop.
21. Even if the condition is false at the initial state, do while executes once, but while does not. Why?
The do-while loop executes the code, then checks the condition for subsequent iterations. However, the while loop checks the condition and executes the code. That’s why if the condition is false at the initial state, the while loop will not execute while the do while loop will.
22. What is a compiler?
A compiler is a computer program that acts as a translator, and its main job is to convert code from one programming language to another. In programming terms , the compiler converts high-level programming language code to low-level code, such as byte code and machine code.
23. What is a subroutine?
A subroutine is a sequential set of program instructions used to perform a specific task. In programming languages , we define subroutines as procedures, functions, methods, or a subprogram. We can define a subroutine in the program or separately in a library.
24. What are modeling languages?
It is a made-up language used to represent a piece of information, algorithm, or structure knowledge. We can either use graphical or textual notation to represent a modeling language. The flowchart is a perfect example of modeling languages.
25. What is a flowchart?
A flowchart is a graphical and pictorial representation of the program control flow. Also, it is one of the modeling languages used to describe the algorithm of a particular program or syntax.
Example:
26. Give some examples of modeling languages.
- Business Process Modeling Notation
- EXPRESS
- Extended Enterprise Modeling Language
- Flowchart
- Fundamental Modeling Concepts
- Jackson Structured Programming
- Unified Modeling Language
- Alloy (specification language
- Systems Modeling Language
27. What is maintaining and updating a program?
After the process of program planning, development, testing, and deployment, the maintenance of the program begins. In this stage, we upgrade the program with new functionalities (updating a program ) and try to improve the program with improved features and eliminate the existing issues.
28. What is a library?
A library is a collection of files that contain precompiled code, such as routines, functions, methods, and classes. Every high-level programming language has many open-source libraries that can be installed from the internet and plugged into our code.
29. What do you understand by documentation?
Documentation is the descriptive guide of a program, algorithm, library, programming language, framework, coding method, testing, and so on. In simple terms, documentation of a project is a written report that provides all the public information and operation of the same.
30. What is the beta version of the software?
A beta version generally refers to an unstable software version still in the testing and up-gradation process. Companies release beta versions to get feedback from their customers on the release of their new features and change it accordingly.
31. How does a program execute?
The computer understands only machine language, so before the execution, the compiler converts the human-written code into machine language. Next, the operating system transfers that machine code from the secondary memory to the primary memory (RAM) because the processors that execute the instructions are linked to the main memory.
32. Why do we use comments in a program?
Comments specify additional information about the code. The compiler and interpreter do not read the comments, and that’s why they do not get compiled or executed when we run a program.
Advanced Programming Interview Questions
33. What do you understand by the DRY principle?
DRY stands for Don’t Repeat Yourself, and many programming languages, libraries, and frameworks work on this principle. The principle states no need to repeat code in a program. Write it once, and use it anywhere throughout the program. The DRY principle increases code reusability and eliminates repetition.
34. What are constants in programming, and how many types of constants are there?
A value that can neither be changed during the execution of a program nor by the computer itself is known as a constant. For instance, character ‘B’ is a constant value with an ASCII code 66. There are two types of constants:
1. Numeric Constants
In programming, any digit or a sequence of digits is a numeric constant, and there are different types of numeric constants, such as Decimal and Octal.
Example:
a= 10 // here a is variable and 10 is numeric constant.
2. Character Constants
Any alphanumeric character, which is inside a single or double quotation, is a character constant. If there is a sequence of characters, it would be a string character constant.
Example:
chr = 'a' // here chr is variable and 'a' is charactere constant.
string = "Hello" // string is variable and "Hello" is string constant
35. What is software testing?
Software testing is a process in which the developed software goes through some testing criteria before it gets deployed. While testing software, many criteria test the reliability, efficiency, and interactivity of the software .
36. What is bubble sort, and what is its time complexity?
Bubble sort is a sorting algorithm in which we repeatedly swap the adjacent elements if they are in the wrong order. The time complexity of bubble sort is O(n 2 ).
37. List the significant sorting algorithms with their time complexities.
Algorithms | Time Complexity | ||
Best | Average | Worst | |
Selection Sort | ?(n 2 ) | ?(n 2 ) | O(n 2 ) |
Bubble Sort | ?(n) | ?(n 2 ) | O(n 2 ) |
Insertion Sort | ?(n) | ?(n 2 ) | O(n 2 ) |
Heap Sort | ?(n log(n)) | ?(n log(n)) | O(n log(n)) |
Quick Sort | ?(n log(n)) | ?(n log(n)) | O(n 2 ) |
Merge Sort | ?(n log(n)) | ?(n log(n)) | O(n log(n)) |
Bucket Sort | ?(n+k) | ?(n+k) | O(n 2 ) |
Radix Sort | ?(nk) | ?(nk) | O(nk) |
38. Write a function that can count the occurrence of a given character in a string.
int count_character(string s, char chr)
{
// Count variable
int count = 0;
for (int i=0;i<s.length();i++)
// checking character in string
if (s[i] == chr)
count++;
return count;
}
39. Write an algorithm to implement counting sort.
Counting_Sort(array, size) // counting sort function, which accepts an array and its size
maxi <- max(array) //the largest element from the array
count[size] // initializes an array count whose all elements are zero
for j 0 to size
find the total count of each unique element and store the count at jth index in count array
for i 0 to maxi
find the cumulative sum and store it in count array itself
for j <- size down to 1
restore the elements to array decrease count of each element restored by 1
40. Write a logic that can remove duplicate elements from a sorted array. The time complexity of the program should be O(N), where N is the total number of elements present in the array.
if (n==0 || n==1) // check for the base case if the size of array is 1 or 0
return n;
else
{
int temp[n]; // create a temporary array temp which size is similar to original array array
// Start traversing elements
int j = 0;
for (int i=0; i<n-1; i++)
// this If statement make sure that only unique elements of the array arr
// store in temporary array temp
if (arr[i] != arr[i+1])
temp[j++] = arr[i];
// Store the last element as whether
// it is unique or repeated, it hasn't
// stored previously
temp[j++] = arr[n-1];
// Modify original array
for (int i=0; i<j; i++)
arr[i] = temp[i];
}
41. Write a function that can reverse an array in place, and the time complexity of the program should be O(N).
void Array_Reverse(int arr[], int front, int back)
{
int temp;
while (front < back)
{
// swapping the back element of the array with the front elements
//with each iteration till the front < back
temp = arr[front];
arr[front] = arr[back];
arr[back] = temp;
front++;
back--;
}
}
42. How will you swap two numbers without using a third variable?
int a, b;
a= 30;
b=40;
a= a+b; // now a = 70
b= a-b; // now b =30
a= a-b; // now a =40
43. What is the difference between stable and unstable sorting algorithms?
A sorting algorithm will be termed a stable sorting algorithm if the algorithm maintains the relative order of elements even after the sorting. But if the algorithm changes the relative order of the elements, then it would be considered an unstable sorting algorithm.
44. Add two numbers without using the + operator.
int Addition(int a, int b)
{
while (b != 0)
{
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
45. How do you check if two rectangles overlap with each other?
We can represent a rectangle by two coordinates; top left(l n ) and bottom right(r n ). Rectangle 1 with coordinates point l1, and r2. Rectangle 2 with coordinates point l2 and r2.
bool Overlap(Point l1, Point r1, Point l2, Point r2)
{
// If one rectangle is on left side of other
if (l1.x >= r2.x || l2.x >= r1.x)
return false;
// If one rectangle is above other
if (l1.y <= r2.y || l2.y <= r1.y)
return false;
return true;
}
46. Differentiate between linked lists and arrays.
Array | Linked List |
The array contains elements of the same data type. | A linked list contains heterogeneous elements. |
Arrays use indexing, which makes it easy to access every element. | Linked lists do not have indexing to access the elements. We have to traverse from the initial node. |
Insertion and deletion are costly operations in an array. | It is straightforward to insert and remove nodes from a linked list. |
An array occupies contiguous memory. | The nodes of a linked list occupy random accessible memory locations. |
An array comes with a fixed size. | The linked list is very flexible, and its size can be increased or decreased. |
47. What is the efficient way to insert a new node in the middle of a linked list?
We can use the tortoise and hare algorithm using two-pointers. One is fast, and the other is slow. The quick pointer moves two steps at a time while the slow pointer moves one, so at the time the quick tip is at the end of the linked list, the slow pointer would be in the middle, and using the slow pointer, we will insert the new node in the linked list.
48. Use a programming language to print a string's reverse using recursion.
#python
def reverse(string):
if len(string) == 0:
return
temp = string[0]
reverse(string[1:]) #recursion
print(temp, end='')
string = "TechGeekBuzz"
reverse(string)
49. Create a function that could tell whether the given linked list contains a cycle.
Traverse through the list of nodes one by one and keep putting the address of each node in a data structure. While traversing through the list, if you hit a node that points to a NULL or NONE value, then return False. Else, if you run a node that points to a visited node whose address is present in the data structure, then return True.
Python Code:
def Contain_Cycle(head):
ds = set()
temp = head
while (temp):
if (temp in ds): #if the node is present in the data structure
return True
ds.add(temp)
temp = temp.next
return False
50. What are the major points we need to consider when implementing a BST (Binary Search Tree)?
- The left subtree key node value must be less than its parent node.
- The correct subtree key node value must be higher than its parent node.
- Each left and right subtree must also be a binary search tree.
- There must be no duplicate nodes.
51. What do you understand by the binary tree traversal?
Unlike other data structures, we have various methods to traverse through binary tree nodes. There are three significant tree algorithms traversal we can follow to traverse through each node of a binary tree:
- inorder traversal (Left Root Right)
- preorder traversal (Root Left-Right)
- postorder traversal (Left-Right Root)
52. Give the algorithm for in-order traversal.
- First, traverse the left subtree (recursively).
- Next, visit and print the root node.
- Finally, traverse through the right subtree (recursively).
53. What is the algorithm for in-order tree traversal without recursion?
- Create stack S.
- Create a temp node from the root node, such as temp = root.
- Push the temp node to the stack S and change the temp node with the left node of the temp, such as temp = temp-> left_node_of_temp
-
Set an IF statement. If the temp is NULL or NONE and stack S is not empty, then:
- Pop the item from the stack.
- Print the pop item and set the temp node as the popped right node, such as temp = popped_item->right.
- Now push the temp node to stack S and change the temp node with the left node of the temp, such as temp = temp-> left_node_of_temp.
- We are done if the temp is NULL and the stack is empty.
Coding Interview Questions
That’s it with the Programming interview questions. Now let’s discuss some common coding interview questions often asked during technical or coding rounds in MNCs. Not every company asks coding interview questions, but some do.
Many companies have online IDEs where they give problem statements to the candidates, and they need to solve them within a given interval of time. Mostly all the coding interview questions are related to the data structure and algorithm because, with them, it’s easy to judge any developer's problem-solving and coding skills.
In coding interviews, you are given a choice to code the given program in a programming language that you are comfortable with. In this article, we have used the Python programming language to solve the problems because it is one of the most used programming languages.
Programming languages provide syntax; you can take the logic from the code and implement it in your compatible programming language, but the logic remains the same for all the programming languages.
54. Implement the bubble sort algorithm and sort the following array [10,11, 5, 7, 12, 15].
#a function to sort the array using bubble sort
def bubble_sort(arr):
for i in range(len(arr)):
for j in range(len(arr)-i-1):
#if the current item is greater than next
#swap the items
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
return arr
#given array
array = [10,11, 5, 7, 12, 15]
sorted_array = bubble_sort(array)
print("The sorted array is: ", sorted_array)
Output
The sorted array is: [5, 7, 10, 11, 12, 15]
Click here to learn more about bubble sort and its implementation in C++ and Java. In the above solution, we implemented the bubble sort using iteration, or for loop, we can also implement bubble sort using recursion. For the recursive Bubble Sort, click here .
55. How to count the occurrences of a given character in a string?
To count the occurrences of a given character, we will iterate through the complete string, and with every occurrence, we will raise the count variable value by one.
Example
string = “Hello World”
Given characte r = ‘W’
output: 1, because ‘W’ has occurred only 1 time in Hello World
Example
# the given string
def char_count(given_string, char):
# initialize the count variable with 0 count
count = 0
# iterate through the string
for i in range(len(given_string)):
# if the character occur in the string
# increase the count by 1
if given_string[i] == char:
count += 1
return count
# chracter occurance to count
char = "e"
given_string = "Hello User! Welcome to techgeekbuzz"
print("The count of character e in given string is: ",
char_count(given_string, char))
Output
The count of character e in the given string is: 7
56. How to find the first non-repeating character in a string?
Let’s say you have given a string "techgeekbuzz.com website" , and you need to find the first non-repeating character. In the string "techgeekbuzz.com website" the first nonrepeating character is h because from left to right, only h has a character count of 1.
To solve this problem, we need to iterate through the list and check if the character has occurred more than once in the string. This problem is just an extension of the problem we have solved in the above example.
Here we need to add one more function that iterates through the string and checks for the character's count; if the character has a count of 1, it will be the first non-repeated character.
# the given string
def char_count(given_string, char):
# initialize the count variable with 0 count
count = 0
# iterate through the string
for i in range(len(given_string)):
# if the character occur in the string
# increase the count by 1
if given_string[i] == char:
count += 1
return count
def non_repeating_char(string):
# iterate over string character
for i in range(len(string)):
# count if the character has occured only one time
if char_count(string, string[i]) == 1:
return string[i]
# if all the characters are repeated
return "All characters are repeated"
given_string = "techgeekbuzz.com website"
print("The first non repeated character is: ", non_repeating_char(given_string))
Output
The first non repeated character is: h
57. How do duplicate items from an array?
To remove the duplicate items, follow the given steps.
- Create a new array that iterates over individual given array items.
- Store the items in the new array after checking if the item is not in the new array.
Example
Given Array = [1, 3, 5, 6, 7, 3, 5, 7, 1, 10, 13, 10]
Output Array = [1, 3, 5, 6, 7, 10, 13]
#function to check if the item present in the array
def check(array, item):
for i in range(len(array)):
#if the item alredy exist in the new array
if item == array[i]:
return True
#if item does not present in the array
return False
def remove_duplicate(given_array):
#initialize a new array
#that will stroe unique items
new_array = []
for i in range(len(given_array)):
item = given_array[i]
#check if the item is not present in the new array
if not check(new_array, item):
new_array.append(item)
return new_array
given_array = [1, 3, 5, 6, 7, 3, 5, 7, 1, 10, 13, 10]
print("The new array after removing the duplicates is: ", remove_duplicate(given_array))
Output
The new array after removing the duplicates is: [1, 3, 5, 6, 7, 10, 13]
58. How reverse an array in place?
To perform an in-place reverse operation on an array, we use two pointers, one at the front and the other at the rear. The iteration will go from 0 to half of the array, and with each iteration, we swap the first pointer value with the last pointer value.
# function to perfrom inplace reverse on an array
def reverse_inPlace(array):
size = len(array)-1
# iterate the array from 0 to half of the array
for i in range(len(array)//2):
# front and rear pointers
ptr1 = array[i]
ptr2 = array[size-i]
# swap the ptr1 with ptr2
array[i] = ptr2
array[size-i] = ptr1
return array
given_array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(reverse_inPlace(given_array))
Output
[9, 8, 7, 6, 5, 4, 3, 2, 1]
59. How to implement Merge Sort Algorithm?
Click here for the solution .
60. How to implement Counting Sort Algorithm?
61. How to implement Radix Sort Algorithm?
62. How to implement Selection Sort Algorithm?
62. Use the Recursion Function to implement a power function.
63. From a given string, count the length of the Longest Substring without repeating characters.
64. Write a Program that Prints all subarrays of a given array having distinct elements.
65. Write a Program that prints the minimum difference between the index of two given elements present in an array
66. Write a Program to count the triplet inversion from an array.
In an array, a triplet inversion is when i < j < k and array[i] < array[j] < array[k] , where i, j, and k are the array's indices. solution
67. Write a Program to print all the symmetric pairs present in an array.
68. Write a program that sorts an array based on item frequencies and indexes.
You must write a program that sorts the array based on the following conditions.
- Sort the items by their frequencies or the number of their occurrence.
- If the frequencies of two items are the same, sort them by their index numbers. The item with a low index number has a high priority.
Click here for the Solution .
69. How to implement the Quicksort algorithm using Hoare’s partitioning scheme.
70. Write a Program that prints the minimum sum of a subarray of size k.
71. Write a Program that prints the equilibrium index of an array.
An Equilibrium index of an array is that index point from where the sum of numbers on the left and right subarray is the same. Click here to know the solution .
72. How to Implement the Quicksort using Dutch National Flag Algorithm?
73. Write a Program that finds duplicated items in an array within a k distance.
74. In a sorted array, two numbers are swapped; you need to write a program that sorts the array again by swapping those two numbers.
75. Write a Program that can sort an array only containing 0s, 1s, and 2s, with the time complexity of O(N).
Conclusion
That sums up our list of the top programming interview questions and answers. In this article, we not only cover the top programming questions, we have also discussed some of the common coding interview questions as well.
We hope you go through these questions first before you go for the interview. During the interview, you will be tested more for necessary programming skills than your advanced knowledge of a specific programming language. So you should understand programming, data structures, and algorithms well.
People are also reading:
Leave a Comment on this Post