0% found this document useful (0 votes)
43 views23 pages

TCS Actual Coding Problems

The document contains a series of programming problems and their solutions, including finding subarrays with a given sum, calculating unique paths in a grid, and determining majority elements in an array. Each problem is presented with input/output examples and a detailed approach to solving it, utilizing various algorithms and data structures. The problems cover a range of topics such as recursion, hash maps, and array manipulation.

Uploaded by

Firoz Shaik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views23 pages

TCS Actual Coding Problems

The document contains a series of programming problems and their solutions, including finding subarrays with a given sum, calculating unique paths in a grid, and determining majority elements in an array. Each problem is presented with input/output examples and a detailed approach to solving it, utilizing various algorithms and data structures. The problems cover a range of topics such as recursion, hash maps, and array manipulation.

Uploaded by

Firoz Shaik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Date- 26 April Shift-1

Q1 -Find Sub-Arrays with a given sum in array. Given integer array find subarray with a
given sum in it.
I/P- arr = [3,4,-7,1,3,3,1,-4] target= 7
O/P- [3,4] , [3,4,-7,1,3,3] , [1,3,3] , [3,3,1]
Approach-
Brute Force Approach is simple , we directly use two for loops to find sub Array and third loop
to print the required Array.
In Optimized approach uses a hash map to efficiently find subarrays that sum to a target value.
It maintains a cumulative sum (curSum) as it iterates through the array. For each element, it
checks if curSum equals the target or if curSum - target is present in the hash map. If so, it
prints the subarray that sums to the target. The hash map stores the cumulative sum and its
corresponding index, allowing for quick lookups and subarray identification.
Brute Force-

Optimized Solution-
Q2 - There is a robot on an m x n grid. The robot is initially located at the top-left corner
(i.e., grid[0][0]).
The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]).
The robot can only move either down or right at any point in time.
Given the two integers m and n, return the number of possible unique paths that the
robot can take to reach
the bottom-right corner.
I/O: m = 3, n = 2
O/P: 3
Approach-
This approach calculates the number of unique paths in an m x n grid using recursion. Starting
from the top-left corner (0,0), it recursively explores moving right and down until it reaches
the bottom-right corner (m-1, n-1). The base cases handle reaching the grid boundaries or the
destination. The function sums the paths from moving right and down to compute the total
number of unique paths.

Date- 26 April S2
Q1 - Given two Integer, find sum of cubes of all numbers in the range of n & m.
I/P- n=1 , m=13
O/P- 8281
Approach-
The CubeSum function calculates the sum of cubes of all integers from start to end (inclusive).
It iterates through each integer in this range, computes its cube, and accumulates these values
in the variable Sum. After completing the iteration, it prints the total sum.

Q2-You are given a grocery List which consists of three parameters ITEMS,
QUANTITY,PRICE.
Your task is to find 1)Higher Selling item 2)Total Selling item 3)Avg. Selling item
I/P- Pen ,20,10
Notebook,100,10
Pencil,10,10
O/P- Notebook , 1300,433.33
Approach-
1. Input and Calculation: The program reads item details, calculates each item's total cost, and
updates the overall total cost.
2. Maximum Cost Tracking: It keeps track of the item with the highest total cost.
3. Average Cost: It computes the average cost by dividing the total cost by the number of items.

4. Output: Finally, it prints the most expensive item, the total cost formatted to two decimal
places, and the average cost.
Date- 29 April S1
Q1- Given an Integer , we need to find the sum of values of that table.
I/P- 12
O/P- 660
Approach-
The program reads an integer `number` from the user and then calculates the total sum of
`number` multiplied by each integer from 1 up to `number`. It does this by iterating through
values from 1 to `number`, adding the product of `number` and each iterator value `i` to a
running total. After completing the iteration, it prints the total sum, which represents the sum
of all these products.

