0% found this document useful (0 votes)
2 views16 pages

Optional Questions d4 d3

The document outlines several programming tasks in C++, including implementing a Reverse Polish Notation calculator, pattern matching in sentences, sorting arrays, checking for rotated sorted arrays, identifying champion elements, calculating maximum area from heights, and reversing words in a sentence. Each task includes specific input and output formats, constraints, and examples. The tasks emphasize the importance of not using certain C++ features like variable-length arrays and avoiding hard-coded solutions.

Uploaded by

pihumalviya728
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)
2 views16 pages

Optional Questions d4 d3

The document outlines several programming tasks in C++, including implementing a Reverse Polish Notation calculator, pattern matching in sentences, sorting arrays, checking for rotated sorted arrays, identifying champion elements, calculating maximum area from heights, and reversing words in a sentence. Each task includes specific input and output formats, constraints, and examples. The tasks emphasize the importance of not using certain C++ features like variable-length arrays and avoiding hard-coded solutions.

Uploaded by

pihumalviya728
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/ 16

Optional Questions (Lab 7)

Q1. Reverse Polish Notation Calculator

We generally write expressions like a + b, where a and b are operands and + is an operator.
This is known as infix notation, i.e. the operator ‘+’ is placed in between two operands, ‘a’ and
‘b’. On the other hand, Reverse Polish Notation, also known as postfix, is a notation in which the
operator follows their operands. For example “a + b” in RPN is “a b +”.

Some more examples are given below

Infix RPN

(a + (b - c)) abc-+

(a + b) * (c - d) ab+cd-*

(a * (b - (c + d))) abcd+-*

( (a - (b + c)) /d) abc+-d/

More info on RPN: https://en.wikipedia.org/wiki/Reverse_Polish_notation

The operands can be replaced with actual numbers (integers/floats). Write a C++ program to
read in a string/character array that will denote an expression using RPN notation. Your task is
to evaluate the RPN expression and print the result.

Hint to solve (Stacks is our clue):


● Scan the expression from left to right.
● Operands encountered: Keep storing them.
● Operator encountered: Take the last two operands, apply the operator, and store the
result.
● Continue until the expression is fully processed.

Input:
● First line contains an integer n, denoting the number of characters in the input
expression
● Second line contains the RPN expression containing digits and operators without
spaces. All the numbers are single-digit integers.

Output:
● If the expression is valid, print the appropriate answer
● Print appropriate error message for an invalid expressions.

Test cases:
INPUT OUTPUT

5 20
23+4*

5 1.2
623+/

3 Invalid division by 0
60/

7 -30
6234+-*

3 Invalid
2+

Note:

● Do not write any C++ statements for printing general messages. For example, the following
should NOT be present in your program:
cout << "Enter expression length: ",
● cout should be used to print only the computed final output. In addition, do not print
unnecessary spaces unless specified in the program.
● If any hard coding is found, or if any test case passes by merely writing a cout statement
and without any logic, then the marks for that test case will NOT be awarded.
Q2. Pattern Matching

Write a C++ program to accept a sentence as input from the user. Thereafter, accept words, i.e.
patterns, one by one from the user. For each word, determine the first index at which it appears
in the sentence, if the sentence is treated as an array of characters with one space between
each pair of adjacent words. If a pattern does not exist in the sentence, you should indicate that
as well by printing -1.

(You can use the data type std::string to store each word that you read. In this case you will
find the following functions useful: If str is a std::string type variable, str.back() returns the last
character of str (to check it is a full stop); str.pop_back() deletes its last character; str.length()
returns the number of characters in str.)

Example :
sentence = "This is a simple example to demonstrate pattern finding example."
patterns = ["simple", "pattern", "notfound", "demonstrate", "example"]
output = [10, 38, -1, 29, 16]
Explanation =
{
'simple': 10,
'pattern': 34,
'notfound': -1,
'demonstrate': 29,
'example': 16
}

Input format
● First line contains a sentence ending with a full stop. The full stop is not part of the
sentence, it is used to represent the end of the sentence. The length of the sentence will
always be less than 100 including the full stop(.).
● Second line will be an integer n
● This is followed by n words (separated by whitespace).

Output format
● One single line of space-separated indices corresponding to the occurrence of the
respective string pattern

Note :

