Table of Contents
Tech Mahindra Coding Questions 2024
By practicing the Tech Mahindra Coding Questions prepared by experts in 2024, graduates attempting the Tech Mahindra online exam can ace the first attempt. These Tech Mahindra Coding Questions consist of complex coding questions with answers. Read this blog on Tech Mahindra Coding questions and prepare well for the exam 2024. This includes Top 15 Tech Mahindra Coding questions and answers for your reference.
This blog on Tech Mahindra Coding Questions and Answers will equip you with the essential knowledge and skills to excel in the coding rounds, covering topics from data structures and algorithms to problem-solving techniques. These questions are beneficial if you’re a fresher or an experienced professional. This blog is about Tech Mahindra Coding questions and answers for 2024. The programming language used by Tech Mahindra is Python, C++or Java.
Furthermore, a strong knowledge of programming languages such as Python, Java, or C++ and an understanding of the NLP libraries including the NLTK, SpaCy, and TensorFlow is necessary to apply for the job in Tech Mahindra.
15 Tech Mahindra Coding Questions and Answers 2024
Graduates and experienced can practice and brush up their coding skills with the Tech Mahindra Coding Questions and Answers of 2024 given here. These are repeatedly asked coding questions and answers. So, check out these to solve these coding questions in the Tech Mahindra exam within the time frame.
1. Write a program to calculate and return the sum of the absolute difference between the adjacent number in an array of positive integers from the position entered by the user.
Note: You are expected to write code in the findTotalSum function only which receives three positional arguments: number of elements in the array2nd: array3rd: position from where the sum is to be calculated
Example
Input
input 1: 7
input 2: 11 22 12 24 13 26 14
input 3: 5
Output
25
Explanation
The first parameter 7 is the size of the array. Next is an array of integers, input 5 is the position from which to calculate the Total Sum. The output is 25 as per the calculation below.
| 26-13 | = 13
| 14-26 | = 12
Total Sum = 13 + 12 = 25
Ans.
C++ Program
#include <stdio.h>
#include <stdlib.h>
int findTotalSum(int n, int arr[], int start)
{
int difference, sum=0;
for(int i=start-1; i<n-1; i++)
{
difference = abs(arr[i]-arr[i+1]);
sum = sum + difference;
}
return sum;
}
int main()
{
int n;
int start;
scanf("%d",&n);
int array[n];
for(int i=0; i<n; i++)
{
scanf("%d",&array[i]);
}
scanf("%d",&start);
int result = findTotalSum(n, array, start);
printf("\n%d",result);
return 0;
}
Output
Input:
7
11 22 12 24 13 26 14
5
Output:
25
Python
def countOddEvenDifference(n, arr):
odd_count = 0
even_count = 0
for num in arr:
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
return odd_count - even_count
# Example usage:
n = 6
arr = [1, 2, 3, 4, 5, 6]
result = countOddEvenDifference(n, arr)
print("Difference between count of odd and even numbers:", result)
Output
Input:
7
11 22 12 24 13 26 14
5
Output:
25
2. Write a program to return the difference between the count of odd numbers and even numbers.
Ans.
C++ Program
#include <iostream>
#include <vector>
int differenceOddEvenCount(const std::vector<int>& numbers) {
int oddCount = 0, evenCount = 0;
for (int num : numbers) {
if (num % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}
return oddCount - evenCount;
}
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6}; // Example list
int difference = differenceOddEvenCount(numbers);
std::cout << "Difference between count of odd and even numbers: " << difference << std::endl;
return 0;
}
Output
Difference between count of odd and even numbers: -2
Python Program
def difference_odd_even_count(numbers):
odd_count = 0
even_count = 0
for num in numbers:
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
return odd_count - even_count
numbers = [1, 2, 3, 4, 5, 6] # Example list
difference = difference_odd_even_count(numbers)
print("Difference between count of odd and even numbers:", difference)
Output
Difference between count of odd and even numbers: -2
3. Write a program to find the difference between the elements at the odd index and index.
Note: You are expected to write code in the findDifference function that only receives the first parameter as the number of items in the array and the second parameter as the array itself. You are not required to take the input from the console.
Ans.
C++ Program
#include <iostream>
#include <vector>
int differenceOddEvenIndex(const std::vector<int>& numbers) {
int oddIndexSum = 0, evenIndexSum = 0;
for (size_t i = 0; i < numbers.size(); ++i) {
if (i % 2 == 0) {
evenIndexSum += numbers[i];
} else {
oddIndexSum += numbers[i];
}
}
return oddIndexSum - evenIndexSum;
}
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6}; // Example list
int difference = differenceOddEvenIndex(numbers);
std::cout << "Difference between sum of elements at odd indices and even indices: " << difference << std::endl;
return 0;
}
Output
Difference between sum of elements at odd indices and even indices: -3
Python
def difference_odd_even_index(arr):
odd_index_sum = 0
even_index_sum = 0
for i in range(len(arr)):
if i % 2 == 0:
even_index_sum += arr[i]
else:
odd_index_sum += arr[i]
return odd_index_sum - even_index_sum
# Example usage:
arr = [1, 2, 3, 4, 5, 6] # Example list
result = difference_odd_even_index(arr)
print("Difference between sum of elements at odd indices and even indices:", result)
Output
Difference between sum of elements at odd indices and even indices: -3
4. A Cloth merchant has some pieces of cloth of different lengths. He has an order of curtains of 12 feet. He has to find how many curtains can be made from these pieces. The lengths of pieces of cloth are recorded in feet.
Note: You are expected to write code in the findTotalCurtains function only to receive the first parameter as the number of items in the array and the second parameter as the array itself. You are not required to take the input from the console.
Ans.
C++ Program
#include <iostream>
#include <vector>
int findTotalCurtains(int n, const std::vector<int>& lengths) {
const int curtain_length = 12;
int totalCurtains = 0;
for (int length : lengths) {
totalCurtains += length / curtain_length;
}
return totalCurtains;
}
int main() {
std::vector<int> lengths = {24, 30, 18, 12, 36}; // Example list of lengths
int n = lengths.size();
int totalCurtains = findTotalCurtains(n, lengths);
std::cout << "Total number of curtains that can be made: " << totalCurtains << std::endl;
return 0;
}
Output
Total number of curtains that can be made: 7
Python
def find_total_curtains(n, lengths):
curtain_length = 12
total_curtains = 0
for length in lengths:
total_curtains += length // curtain_length
return total_curtains
# Example usage:
lengths = [24, 30, 18, 12, 36] # Example list of lengths
n = len(lengths)
total_curtains = find_total_curtains(n, lengths)
print("Total number of curtains that can be made:", total_curtains)
Output
Total number of curtains that can be made: 7
5. Find a pair with the maximum product in an array of Integers.
Ans.
C++ Program
#include <iostream>
#include <vector>
#include <limits.h>
std::pair<int, int> findMaxProductPair(const std::vector<int>& arr) {
if (arr.size() < 2) {
throw std::invalid_argument("Array should contain at least two elements.");
}
int max1 = INT_MIN, max2 = INT_MIN;
int min1 = INT_MAX, min2 = INT_MAX;
for (int num : arr) {
if (num > max1) {
max2 = max1;
max1 = num;
} else if (num > max2) {
max2 = num;
}
if (num < min1) {
min2 = min1;
min1 = num;
} else if (num < min2) {
min2 = num;
}
}
int maxProduct = std::max(max1 * max2, min1 * min2);
if (maxProduct == max1 * max2) {
return {max1, max2};
} else {
return {min1, min2};
}
}
int main() {
std::vector<int> arr = {1, 20, -10, -30, 50, 2, 60}; // Example array
try {
auto result = findMaxProductPair(arr);
std::cout << "Pair with maximum product: (" << result.first << ", " << result.second << ")\n";
} catch (const std::invalid_argument& e) {
std::cerr << e.what() << '\n';
}
return 0;
}
Output
Pair with maximum product: (60, 50)
Python
def find_max_product_pair(arr):
if len(arr) < 2:
raise ValueError("Array should contain at least two elements.")
max1 = max2 = float('-inf')
min1 = min2 = float('inf')
for num in arr:
if num > max1:
max2 = max1
max1 = num
elif num > max2:
max2 = num
if num < min1:
min2 = min1
min1 = num
elif num < min2:
min2 = num
max_product = max(max1 * max2, min1 * min2)
if max_product == max1 * max2:
return (max1, max2)
else:
return (min1, min2)
# Example usage:
arr = [1, 20, -10, -30, 50, 2, 60] # Example array
try:
result = find_max_product_pair(arr)
print(f"Pair with maximum product: {result}")
except ValueError as e:
print(e)
Output
Pair with maximum product: (60, 50)
6. Write a program for Decimal to Binary Conversion.
Ans.
C++ Program
#include <iostream>
#include <string>
std::string decimalToBinary(int num) {
if (num == 0) return "0";
std::string binary = "";
while (num > 0) {
binary = (num % 2 == 0 ? "0" : "1") + binary;
num /= 2;
}
return binary;
}
int main() {
int num = 25; // Example decimal number
std::string binary = decimalToBinary(num);
std::cout << "Binary representation of " << num << " is: " << binary << std::endl;
return 0;
}
Output
Binary representation of 25 is: 11001
Python
def decimal_to_binary(num):
if num == 0:
return "0"
binary = ""
while num > 0:
binary = ("0" if num % 2 == 0 else "1") + binary
num //= 2
return binary
# Example usage:
num = 25 # Example decimal number
binary = decimal_to_binary(num)
print(f"Binary representation of {num} is: {binary}")
Output
Binary representation of 25 is: 11001
7. You are given an array, You have to choose a contiguous subarray of length ‘k’, find the minimum of that segment, and return the maximum of those minimums.
Input:
1 → Length of segment x =1
5 → size of space n = 5
1 → space = [ 1,2,3,1,2]
2
3
1
2
Output
3
Ans.
C++ Program
#include <iostream>
#include <vector>
#include <deque>
#include <limits.h>
int maxOfMinSegments(int k, const std::vector<int>& arr) {
int n = arr.size();
std::deque<int> dq;
std::vector<int> minValues;
for (int i = 0; i < n; ++i) {
while (!dq.empty() && dq.front() <= i - k) {
dq.pop_front();
}
while (!dq.empty() && arr[dq.back()] >= arr[i]) {
dq.pop_back();
}
dq.push_back(i);
if (i >= k - 1) {
minValues.push_back(arr[dq.front()]);
}
}
int maxOfMin = INT_MIN;
for (int val : minValues) {
if (val > maxOfMin) {
maxOfMin = val;
}
}
return maxOfMin;
}
int main() {
int k = 1;
std::vector<int> arr = {1, 2, 3, 1, 2};
int result = maxOfMinSegments(k, arr);
std::cout << "Maximum of minimums of all contiguous subarrays of length " << k << ": " << result << std::endl;
return 0;
}
Output
Maximum of minimums of all contiguous subarrays of length 1: 3
Python
def max_of_min_segments(k, arr):
from collections import deque
n = len(arr)
dq = deque()
min_values = []
for i in range(n):
while dq and dq[0] <= i - k:
dq.popleft()
while dq and arr[dq[-1]] >= arr[i]:
dq.pop()
dq.append(i)
if i >= k - 1:
min_values.append(arr[dq[0]])
return max(min_values)
# Example usage:
k = 1
arr = [1, 2, 3, 1, 2]
result = max_of_min_segments(k, arr)
print(f"Maximum of minimums of all contiguous subarrays of length {k}: {result}")
Output
Maximum of minimums of all contiguous subarrays of length 1: 3
8. Given an array of integers representing measurements in inches, write a program to calculate the total of measurements in feet. Ignore the measurements that are less than a foot (eg. 10).
Note: You are expected to write code in the findTotalFeet function only which will receive the first parameter as the number of items in the array and the second parameter as the array itself. You are not required to take input from the console
Example:
Finding the total measurements in feet from a list of 5 numbers
Input:
18 11 27 12 14
Output:
5
Ans.
C++ Program
#include <iostream>
#include <vector>
int findTotalFeet(int n, const std::vector<int>& measurements) {
int totalFeet = 0;
for (int measurement : measurements) {
if (measurement >= 12) {
totalFeet += measurement / 12;
}
}
return totalFeet;
}
int main() {
int n = 5;
std::vector<int> measurements = {18, 11, 27, 12, 14}; // Example list
int result = findTotalFeet(n, measurements);
std::cout << "Total measurements in feet: " << result << std::endl;
return 0;
}
Output
Total measurements in feet: 4
Python
def find_total_feet(n, measurements):
total_feet = 0
for measurement in measurements:
if measurement >= 12:
total_feet += measurement // 12
return total_feet
# Example usage:
n = 5
measurements = [18, 11, 27, 12, 14] # Example list
result = find_total_feet(n, measurements)
print(f"Total measurements in feet: {result}")
Output
Total measurements in feet: 4
9. Write a program to calculate and return the sum of absolute differences between the adjacent numbers in an array.
Ans.
C++ Program
#include <iostream>
#include <vector>
#include <cmath>
int sumOfAbsoluteDifferences(const std::vector<int>& nums) {
int sum = 0;
for (int i = 1; i < nums.size(); ++i) {
sum += std::abs(nums[i] - nums[i - 1]);
}
return sum;
}
int main() {
std::vector<int> nums = {3, 5, 2, 8, 4}; // Example array
int result = sumOfAbsoluteDifferences(nums);
std::cout << "Sum of absolute differences between adjacent numbers: " << result << std::endl;
return 0;
}
Output
Sum of absolute differences between adjacent numbers: 10
Python
def sum_of_absolute_differences(nums):
return sum(abs(nums[i] - nums[i - 1]) for i in range(1, len(nums)))
# Example usage:
nums = [3, 5, 2, 8, 4] # Example array
result = sum_of_absolute_differences(nums)
print("Sum of absolute differences between adjacent numbers:", result)
Output
Sum of absolute differences between adjacent numbers: 10
10. Write a program to calculate the total bill tax amount for a list of billing amounts passed as an array of long integers.
Up to 1000, there is no tax applicable, subsequently, a flat tax of 10% for the remaining amount as per the tax rate.
Note:
All calculations and results should be integer-based ignoring fractions
You are expected to write code in the calcTotalTax function only which will receive the first parameter as the number of items in the array and the second parameter is the array itself. You are not required to take input from the console.
Ans.
C++ Program
#include <iostream>
#include <vector>
long calcTotalTax(int n, const std::vector<long>& billingAmounts) {
long totalTax = 0;
for (long amount : billingAmounts) {
if (amount > 1000) {
totalTax += (amount - 1000) * 10 / 100; // Flat tax of 10% for amounts above 1000
}
}
return totalTax;
}
int main() {
int n = 5;
std::vector<long> billingAmounts = {800, 1200, 1500, 500, 2000}; // Example list of billing amounts
long result = calcTotalTax(n, billingAmounts);
std::cout << "Total bill tax amount: " << result << std::endl;
return 0;
}
Output
Total bill tax amount: 120
Python
def calc_total_tax(n, billing_amounts):
total_tax = 0
for amount in billing_amounts:
if amount > 1000:
total_tax += (amount - 1000) * 10 // 100 # Flat tax of 10% for amounts above 1000
return total_tax
# Example usage:
n = 5
billing_amounts = [800, 1200, 1500, 500, 2000] # Example list of billing amounts
result = calc_total_tax(n, billing_amounts)
print("Total bill tax amount:", result)
Output
Total bill tax amount: 120
11. Write a program to reverse a given string without using built-in library functions.
Ans.
C++ Program
#include <stdio.h>
#include <string.h>
void reverseString(char *str) {
int length = strlen(str);
for (int i = 0; i < length / 2; i++) {
char temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}
}
int main() {
char str[] = "Tech Mahindra";
reverseString(str);
printf("Reversed string: %s\n", str);
return 0;
}
Output
Reversed string: ardnihaM hceT
Python
def reverse_string(s):
return s[::-1]
s = "Tech Mahindra"
reversed_str = reverse_string(s)
print("Reversed string:", reversed_str)
Output
Reversed string: ardnihaM hceT
12. Write a program to print the Fibonacci series to a given number.
Ans.
C++ Program
#include <stdio.h>
void fibonacci(int n) {
int first = 0, second = 1, next;
printf("Fibonacci Series: ");
for (int i = 0; i < n; i++) {
printf("%d ", first);
next = first + second;
first = second;
second = next;
}
}
int main() {
int n = 10; // Number of terms
fibonacci(n);
return 0;
}
Output
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34
Python
def fibonacci(n):
first, second = 0, 1
fib_series = []
for _ in range(n):
fib_series.append(first)
first, second = second, first + second
return fib_series
n = 10 # Number of terms
print("Fibonacci Series:", fibonacci(n))
Output
Fibonacci Series: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
13. Write a program to calculate the factorial of a given number.
Ans.
C++ Program
#include <stdio.h>
int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int num = 5; // Number for factorial calculation
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
Output
Factorial of 5 is 120
Python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
num = 5 # Number for factorial calculation
print("Factorial of", num, "is", factorial(num))
Output
Factorial of 5 is 120
14. Write a program to check whether a given string is a palindrome.
Ans.
C++ Program
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isPalindrome(char *str) {
int length = strlen(str);
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length - i - 1])
return false;
}
return true;
}
int main() {
char str[] = "radar";
if (isPalindrome(str))
printf("%s is a palindrome\n", str);
else
printf("%s is not a palindrome\n", str);
return 0;
}
Output
radar is a palindrome
Python
def is_palindrome(s):
return s == s[::-1]
s = "radar"
if is_palindrome(s):
print(s, "is a palindrome")
else:
print(s, "is not a palindrome")
Output
radar is a palindrome
15. Write a program to check if a given number is prime.
Ans.
C++ Program
#include <stdio.h>
#include <stdbool.h>
bool isPrime(int n) {
if (n <= 1)
return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}
int main() {
int num = 17;
if (isPrime(num))
printf("%d is a prime number\n", num);
else
printf("%d is not a prime number\n", num);
return 0;
}
Output
17 is a prime number
Python
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
num = 17
if is_prime(num):
print(num, "is a prime number")
else:
print(num, "is not a prime number")
Output
17 is a prime number
These questions cover a range of fundamental programming concepts and are commonly asked in technical interviews.
In conclusion, Tech Mahindra’s coding questions are structured to assess a candidate’s problem-solving abilities and programming skills. While these questions may seem challenging, they can be tackled logically, and a strong understanding of programming concepts. By practicing regularly and familiarizing yourself with common coding patterns and data structures, you can improve your chances of success.
Remember, the goal is to find the correct solution but demonstrate your thought process and coding style. Along with dedication and perseverance, you can excel in Tech Mahindra’s coding assessments and take a step closer to your dream job.
Important Links – Tech Mahindra Coding Questions 2024
- Tech Mahindra Eligibility Criteria For Freshers 2024
- Tech Mahindra Application Form 2024- Apply Now
- Tech Mahindra Previous Year Paper- PDF Download
- Tech Mahindra Interview Question 2024
- Tech Mahindra Recruitment Process 2024 For Freshers
- Tech Mahindra Syllabus and Exam Pattern 2024- Download PDF
- Tech Mahindra 2024: Overview, Benefits and Interview Process
- Tech Mahindra Salary In India 2024 – Freshers and Experienced
Tech Mahindra Coding Question -FAQs
Q1. What type of coding questions can I expect in Tech Mahindra interviews?
Ans. Tech Mahindra coding questions typically cover topics, data structures, algorithms, problem-solving, and sometimes specific technologies or domains relevant to the position you are applying for.
Q2. Are the coding questions in Tech Mahindra interviews language-specific?
Ans. No, Tech Mahindra coding questions are generally not language-specific. You can choose a programming language, such as C++, Java, or Python to solve the coding problems.
Q3.How difficult are the coding questions in Tech Mahindra interviews?
Ans. The difficulty level of coding questions in Tech Mahindra interviews can vary depending on the role and level you are applying for. Generally, you can expect a mix of easy, medium, and sometimes hard coding problems.
Q4.What are some common coding topics I should prepare for Tech Mahindra interviews?
Ans. Some common coding topics to prepare for Tech Mahindra interviews include:
Arrays and Strings
Linked Lists
Trees and Graphs
Sorting and Searching Algorithms
Dynamic Programming
Recursion and Backtracking
Hashing and Maps
Bit Manipulation
Object-Oriented Programming (OOP) concepts
Q5. Which programming languages or tools to focus on for Tech Mahindra interviews?
Ans. While Tech Mahindra does not typically require proficiency in any specific programming language or tool for interviews, it’s a good idea to be comfortable with at least one programming language and its associated libraries or frameworks. Additionally, knowledge of SQL, databases, and web technologies can be beneficial depending on the role.
Q6.How can I prepare effectively for coding questions in Tech Mahindra interviews?
Ans. To prepare for coding questions in Tech Mahindra interviews, you should:
Practice solving coding problems from online platforms like Tech Mahindra Mock Test by Skillvertex
Review fundamental data structures and algorithms.
Understand the time and space complexity of your solutions.
Solve previous years’ Tech Mahindra placement papers or interview questions.
Participate in mock interviews to simulate the interview experience.
Q7.How important are problem-solving and coding skills in Tech Mahindra interviews?
Ans. Problem-solving and coding skills are crucial in Tech Mahindra interviews, as they assess your ability to think logically, approach problems systematically, and write efficient and correct code. Strong problem-solving skills demonstrate your readiness to tackle real-world challenges in software development.
Q8.Do you know any additional resources or tips to help me prepare for Tech Mahindra coding questions?
Ans. Utilize online resources like tutorials, articles, and videos to strengthen your understanding of coding concepts.
Join coding communities or forums to discuss problems and learn from others.
Practice solving coding problems under time constraints to improve your speed and accuracy.
Stay updated with industry trends and technology relevant to your field of interest.
Remember to stay calm and confident during the interview process. Preparation and practice will boost your confidence and increase your chances of success in Tech Mahindra interviews.
Q9. How does Tech Mahindra evaluate coding skills during the interview process?
Ans. Tech Mahindra evaluates coding skills through various stages of the interview process. This may include an initial screening round, candidates are asked to solve coding problems online or on a coding platform. In subsequent interview rounds, candidates may be given more complex coding challenges to solve either on a whiteboard, in a shared coding environment, or on paper. Interviewers assess candidates based on their problem-solving approach, coding style, efficiency of solutions, and ability to handle edge cases and exceptions.
Q10. Can I use external resources or ask for help during Tech Mahindra coding interviews?
Ans. During Tech Mahindra coding interviews, candidates are expected to solve problems independently without referring to external resources or asking for help. While interviewers may allow clarifications on problem statements or provide hints if a candidate is stuck, relying heavily on external resources or seeking excessive help may reflect on the candidate’s problem-solving abilities. It’s important to demonstrate self-reliance and critical thinking skills during coding interviews.
Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together