Q2-Given an Array and a integer k , we need to find the maximum element in each of the
contiguous subarrays.
I/P- [2,3,6,1,5,1]
k=3
O/P- [6,6,6,5]
Approach-
The function finds the maximum element in each subarray of size windowSize from a given
array. It does this by iterating through the array and for each subarray, it uses a max heap
(priority queue) to determine the maximum value within that subarray. The maximum value is
then stored in a result vector. Finally, the function prints all the maximum values for each
subarray.
Date- 29 April S2
Q1-Calculate the sum of N terms if Fibonacci Series
Note: fib(0)=1
fib(1)=1
I/P: n=7
O/P: 33
Approach-
The function calculates the sum of Fibonacci numbers up to the n-th position. It initializes the
first two Fibonacci numbers and starts the sum with 1. In a loop, it computes each subsequent
Fibonacci number, adds it to the total sum, and updates the previous and current Fibonacci
numbers accordingly. The final result is the total sum of Fibonacci numbers up to the n-th
position. If n is less than 0, it returns -1 as an error code.
Q2- Given an integer array arr, return the number of distinct bitwise ORs of all the non-
empty subarrays of arr.The bitwise OR of a subarray is the bitwise OR of each integer in
the subarray. The bitwise OR of a subarray of one integer is that integer.
I/P: arr = [1,1,2]
O/P: 3
Approach-
The function calculates the number of unique results of bitwise OR operations on all possible
subarrays of a given array. It iterates through each element, updating a list of bitwise OR
results by combining the current number with each existing result. This ensures that all
possible subarray OR values are considered. Finally, it uses a set to determine and return the
number of unique bitwise OR results.

Date- 30 April S1
Q1- Find majority elements, where majority elements is the element which occurs more
than or equal to N/2 times the array, where 'N' is the size of the array.
I/P- 8
[5,5,4,4,5,4,5,4]
O/P- 5,4
Approach-
The function identifies and prints elements in an array that appear at least \( N/2 \) times,
where N/2 is the size of the array. It uses an unordered map to count the frequency of each
element. After populating the map, it iterates through the map entries and prints elements
that meet or exceed the frequency threshold of N/2 . This approach ensures that only majority
elements are output.
Q2-In a database there are N students, the fields of the table are NAME,AGE,GENDER.
Your task is to return
the students Name who are greater than 20 years old & Calculate the average of grades
using ascii value of female Candidates
I/P - 3
AA 21 A Female
BB 22 B Male
CC 24 C Female
O/P - AAA BBB CCC
66
Approach-
The program processes a list of people and performs two tasks. First, it collects and prints
names of individuals older than 20. Second, it calculates the average grade for female
individuals by converting their grades from characters to integers, summing them up, and then
dividing by the number of females. The results are printed at the end, showing names of older
individuals and the average female grade.
Date- 3 May S1
Q1- The Organization has data warehouse there will be given a three digit number.
Check Whether number is divisible by 9 or not ?
I/P- 162
O/P- Number 162 is divisible by 9.
I/P 236
O/P- Number 236 is not divisible by 9.
Approach-
In this approach, the function isDivisibleByNine checks if a given number is divisible by 9 by
using the modulus operator. In the main function, it reads an integer input and first checks if
the number is within the range of 100 to 999. If it is, the function isDivisibleByNine is called to
determine divisibility. Based on the result, the program prints whether the number is divisible
by 9 or not.
Q2- We are given a list of numbers we need to return maximum difference b/w smallest
& largest Number.
I/P- n=4
[1,5,7,3]
O/P- 6
Approach-
In this approach, the function findMaxDifference calculates the maximum difference between
the smallest and largest numbers in a vector. It starts by initializing the minVal and maxVal to
the first element of the vector. As it iterates through each element, it updates minVal and
maxVal if a smaller or larger value is found. Finally, it returns the difference between the
largest and smallest values.