● Do not write any C++ statements for printing general messages. For example, the
following should NOT be present in your program:
● cout << "Enter a number:"
● cout << "The computed answer is", etc.
● cout should be used to print only the computed final output. In addition, do not
print unnecessary spaces unless specified in the program.
● If any hard coding is found, or if any test case passes by merely writing a cout
statement and without any logic, then the marks for that test case will NOT be
awarded.
● IMPORTANT: Do not use variable length arrays. (It is not C++ standard and doesn’t
work on MS Visual C++.)

Visible Test Cases

INPUT OUTPUT

This is a simple example to demonstrate pattern finding. 10 38 -1 29 16


5
simple pattern notfound demonstrate example

Find the word that appears first and not the repeated one. 0 9 45 19
4
Find word repeated appears

This is my gift my curse. 8 -1 19 -1 11


5
my spiderman curse peter gift

When in doubt look intelligent. 5 -1 -1


3
in question why

A day without laughter is a day wasted. -1 2 32 23


4
cry day wasted is
Q3. Sort the Given Array in Ascending Order

In computer science, sorting refers to the process of arranging the elements of a list or array in
a specific order, typically in ascending or descending order. In-place sorting refers to sorting
algorithms that sort the elements of a data structure (like an array or list) without requiring extra
space for another array of the same size. Instead, these algorithms rearrange the elements
within the original data structure. This can be particularly efficient in terms of space complexity.

Write a C++ program to accept an array of integers as input from the user and sort it in
ascending order in-place. If the elements repeat, the order of their first occurrence should be
preserved, i.e., the sorting should be stable.

(Use an in-place sorting algorithm for the solution.)

Example:

—---------------------------
Input:
6
20 -10 35 3 -10 20

Output:
-10 -10 3 20 20 35
—--------------------------
Input:
10
4371934608

Output:
0133446789

Explanation:
- The elements are sorted in ascending order while maintaining their relative positions in case of
duplicates.

Input Format:
- First line will contain an integer `n`, the number of elements in the array.
- Second line will contain `n` space-separated integers, the elements of the array.

Output Format:

- One single line containing the sorted array, with each element separated by a space.
Note:

- Do not write any C++ statements for printing general messages. For example, the following
should NOT be present in your program:

cout << "Enter the number of elements:";


cout << "The sorted array is:", etc.

cout should be used to print only the computed final output. In addition, do not print
unnecessary spaces unless specified in the program.

- If any hard coding is found, or if any test case passes by merely writing a `cout` statement and
without any logic, then the marks for that test case will NOT be awarded.

- IMPORTANT: Do not use variable length arrays. (It is not C++ standard and doesn’t work on
MS Visual C++.)

Visible Test Cases:


6 -10 -10 3 20 20 35
20 -10 35 3 -10 20

10 0133446789
4371934608

8 -7 0 2 3 3 5 5 9
5 5 -7 9 0 3 3 2

12 111223334445
111223334445

15 -100 -100 -50 -50 -10 0 0 0 10 10 50 50 100


100 -100 50 0 -50 -100 100 50 -10 10 0 -50 100 100
100 0 10
Q4. Rotated Sorted Array Check

Write a C++ program that accepts an array of integers and determines whether the array was
originally sorted in non-decreasing order, then rotated some number of positions (including
zero). Duplicates are allowed in the array.

To clarify, an array A rotated by x positions results in an array B of the same length such that
A[i] == B[(i+x) % length], where % is the modulo operation. Your task is to return true
if the input array can be formed by rotating a non-decreasing sorted array, and false
otherwise.

Example:
Let the array be

nums = [3, 4, 5, 1, 2]

In this case, the array is a rotation of the sorted array [1, 2, 3, 4, 5] by 3 positions, so the
output would be true.

Similarly, for the array:

nums = [2, 1, 3, 4]

This array cannot be obtained by rotating a sorted array, so the output would be false.

Input format:

● The first line will contain a single integer n which denotes the length of the array.
● The second line will contain n integers (separated by spaces), representing the elements
of the array.

Output format:

● A single line containing true if the array is a rotation of a non-decreasing sorted array,
and false otherwise.

Note :

● Do not write any C++ statements for printing general messages. For example, the
following should NOT be present in your program:
● cout << "Enter a number:"
● cout << "The computed answer is", etc.
● cout should be used to print only the computed final output. In addition, do not
print unnecessary spaces unless specified in the program.
● If any hard coding is found, or if any test case passes by merely writing a cout
statement and without any logic, then the marks for that test case will NOT be
awarded.
● IMPORTANT: Do not use variable length arrays. (It is not C++ standard and doesn’t
work on MS Visual C++.)