Date- 3May S2
Q1-A person has many shoes of different sizes and he wants to arrange them, Calulate
the numbers of pairs of shoes.
I/P- 6
7L 8L 6R 6L 7L 8R
O/P- 2
Approach-
In this approach, the function `countPairs` calculates the number of shoe pairs from a list of
shoes. It uses two unordered maps to count the occurrences of left and right shoes for each
size. The function then iterates over the map of left shoes, and for each size, it finds the
corresponding count of right shoes. It adds the minimum of the counts for each size to the
total number of pairs. Finally, it returns the total number of pairs.

Q2- In a company there are employees and their efficiency is given in array ( can be
negative ) you need to find the maximum efficiency of 3 employees. The efficiency of 3
employees will be calculated by multiplying their individual efficiencies from the given
array.

I/P - 5
[2,-5,7,6,3]
O/P – 84
Approach-
In this approach, the function `findMaxProductOfThree` computes the maximum product of
any three numbers from a vector of efficiencies. It first checks if there are at least three
employees; if not, it returns an error value. The function then sorts the vector to facilitate easy
access to the largest and smallest values. It calculates the maximum product of the top three
largest numbers and the product of the two smallest (potentially negative) numbers with the
largest number. The function returns the greater of these two products as the maximum
product of three numbers.

Date- 6 May S1
Q1- Given an array nums of size n, return the majority element.The Majority elements is
the element that appears more than n/3 times.You may assume that the majority
element always exists in the array.
I/P- nums=[2,2,2,4,5,5]
O/P-2
Approach-
In this approach, the function `findMajorityElement` identifies and prints elements in the
vector that appear at least ( N/3 ) times. It uses an unordered map to count the frequency of
each element. After populating the map with counts, it iterates through the map and prints
elements whose frequency meets or exceeds the ( N/3 ) threshold. This approach efficiently
determines majority elements based on their occurrence in the vector.
Q2: Given an array balls containing numbers like '3', '5', and '6', sort the array in-place
so that balls with the same number
are adjacent, in the order '3', '5', '6'.
I/P- balls = [5, 3, 3, 6, 5, 6]
O/P- [3, 3, 5, 5, 6, 6]
Approach-
In this approach, the function sortBalls sorts an array of balls with values 3, 5, and 6 using the
Dutch National Flag algorithm. Three pointers (low, mid, and high) are used to manage the
positions of these values in the array. The low pointer tracks where the next 3 should be
placed, the mid pointer iterates through the array, and the high pointer tracks where the next 6
should be placed. The algorithm swaps values based on their type to ensure that all 3s are at
the beginning, 5s in the middle, and 6s at the end of the array.

Date- 6 May S2
Q1- Given an array of size N-1 with integers in the range of [1,N] the task to find the
missing number from the first N integers.
I/P- 6
[1,2,3,4,6,7]
O/P- 5
Approach-
In this approach, the function `Missing` finds the missing number in a sequence from 1 to ( n ).
It calculates the sum of all elements in the given array and the expected sum of the first ( n )
natural numbers using the formula n(n + 1)/2. The missing number is then determined by
subtracting the actual sum from the expected sum. This method efficiently identifies the
missing number with a time complexity of ( O(n) ) and a space complexity of ( O(1) ).
Q2-Given two integers L and R, the task is to find the count of total numbers of prime
numbers in the range [L, R] whose sum of the digits is also a prime number.
I/P- L=1,R=10
O/P- 4
Approach-
In this approach, the function `countPrimeWithPrimeDigitSum` identifies prime numbers
within a given range `[L, R]` where the sum of their digits is also prime. It uses the `isPrime`
function to check for primality of both the number and its digit sum. The `sumOfDigits`
function computes the sum of digits for each number. The total count of such numbers is
returned, providing a count of primes with a prime digit sum in the specified range.
Date- 8May S1

Q1- Write a program to take input of X and Y in a new line.Print the number which is
nearer to the integer when divided by Y.
I/P- X=25
Y=4
O/P-24
Approach –
In this approach, the program first defines a custom rounding function, customRound, that
rounds a given double to the nearest integer, rounding up if the decimal part is 0.5 or greater.
In the main function, the user inputs two integers x and y. The program calculates the quotient
of x divided by y, rounds it using the customRound function, and then multiplies the rounded
value by y to get the nearest multiple of y to x, which is then printed

Q2-Write a program that generates a password adhering to the following conditions:


C1-The password must consist of at least 8 characters.
C2-It must contain at least one integer.
C3-It must contain at least one special character from the set {'#', '@').
C4-It must contain at least one uppercase letter and one lowercase letter.
C5-Each character in the password should be incremented by the number of times
specified by the second input.
Your program should take two inputs:
1. A string representing the initial password.
2. An integer representing the number of times each character should be incremented.
Your program should then generate and output the modified password.
I/P 1: werV432@
I/P 2: 2
O/P: ygtX653#
Approach-
In this approach, the function addValueToChars processes each character of the input string. If
the character is a letter, it shifts it by a given value within the alphabet, wrapping around using
modulo arithmetic. If the character is a digit, it shifts similarly within the range of digits. Non-
alphanumeric characters like @ are conditionally transformed into # and vice versa. The
modified characters are then concatenated to form the resulting string, which is returned.

Date- 8 May S2
Q1-Given size of n and list of array elements and we should print if the
given element in array is divisible by 3 then replace the element with "Three"
and if the element in array is divisible by 5 then replace the element with "Five"
if the element divisible by 3 and 5 both then replace the element with "ThreeFive"
if the element in the array is not satisfying the above 3 conditions then
put the element as it is and print the array
I/P- N=4
[8,3,9,5]
O/P- 8 Three 9 Five
Approach-
In this approach, the function `helperfun` iterates through the given array and checks each
element to determine if it is divisible by 3, 5, or both. If a number is divisible by both 3 and 5, it
prints "ThreeFive"; if only by 3, it prints "Three"; and if only by 5, it prints "Five". If the number
is divisible by neither, it prints the number itself. This is similar to the FizzBuzz problem,
where numbers are replaced by strings based on their divisibility.

Q2- Task 1- print the collatz sequence upto ending with 1 the sequence should be in the
following way
-> if the number is even:
F(n)=n//2
-> if the number is odd:
F(n)=3*n+1
This sequence should end until the last element of sequence is 1
Task-2
For the given integer from 1,n it should calculate the sequence of each k value Le,
1<=k<=n
Calculate the maximum length of sequence list of each k value and return the maximum
length of the sequence list of the k value and the k value itself
Task-3

For the given integer from 1.n it should calculate the sequence of each k value le,
1<=k<=n Calculate the maximum value of the each sequence within the sequence list of
each k value and return the maximum value of the sequence list of the k value and those
k value itself
Input: 5
Output:
[5,16,8,4,2.1]
8,3
16,3
Input: 0
Output: Error!
Input: xyza
output: Error!
Input:-13
Output: Error
Input: 5.5
Output: Error!
Approach –