Visible Test Cases

INPUT OUTPUT

5 true
34512

4 false
2134

6 true
678912

5 true
12345

5 true
45661
Q5. Champion in an array (Easy)

A champion array is an array where some elements are called "champions." An element
is considered a champion if it is greater than all the elements to its right in the array.

For example, in the array [16, 17, 4, 3, 5, 2], the champions are 17, 5, and 2.
● 17 (as it is greater than all elements to its right),
● 5 (greater than 2),
● and 2 (the last element is always a leader).

Write a C++ program that accepts an integer N representing the number of elements in an array,
followed by input of N integers. The program should then print all the "champion" elements in
the array in the order of their appearance from left to right.

Hint : Remember that the rightmost element will always be a champion

Input Format:
The first line will contains an integer N, the number of elements in the array.
The second line contains N space-separated integers, the elements of the array.

Output Format:
One single line containing all the champion elements in the order of their appearance from left
to right with each element separated by a space.

Note :
● Do not write any C++ statements for printing general messages. For example, the
following should NOT be present in your program:
● cout << “Enter the number of elements”;
● cout should be used to print only the computed final output. In addition, do not
print unnecessary spaces unless specified in the program.
● If any hard coding is found, or if any test case passes by merely writing a cout
statement and without any logic, then the marks for that test case will NOT be
awarded.
● IMPORTANT: Do not use variable length arrays. (It is not C++ standard and doesn’t
work on MS Visual C++.)

After you have written the solution, answer the following questions:
1. How many loops did you use in your initial solution?
(You can count nested loops separately if they exist.)
2. If you used 2 or more loops, can you think of a way to solve this problem using
just one loop? Try to implement the solution using a single loop if possible and
compare the efficiency of both approaches.
Visible Test Cases:

Input Output

1 16
16

5 10 8 5 3 1
10 8 5 3 1

10 600 200 5
50 40 600 10 30 70 25 90 200 5

12 340 88 25 14
340 12 45 32 11 56 78 43 29 88 25 14

14 95 92 90 88 70 60 50 30 20 10 5
95 85 92 80 90 75 88 70 60 50 30 20 10 5
Q6: Maximum Area
You have an array called heights with n integers. Each integer represents the height
of a vertical line segment drawn at a point in the x-axis; adjacent line segments are
separated by unit distance along the x-axis, as shown in the example below. Your task
is to find a rectangle such that two of its sides are contained within two such segments,
and has the maximum area. Write a function maxArea which receives two
parameters - integer “n” denoting size of array and the array “heights”. The
function should find the maximum possible area of the rectangle and return an integer
denoting the value of maximum area. Print this value in the main function as output.

heights = [2,1,10,2,5,4,8,3,7]

Input format:
● The first line of the input contains an integer N - the size of the array.
● The second line of the input contains N space-separated integers, representing
the elements of the array “heights”.

Output format:
● Single integer denoting the maximum possible area

Function prototype:
int maxArea(int n, int heights[ ])

Note
● Do not write any C++ statements for printing general messages. For example,
the following should NOT be present in your program:
○ cout << "Enter a number:"
○ cout << "The computed answer is", etc.
● cout should be used to print only the computed final output. In addition, do not
print unnecessary spaces unless specified in the program.
● If any hard coding is found, or if any test case passes by merely writing a cout
statement and without any logic, then the marks for that test case will NOT be
awarded.
● IMPORTANT: Do not use variable-length arrays. (It is not C++ standard and
doesn’t work on MS Visual C++.)

Visible Test Cases:

Input Output

2 4
49

8 7
22221111

9 42
2 1 10 2 5 4 8 3 7

7 25
9468351

6 48
9 12 13 15 18 20
Q7. REVERSE WORDS
Write a C++ program to accept a sentence (as a character array) in the main function.
Each word is separated by a single space in the sentence. The sentence will be passed to a
function reverseWords(char arr[], int n), where n is the length of the sentence.
The function should reverse each word in the sentence without using extra space
or data types like strings or additional arrays. After reversing the words, print the
final sentence from the main function.

IMPORTANT: Do not use variable-length arrays. (It is not C++ standard and doesn’t
work on MS Visual C++.)

Input format:
● In the main function, accept a sentence as a character array. A sentence consists of
alphabets and spaces only, where a single space separates each word.

Output format:
● The output should print the sentence with each word reversed, maintaining the order
of the words.

Function Details:

● Function Name: reverseWords


● Parameters:
o char arr[]: The input sentence as a character array.
o int n: The length of the character array.

Note:
● Do not write any C++ statements for printing general messages. For example, the following
should NOT be present in your program:
o cout << "Enter a number:",
● cout should be used to print only the computed final output. In addition, do not print
unnecessary spaces unless specified in the program.
● If any hard coding is found, or if any test case passes by merely writing a cout statement
and without any logic, then the marks for that test case will NOT be awarded.

Test Cases
Test Case Input Output
1 iH I ma won ta BTII Hi I am now at IITB
2 elppa apple
3 gnidoc si nuf coding is fun
4 level rotator racecar level rotator racecar
5 A BC DEF A CB FED
Q8. Two sum

Write a program that takes an integer N as input, followed by N unique elements of an array A,
and a target sum sum. Implement a function called two_sum, which accepts the array A and the
target sum, and performs the following tasks:
● Print the indices of all pairs of distinct elements in A whose sum equals the target sum.
● If no such pair exists, print -1.
Requirements:
● The given array might not be sorted.
● The two indices printed should be different i.e., adding a number at ith position to itself to
achieve target sum is not a valid answer.
Input format:
● First line takes an integer ‘n’ representing the size of the array.
● Second line takes ‘n’ elements of the array i.e., A[0], A[1], … A[n]
● Third line takes an integer ‘sum’ representing target sum.
Output format:
● If such 2 numbers exists then print their indices in form: i j (all such pairs)
● Otherwise print -1.

Note
● Do not write any C++ statements for printing general messages. For example, the
following should NOT be present in your program:
○ cout << "Enter a number:"
○ cout << "The computed answer is", etc.
● cout should be used to print only the computed final output. In addition, do not print
unnecessary spaces unless specified in the program.
● If any hard coding is found, or if any test case passes by merely writing a cout statement
and without any logic, then the marks for that test case will NOT be awarded.

Test Cases :
Input Output

3 01 // Because element 1 ( at index 0 ) and element 2 ( at index


123 1) adds upto the sum of 3.
3

4 -1 // No pair of element adds up to sum of 7 from the given


12 6 9 2 array.
7

5 24 // Because element 45 ( at index 2 ) and element 12 ( at index


21 32 45 19 12 4) adds upto the sum of 57.
57

7 14 // Because 18 ( at index 1 ) and 7 ( at index 4) = 25


25 18 3 11 7 15 10 56 // Because 15 ( at index 5 ) and 10 ( at index 6) = 25
25
Q9. Array permutations using Recursion
You are given a 1D array A of size N. The elements of A are sorted in non-decreasing
order. You are required to write a recursive function:
void printPermutations(int A[], int N);
You can pass any additional arguments to the function if required. The function should
generate and print all possible permutations of A. It should handle arrays with unique as
well as duplicate elements. You should print the permutations in strictly increasing
lexicographical order.

Input format:
● The first line of the input contains an integer N - the size of the array.
● The second line of the input contains N space-separated integers, representing
the elements of the array A.

Output format:
● You have to print M lines of output, where M is the number of unique permutations
of the array A.
● On each line print a permutation of A, with each permutation containing N
space-separated integers.
● Ensure that the permutations are printed in strictly increasing lexicographical
order.

Assumptions on the input:


● N is an integer between 1 and 6, inclusive.
● Each element of the array A is an integer between 1 and 10,000, inclusive.
● The elements of A are sorted in non-decreasing order.

Note
● Do not write any C++ statements for printing general messages. For example,
the following should NOT be present in your program:
○ cout << "Enter a number:"
○ cout << "The computed answer is", etc.
● cout should be used to print only the computed final output. In addition, do not
print unnecessary spaces unless specified in the program.
● If any hard coding is found, or if any test case passes by merely writing a cout
statement and without any logic, then the marks for that test case will NOT be
awarded.
● IMPORTANT: Do not use variable-length arrays. (It is not C++ standard and
doesn’t work on MS Visual C++.)
Visible Test Cases
Input Output

1 100
100

2 12
12 21

2 11
11

3 123
123 132
213
231
312
321

4 1123
1123 1132
1213
1231
1312
1321
2113
2131
2311
3112
3121
3211

You might also like