In this approach, the code starts by checking if the input string represents a positive integer. If
valid, it generates the Collatz sequence starting from the given integer n, where the sequence
follows the rule: divide by 2 if even, or multiply by 3 and add 1 if odd, until n reaches 1. It then
finds the number k between 1 and n that produces the longest sequence and the highest value
within any sequence. The results include the entire sequence for n, the length of the longest
sequence, and the highest value encountered. If the input is not valid, an error message is
displayed.
Date- 9May S1
Q1) given an integer n, return true if it is an armstrong number, otherwise return false.
an armstrong number is a number that is equal to the sum of its own digits each raised
to the power of the number of digits.
input:
[153, 371, 108]
output:
[true, true, false]
Approach-
In this approach, the function `isArmStrong` determines if a number `n` is an Armstrong
number in `k`-digit space. An Armstrong number (or Narcissistic number) is one where the
sum of its digits each raised to the power of `k` equals the number itself. The function
computes this by iterating over each digit of `n`, raising it to the power of `k`, and summing
these values. Finally, it checks if this sum matches the original number, returning `true` if they
are equal and `false` otherwise.
Q2)Print Top Candidate from the given input
INPUT format: no. of input n ,top k to be sorted, candidate with marks
I/P:3 4 70 Johnny 85 Anmol 270 Vishy
O/P:Vishy:270
Anmol:85
Jhonny 70
Approach-
In this approach, the `main` function reads a line of input, which includes an integer `k`, an
integer `N`, followed by pairs of `marks` and `name`. The input is split into tokens using
`istringstream` and parsed into a vector `l`. The first two tokens are converted to integers `k`
and `N`, respectively. Subsequent tokens are processed into pairs of integers (marks) and
strings (names), which are stored in a vector of pairs. This vector is then sorted in descending
order based on marks using `sort` with a custom comparator. Finally, the top `k` entries (or
fewer if there aren't `k` entries) are printed, showing the names and their corresponding
marks.
Date-9 May S2
Q1)Print all combinations
I/P- n=3
[0,1,2]
O/P-[0,01,012,0123,1,12,123,2,23,3]
Approach –
In this approach, the `generateCombinations` function recursively generates all possible
combinations of elements from the given vector `arr`. It starts at the specified `index` and uses
the `current` string to build combinations. For each element at `arr[index]`, the function is
called twice: once including the current element in the combination (appending it to
`current`), and once excluding it (not modifying `current`). The base case is when `index`
reaches the end of the vector, at which point it prints the current combination if it's not empty.
This recursive method explores all subsets of the array, including the empty subset.

Date-14May S1
Q1)You are given an integer array num. The unique elements of an array are the
elements that appear exactly once in the array.
Return sum of all unique elements of nums.
I/P- [1,2,5,5,7]
O/P-10
Approach –
In this approach, the sumOfUniqueElements function calculates the sum of all unique elements
in a vector nums. It first uses an unordered_map to count the frequency of each element. Then,
it iterates through this map, adding elements to the sum only if they appear exactly once in the
array. The final sum of these unique elements is returned.
Q2)Given an integer array nums ,find the subarray with largest sum , and return its sum.
I/P-[-1,2,4,2,-5,3]
O/P-8
Approach-
In this approach, the program reads a string of space-separated integers from the input and
stores them in a vector. It then calculates the maximum sum of any contiguous subarray using
a modified version of Kadane's algorithm. The currentSum keeps track of the sum of the
current subarray, updating the maxSum whenever a higher sum is found. If currentSum
becomes negative, it is reset to zero. Finally, the maximum subarray sum is printed.
Date- 14 May S2

Q1)You are tasked with writing a program to calculate the total shipping cost based on
the weight of the package and the distance it needs to travel. The shipping cost is
determined by the following criteria:
1. Base money: $5.00
2. Cost per kilogram: $2.00
3. Cost per 10 kilometers: $0.5
Examplel:
10 (w)
100 (D)
output: $30.00
Approach –
In this approach, the computeShippingCost function calculates the total shipping cost for a
package based on its weight and delivery distance. It starts with a base fee of $5.00. The cost is
then increased based on the weight of the package, where each kilogram costs $2.00.
Additionally, the cost is incremented based on the delivery distance, with every 10 kilometers
adding $0.50. The total shipping cost is the sum of these charges.

Q2) Given an array of integers nums and an integer k, return the tota number of
subarrays whose sum equals to k. A subarray is a contiguous non-empty sequence of
elements withi an array.
Input: nums =123-3111
K=3
Output: 6
Approach-
In this approach, the function calculates the number of subarrays whose sum equals a given
value `k`. It uses a hash map to keep track of prefix sums and their frequencies. As the function
iterates through the array, it maintains a running total (`preSum`) of the elements
encountered. For each element, it checks if there is a previous prefix sum that would make the
current subarray sum equal to `k` by subtracting `k` from `preSum` and looking it up in the
hash map. The frequency of such prefix sums is added to the count. Finally, the hash map is
updated with the current prefix sum. This method efficiently computes the count in linear
time.

You might also like