You are given a list of points on a 2D plane, represented by their coordinates (x, y). Your task is to determine the
shape formed by these points based on their count.
- If there are 2 points, print "Line" (without quotes).
- If there are 3 points, print "Triangle" (without quotes).
- If there are 4 points, print "Quadrilateral" (without quotes).
- If there are 5 points, print "Pentagon" (without quotes).
The input ends when you encounter -1 as a termination signal.
--------------------------------------------------------------------------------------------------------------------------Input Format:
Each line contains two space-separated positive integers, representing the x and y coordinates of a point. The last line
of input will contain -1, which indicates the end of input.
Output Format:
Print a single line with no trailing whitespaces as directed in the question.
Constraints:
The number of points will be between 2 and 5 (inclusive).
1 <= x, y <= 1000
Sample Input:
89
27
-1
Sample Output:
Line
Explanation:
There are 2 points provided in the input, hence the output is Line.
Sample Input:
13
49
27
41
-1
Sample Output:
Quadrilateral
Explanation:
There are 2 points provided in the input, hence the output is Quadrilateral
John Snow has taken it upon himself to defend the North and defeat the Lannisters by capturing King's Landing. He
plans a surprise attack from an underground crypt with you, Samwell Tarly. For this attack to succeed, he requires
the correct number of soldiers to seize the capital. Being his most trusted advisor, you have to help him find this
number, so you start reading ancient texts and come across a string of characters that will give you the answer. Your
task is to decode this string and inform John Snow of his troop size.
The string contains seven characters and represents a postfix expression. The first two characters will be digits (1 - 9),
and the 3rd character is an operator (+, -, *, /). The operation needs to be performed between the first two digits. The
result will serve as one of the operands for the next calculation. The 4th character contains another digit, and the 5th
character contains an operator, representing the operation that must be performed between the previous result and
the 4th character of the string. Similarly, the 6th character contains a digit, and the 7th character contains a final
operator. In the end, you will have the final number representing the number of soldiers John Snow must take along
with him, print this number.
--------------------------------------------------------------------------------------------------------------------------Input Format:
The input contains only one line with seven characters, representing the string found in the ancient text.
Output Format:
A single integer indicating the number of troops required.
--------------------------------------------------------------------------------------------------------------------------Sample Input:
33+2-7*
Sample Output:
28
Explanation:
We have 3 and 3 as the initial operands, and + is the operator, so the result is
3+3=6
3
+
3
=
6
. The next operands are 6 and 2 with - as the operator, so the result is
6−2=4
6
−
2
=
4
. The next operands are 4 and 7 with * as the operator, so the final result is
4∗7=28
You are given a 3 * 3 character matrix, consisting of small letters (a - z) and capital letters (A
- Z). You are given 2 target words : "cat" , "jam" .
Your task is to report if these words are present in the matrix ( A word is present in the
matrix if we can locate these words in a row (from left to right OR from right to left), or a
column (from top to bottom OR from bottom to top), or any diagonal (from top left to
bottom right OR from top right to bottom left) ). If words such as "CAT" or "Jam" or "jAM"
are found, these are not considered as found words. ( Case-sensitive Identification )
NOTE : please notice that some possible diagonal arrangement are not considered (eg :
bottom left to top right).
Sample Input :
CaT
jam
iOt
(Note : characters are space separated, and each line contains 3 characters, no extra space
after last character in a line)
Sample Output :
cat : Absent
jam : Present
(Note : For the above example input, cat is not found anywhere (though CaT and Cat are
found), jam is found in the 2nd row)
Problem Statement
Write a C program that converts a two-digit positive integer into its equivalent English
words. The program should take an integer input between 10 and 99 (inclusive) and output
the number in words. Input should be validated to ensure it is within the range [10, 99]. If
the input is invalid, display an error message "Error: Number out of range!"
Sample Input
42
Sample output
Forty-Two
Sample Input 2
19
Sample Output 2
Nineteen
Sample Input 3
105
Sample Output 3
Error: Number out of range!
Sample Input 4
80
Sample Output 4
Eighty
Write a C program to determine the type of triangle based on the lengths of its three sides.
The program should classify the triangle as
1) Equilateral: All sides are equal.
2) Isosceles: Exactly two sides are equal
3) Scalene: All sides are different
4) Not a Triangle: The sides do not satisfy the triangle inequality (the sum of any two sides
must be greater than the third side)
Input
Input three positive integers representing the lengths of the sides
Output
If equilateral triangle print "Equilateral Triangle"
If Isosceles triangle print "Isosceles Triangle"
If scalene triangle print "Scalene Triangle"
If not a triangle print "Not a Triangle"
Sample Input 1
333
Sample Output 1
Equilateral Triangle
Sample Input 2
558
Sample Output 2
Isosceles Triangle
Sample Input 3
7 8 10
Sample Output 3
Scalene Triangle
Sample Input 4
1 2 10
Sample Ouput 4
Not a Triangle
Write a C program to check whether a given date is valid or not
Input
Three integers: day, month, and year, representing a date in the format DD MM YYYY.
The program should validate the date based on:
Valid Year: Year must be positive.
Valid Month: Month must be between 1 and 12.
Valid Day: Day must be valid for the given month
Months with 31 days: January, March, May, July, August, October, December
Months with 30 days: April, June, September, November
February 28 days in a normal year and 29 days in a leap year.
Leap Year: A year is a leap year if
It is divisible by 4 and not divisible by 100, OR
It is divisible by 400.
If the date is valid, print "Valid Date!". Otherwise, print "Invalid Date!".
Sample Input 1
15 8 2025
Sample Output 1
Valid Date!
Sample Input 2
29 2 2024
Sample Output 2
Valid Date!
Sample Input 3
31 4 2023
Sample Output 3
Invalid Date!
Let's play the first squid game..
Some context before the problem: There is a starting line and a finish line, and participants
must run from the starting line to the finish line within a given time duration, T seconds. A
signal alternates between "red" and "green," indicating whether participants are allowed to
move. If the signal is "red" and any participant is found moving during this time, they are
eliminated. Here, we will simulate an almost red light green light game.
You will be given the duration of game (in seconds), the distance between the start and end
line (in metres) and the number of players along with their names.
The movement of each participant is predetermined, represented by a binary string of
length T:
0 indicates the participant remains at rest for that second.
1 indicates the participant moves 1 meter forward during that second.
Also, you are given some timestamps (in seconds) at which the light changes (from red to
green and vice versa). The signal starts as "green" at time 0. You have to find the names of
players who are able to reach beyond the finish line.
Input format:
The first line of the input contains three integers - the duration of the game in seconds (T),
the distance between starting and finish line in metres (d) and the number of players (n).
The next n lines will contain the names of n players (the names can span a maximum of 3
words, separated by a space). The next n lines will contain a binary string of length T
denoting the state of motion or rest for each player (0 for rest and 1 for motion).
The next line will contain an integer k denoting the number of timestamps at which the
light changes. The last line of input contains k integers denoting the timestamps (in
seconds) when the light changes.
Constraints:
1. Maximum length of name of any player can be 50 and the name can have a maximum of
3 space separated words.
2. Maximum number of players can be 100
3. The duration of the game can range from 1 to 1000 (inclusive).
Output format:
The first line of output should contain an integer w, which represents the number of players
who are qualified. The next w lines should contain the names of those w players. (Please
ensure that the relative ordering of those w players in the output should be same as in the
input).
You are given an array of N integers. Your task is to find the elements that occur with the
second-highest frequency in the array. If there are multiple elements with the same secondhighest frequency, output them in increasing order.
Input Format
The first line contains an integer N (1 <= N <= 100) — the number of elements in the array.
The second line contains N space-separated integers (1 <= A[i] <= 50) representing the array
elements.
Output Format
The first line should contain an integer M, representing the number of elements that occur
with the second-highest frequency.
The second line should contain M space-separated integers in ascending order.
Note:
If all elements in the array appear with the same frequency, print 0 (since there is no valid
second-highest frequency).
If there is only one distinct frequency (meaning no second-highest frequency exists), also
print 0.
The Edict of Compressed Wisdom
-----------------------------In the golden age of the Magadha Empire, Emperor Ashoka’s scribes faced a grave
challenge. A newly discovered edict at Sarnath—carved with repetitive runes—threatened
to exhaust the sacred pillar’s space.
Ashoka summoned his chief scribe, Vimalakirti, and declared:
"Carve this edict anew, but shorten it without losing its essence."
The Challenge
-------------
Given a character array runes[] of length N representing the edict’s runes, compress in-place
by replacing consecutive duplicates with the rune followed by their count (if >1).
Constraint: N >= 1
Examples
-------Input:
6
aaabbc
Output: a3b2c
NVIDIA Stock Analysis After Market Dip
-------------------------------------Following a sudden drop in NVIDIA's stock price recently, investors are analyzing historical
price data to strategize their trades. Given the volatility, you are tasked with determining
the maximum profit possible from a single buy-sell transaction (one buy followed by one
sell) in NVIDIA's stock over the past N days.
The Challenge
------------Given an array prices[] of length N, where prices[i] represents NVIDIA's stock price on day
i, find the maximum profit achievable with at most one transaction (i.e., buy on one day and
sell on a later day). If no profit is possible, return 0.
Constraint: N >= 1
Example
------Input:
3
123
Output: 2
Explanation: Buy on day 1 (price = 1) and sell on day 3 (price = 3). Profit = 3 - 1 = 2.
Input:
2
21
Output: 0
Explanation: No profit possible
Rick Sanchez, the brilliant scientist, has composed a sequence of musical notes that could
save the world — but only if it’s perfect. The notes are represented by integers between 0
and 127. The interval between two notes a and b is the absolute difference semitones.
Rick believes that for the melody to work and save the multiverse, the interval between
each pair of adjacent notes must be either 5 or 7 semitones. Before Rick releases this melody
into the wild, he asks Morty to double-check and make sure it’s perfect.
That’s where you come in. Morty needs your help to determine if each melody is “perfect”
or not before Rick unleashes it on the multiverse!
Input:
The first line contains an integer t which denotes the number of melodies such that
1<=t<=1000.
For each melody, two lines:
An integer n which is the number of notes is 2 <= n <= 50.
A sequence of n integers a_1,a_2,…,a_n are the notes.
Output:
For each melody, output "YES" if the melody is perfect, otherwise, output "NO" in a new
line.
Test Case 1:
1
2
10 15
Output:
YES
Explanation: The interval is |15 - 10| = 5, which is valid.
Saul Goodman, the best lawyer in Albuquerque, NM has fled from his house as the federal officers try to chase him.
He had written down all his "important" numbers in a diary. Now that he must figure out a way to escape, he wants
to call the vacuum shop. But obviously he wasn't careless - he had saved the numbers in a coded manner.
Instead of writing a digit directly, he writes it down in the form of a 12 digit binary string. To find what digit a string
represents, Saul does the following:
1. Calculate the length of the shortest non-empty contiguous sequence of 1's, followed and preceded by 0's or
start/end of string - let this number be x. Note that this means that the sequence should be non-empty, all 1's, and
sandwiched between 0's/start/end only - e.g. in 01110, x = 3, not 2 or 1.
2. Calculate the length of the longest contiguous sequence of 0's - let this number be y;
Then, y - x denotes the digit represented by this string.
Now this is a long process obviously, and all was fine when the feds weren't chasing down Saul. But in this situation,
Saul must act fast - so he asks you to write him a C program to quickly decipher his encoded phone number!
Help Saul!
Input format:
10 lines consisting of binary strings, each string of length 12.
Output format:
One 10-digit phone number
Example input:
000000000010
010101010100
000000111111
010101010100
000000000010
000000111111
010101010100
000000000010
000000111111
000000111111
Example Output:
9101901900
Explanation:
000000000010: The longest contiguous sequence of 0's is of length 10, and the shortest non-empty sequence of 1's is
of length 1. The digit is 9.
010101010100: The longest contiguous sequence of 0's is of length 2, and the shortest non-empty sequence of 1's is of
length 1. The digit is 1.
000000111111: The longest contiguous sequence of 0's is of length 6, and the shortest non-empty sequence of 1's is of
length 6. The digit is 0.
Beware, a number may start with 0! It is however guaranteed that the binary string contains both 0's and 1's.
Hint: You can make an array of strings if needed - declared as:
char arr[a][b] // an array of "a" strings each of length b.
To access the ith string then, you may use arr[i].
In the bustling city of Codeville, two merchants, Alice and Bob, were known for their
unique way of trading goods. Instead of using traditional numbers, they represented their
inventory counts as strings of digits. One day, they decided to collaborate on a new venture,
but they needed to calculate the total product of their combined inventories. However, they
faced a challenge: their inventory counts were too large to be handled by standard integer
types, and they could only work with strings.
Alice had an inventory count represented by the string num1 of length n1, and Bob had his
count represented by the string num2 of length n2. They needed a way to multiply these
two large numbers and represent the result as a string to avoid any overflow issues.
Can you help Alice and Bob by writing a function that takes num1 and num2 as input and
returns the product of the two numbers, also represented as a string? Don't print leading
zeros except for the number 0 itself.
Examples
-------Input:
3
123
3
456
Output:
56088
Constraints:
- n1, n2 >= 1
- Both num1 and num2 contain only digits 0-9
- Neither num1 nor num2 contains any leading zeros, except for the number 0 itself
A subarray is a contiguous portion of an array. This means that given an array nums, a
subarray consists of one or more consecutive elements taken from nums, maintaining their
order.
You are given an integer array nums of length n and an integer k. A subarray of nums is
called good if it contains exactly k different integers.
Your task is to determine the number of good subarrays in nums.
Input:
The first line contains two integers n and k — the length of the array and the required
number of distinct integers.
The second line contains n space-separated integers nums[i] — the elements of the array.
Output:
Print a single integer — the number of good subarrays of nums.
Constraints:
1 <= nums.length <= 2 * 10^4
1 <= nums[i], k <= nums.length
Example 1:
Input:
52
12123
Output: 7
Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3],
[1,2,1], [2,1,2], [1,2,1,2]
Example 2:
Input:
53
12134
Output: 3
Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].
The sequence of "Count and Say" is a sequence of numbers where each term is generated by
reading the previous term and counting consecutive digits.
Starting with the number "1", the next term is generated by describing the number in terms
of the count of digits in consecutive groups:
"1" is read as "one 1" => "11".
"11" is read as "two 1s" => "21".
"21" is read as "one 2, one 1" => "1211".
"1211" is read as "one 1, one 2, two 1s" => "111221".
And so on.
Input:
An integer n (1 <= n <= 22) which represents the term number of the sequence to generate.
Output:
Return the nth term of the "Count and Say" sequence as a string.
Example:
Input: n=1
Output: 1
Input: n=4;
Output: 1211
Explanation:
1st term: "1".
2nd term: "11".
3rd term: "21".
4th term: "1211"
Given a string, write a function to count all the palindromic substrings in it. A substring is a
palindrome if it reads the same forward and backward.
Input: A string s of length n (1 <= n <= 100).
Output: The number of palindromic substrings in the given string.
Example 1:
Input: s = "abc"
Single-character palindromes: "a", "b", "c" (3 palindromes)
No two adjacent characters form a palindrome.
Total palindromic substrings: 3
Example 2:
Input: s = "aaa"
Single-character palindromes: "a", "a", "a" (3 palindromes)
Two-character palindromes: "aa", "aa" (2 palindromes)
Three-character palindrome: "aaa" (1 palindrome)
Total palindromic substrings: 6
In the input, you will be given a strictly positive integer K denoting the length of the strings
you have to print. In your output, on each line, you have to print a string of length K using
only the characters '0' and '1' (without quotes). The strings must be printed in
lexicographically increasing order i.e. if you think of these strings as numbers, the numbers
should appear in increasing order.
The only property these strings must satisfy is that no two consecutive characters in the
strings you generate can be the character '0'. Two or more consecutive characters can be '1'
but two consecutive characters cannot be '0'.
Note
The first character in the string can freely be 0 or 1 since there is no previous character to
cause consecutive 0. However, second character onwards, we must have a 0 only if the
previous character was not 0 to avoid consecutive 0.
Be sure to print all leading 0 in the output. Every string you print must contain k characters
where 2 <= k <= 14.
There should be no extra spaces anywhere. There MUST be a trailing newline after the last
string printed.
Example Input
2
Example Output
01
10
11
Explanation
00 is an illegal string.
You are given two sorted arrays nums1 and nums2 of sizes m and n respectively. Your task
is to find the median of the two sorted arrays combined.
Input
The first line contains an integer m — the size of the first array.
The second line contains m space-separated integers nums1[i] — elements of the first sorted
array.
The third line contains an integer n — the size of the second array.
The fourth line contains n space-separated integers nums2[i] — elements of the second
sorted array.
Output
Print a single floating-point number — the median of the two combined sorted arrays.
The answer should be printed to 1 decimal place of precision.
Example 1:
Input:
2
13
1
2
Output: 2.0
Example 2:
Input:
2
12
2
34
Output: 2.5
Mr C had drawn a nice axis-aligned rectangle (i.e. whose sides are parallel either to the x or the y axis) on a piece of
paper and decorated his drawing with a few dots. However, one of his mischievous clones came and erased the lines
forming the edges of the rectangle leaving only the dots for the corners behind and potentially added more dots. Mr
C needs your help to recover the largest rectangle. More formally you task is : Given n points in 2d space, find the
largest axis-aligned rectangle that can be formed.
The first line of the input will give you n, a strictly positive number, giving you the number of points on the plane.
In the next n lines, we will give you the x and y coordinates of n points on the 2D plane, separated by a space. The
coordinates will all be integers. In your output, you have to print the area of the largest axis-aligned rectangle that
can be formed out of the n points we have given you(all the n points need not to be on one of the side of largest
rectangle). If no axis-aligned rectangle can be formed out of the points we have given you, simply print -1 in the
output.
Note
Rest assured that we will give you at least 4 points, i.e., n will be greater than or equal to 4.
The rectangle we are looking for has non-zero area. Please do not report a single point as a rectangle of area zero. If
there is no axis-aligned rectangle of non-zero area, you should print -1 as your output.
The rectangle we are looking for must be axis aligned. Do not report a rectangle whose sides are not parallel to the x
and y axes.
Be careful about extra/missing lines and extra/missing spaces in your output.
Examples:
Input 1
9
11
12
13
21
22
23
31
32
33
Output 1
4
Explanation 1
The points (1,1), (1,3), (3,1) and (3,3) form a rectangle of area 4.
Input 2
4
10
21
01
12
Output 2
-1
Explanation 2
There is no axis-aligned rectangle.
You need to process an array of N integers while maintaining a static counter. The counter follows specific rules and is affected by previously processed numbers.
You must implement a function:
void processArray(int arr[], int N)
This function will update the static counter based on these conditions:
1.
Counter Initialization: counter = 10 (static variable).
2.
Processing Rules:
If arr[i] is even, add it to counter.
If arr[i] is odd, subtract it from counter.
If counter is divisible by 5, reset counter = counter / 2.
If counter becomes negative, print "Negative counter reached" and stop processing.
3.
Memory Effect (History Tracking):
Maintain an auxiliary array history[] to store all encountered even numbers.
If arr[i] is even and is already present in history[], double the counter instead of adding arr[i].
4.
Processing Stops If:
"Negative counter reached" is printed.
The same odd number appears twice (to prevent infinite loops). In this case, print "Processing stopped due to repeated odd number" in the output.
Input Format:
An integer N (1 <= N <= 100), representing the size of the array.
An array of N space-separated integers arr[0], arr[1], ..., arr[N-1] (0 <= arr[i] <= 1000).
Sum of integers, counter <= 1000
Output Format:
If "Negative counter reached" is printed, stop processing further numbers.
if "Processing stopped due to repeated odd number" is printed, stop processing further numbers.
Otherwise, print the final value of counter.
Example 1:
Input:
6
2 4 8 5 10 2
Processing Steps:
counter = 10
2 (even) -> counter = 10 + 2 = 12
4 (even) -> counter = 12 + 4 = 16
8 (even) -> counter = 16 + 8 = 24
5 (odd) -> counter = 24 - 5 = 19
10 (even) -> counter = 19 + 10 = 29
2 (even, already seen in history) -> Double counter instead of adding 2 -> counter = 29 * 2 = 58
Output:
58
Example 2 (Negative Counter Case):
Input:
7
5 10 3 4 7 15 6
Processing Steps:
counter = 10
5 (odd) -> counter = 10 - 5 = 5 (divisible by 5, reset 5/2 = 2)
10 (even) -> counter = 2 + 10 = 12
3 (odd) -> counter = 12 - 3 = 9
4 (even) -> counter = 9 + 4 = 13
7 (odd) -> counter = 13 - 7 = 6
15 (odd) -> counter = 6 - 15 = -9 (Negative, stop processing)
Output:
Negative counter reached
Example 3 (Odd Number Repeats - Stops Early):
Input:
5
6 8 3 10 3
Processing Steps:
counter = 10
6 (even) -> counter = 10 + 6 = 16
8 (even) -> counter = 16 + 8 = 24
3 (odd) -> counter = 24 - 3 = 21
10 (even) -> counter = 21 + 10 = 31
3 (odd, already seen earlier) -> Processing stops!
Output:
Processing stopped due to repeated odd number
You are given an N x N square matrix stored as a 1D array (row-wise). You must repeatedly
reduce the matrix using the following rule until only one element remains:
1.
Construct a new (N-1) x (N-1) matrix, but store it again in a 1D array.
2.
Each element at index (i, j) in the new matrix is computed as:
Mnew[i][j] = abs(M[i][j] - M[i+1][j+1])
3.
Continue the transformation, reducing the matrix size by 1 each time.
4.
Print the final remaining element.
Example:
Input:
3
259
473
618
Output:
4
Logic:
Original Matrix (stored as 1D array):
[ 2, 5, 9, 4, 7, 3, 6, 1, 8 ]
Step 1: Construct 2x2 matrix:
[ |2-7|, |5-3|]
[|4-1|, |7-8|]
-> [ 5, 2, 3, 1 ]
Step 2: Construct 1x1 matrix:
[ |5-1| ]
-> [4]
Constraints
2 <= N <= 100
-1e6 <= matrix[i] <= 1e6
You do not need to use 2d arrays for this question
Aadhya has developed a complex encoding system for her secret messages. The system
works as follows:
1. Each letter is first converted to its ASCII code.
2. The ASCII code is then transformed using the formula ASCII * 2 + 1) % 256
3. The resulted is represented as a 3-digit number, padding with leading zeros if necessary.
Write a program that encodes a given message using this system.
Input: The input consists of a single line of text containing only printable ASCII characters
(32 <= ASCII < 126). The maximum length of the input is 100 characters.
Output: Output the encoded message as a single line of 3-digit numbers separated by spaces.
Example:
Input:
Hello, World!
Output:
145 203 217 217 223 089 065 175 223 229 217 201 067
You are given a collection of N intervals, where each interval is represented as a pair [start,
end]. Your task is to merge all overlapping intervals and return the resulting list of nonoverlapping intervals in sorted order.
Example:
Input:
4
13
26
8 10
15 18
Output: [1,6] [8,10] [15,18]
Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
Input Format:
The first line contains a single integer N — the number of intervals.
The next N lines each contain two space-separated integers, start and end, representing an
interval [start, end].
Output Format:
Print the merged list of non-overlapping intervals in a single line, with each interval
represented as [start,end], separated by a space. The intervals should be sorted in ascending
order based on their start values.
Also, merge intervals that have the same start or end time. For example, merge [1,2] and
[2,3] into [1,3].
The kingdom of Eldoria has hidden treasures guarded by an enchanted map. The map
consists of a grid of size NxM, where each cell contains either :
A positive integer represents the amount of treasure in that location or a -1 represents a trap
that instantly ends the journey if stepped on.
Sir Harvey starts at the top left corner (0,0) and must reach the bottom right corner (N-1,
M-1) while collecting the maximum possible treasure. However, there is a catch he can only
move right or move down at each step, and if he steps into a trap, he loses all the treasure
and the journey ends.
Find the maximum treasure that he can collect if he follows the best possible path by
avoiding traps.
Input Format: N, M and grid of NxM
Output: Maximum possible treasure or -1 if there is no such path to avoid traps while
reaching bottom right corner
You are given an integer n which represents the number of elements in the set [1, 2, 3, ...,
n]. The total number of unique permutations of this set is n! (n factorial). Each permutation
can be listed in lexicographical order.
Your task is to return the k-th permutation sequence of the numbers in the set.
Input Format:
Two integers n and k, where:
n is the length of the set, with the constraint 1 <= n <= 9.
k is the 1-based index of the permutation sequence to return, with the constraint 1 <= k <=
n!.
Output Format:
A string representing the k-th permutation sequence.
Note:
Take input in the main function and implement the code in "getPermutation" function. Not
doing so will result in penalty.
Example:
For n = 3 and k = 4, the output should be: "231"
Peter is learning cryptography and security for the first time. He is curious about the “OTP” or “One Time
Pad”. Peter decides to make an otp that ranges from 0 to 1023. To do that, Peter first takes 10 random
numbers that ranges from 0 to 255. He then converts the random numbers into their binary
representations. Then Peter performs bitwise xor of each binary number separately and gets 10 binary
digits. Forming a 10 digit binary number from the 10 digits obtained, Peter converts the 10 digit binary
number into a decimal number and bingo ! Here is the OTP.
Here is an example of the process described above: The 10 random numbers in the range 0-255 are given to
the program as inputs. The final output is the OTP.
Inputs: 0
1
2
3
4
5
6
7
8
9
After conversion of the numbers in binary will look like:
00000000
00000001
00000010
00000011
00000100
00000101
00000110
00000111
00001000
00001001
Bitwise xor follows the following property:
if we consider xor of two bits, xor (0,0)= 0, xor (0,1)= 1, xor (1,0)= 1, xor (1,1)= 0.
After bitwise xoring of each row the output will be:
0 1 1 0 1 0 0 1 1 0 (e.g. Bitwise xor of the 2nd row ‘00000001’ will be ‘1’. )
The last step is the conversion of the binary number ‘0 1 1 0 1 0 0 1 1 0 ‘ to decimal i.e. 422.
Output:
0110100110
422
Note for Output:
The output will consist of two things. One is the binary number after bitwise xor, and another is the
decimal number of the binary number after bitwise xor.
The Initial Program Template:
Note:”arr1” is a pointer to an array of pointers. arr1 being a pointer to an array of pointers, arr1[0], arr[1],
....arr[9] are pointers to arrays. Length of “arr1” is 10. Each of the 10 entries are of size “8”. You have to
write two functions. One is the declaration of the array of pointers “arr1” in the function “create_table”.
Another is “convert_to_otp”. Note that the 2nd input to the 2nd function, is an array of integers given as
input to the program. The 3rd input is a pointer to an integer which will contain the final decimal otp.
Feel free to change the template code if required.
There are N flowers arranged in a row. For each i (1 <= i <= N), the height and the beauty of
the i-th flower from the left is h_i and a_i, respectively. Here, h_1, h_2, ..., h_N are all
distinct.
Taro is pulling out some flowers so that the following condition is met:
The heights of the remaining flowers are monotonically increasing from left to right.
Find the maximum possible sum of the beauties of the remaining flowers.
Input Format:
The first line contains a single integer N.
The second line contains N space separated numbers representing heights of flowers.
The third line contains N space separated numbers representing beauties of flowers.
Output Format:
Print a sinlge integer representing the maximum sum of beauties of flowers following the
aforementioned condition.
Constraints:
1 <= N <= 20
1 <= h_i <= 100000
1 <= a_i <= 1000000000
Sample Input:
4
3142
10 20 30 40
Sample Output:
60
Explanation:
We should keep the second and fourth flowers from the left. Then, the heights would be 1,
2 from left to right, which is monotonically increasing, and the sum of the beauties would
be 20+40=60.
Let N be a positive odd number. There are N coins, numbered 1, 2, ..., N. For each i (1 <= i <= N), when coin
i is tossed, it comes up heads with probability p_i and tails with probability 1-p_i. You have tossed all the N
coins. Find the probability of having more heads than tails. You need to solve this using recursion.
Output your answer with 10 digits after the decimal.
Input Format:
The first line contains a single integer N.
The next line contains N space-separated floating point numbers representing the probability of heads for
the i-th coin.
Output Format:
Print a single number denoting the probability of having more heads than tails.
Constraints:
1 <= N <= 15
0.0 < p_i < 1.0
Sample Input:
3
0.30 0.60 0.80
Sample Output:
0.6120000000
Explanation:
The probability of having (Coin1,Coin2,Coin3)=(Head,Head,Head) is 0.3×0.6×0.8=0.144
The probability of having (Coin1,Coin2,Coin3)=(Tail,Head,Head) is 0.7×0.6×0.8=0.336
The probability of having (Coin1,Coin2,Coin3)=(Head,Tail,Head) is 0.3×0.4×0.8=0.096
The probability of having (Coin1,Coin2,Coin3)=(Head,Head,Tail) is 0.3×0.6×0.2=0.036
Thus, the probability of having more heads than tails is 0.144+0.336+0.096+0.036=0.612
Sample Input:
1
0.50
Sample Output:
0.5000000000
Explanation:
The only way to get more heads than tails is (Coin1)=(Head), the probability for which is 0.5
You and I participated in a game show and won N gift cards, each worth some amount of
money (values might repeat, but each card is distinct). Splitting them equally is tedious, so
here’s my plan: We each take some cards such that the sum of my cards equals the sum of
yours, and we give the remaining cards to our friends (celebrating happiness together!). I’m
fascinated by counting, so I challenge you to find the number of ways we can pick two
disjoint subsets—one for me, one for you—with equal sums.
Note 1: Treat cards with the same value (e.g., two cards worth 10) as different cards.
Note 2: If I get subset A and you get B in one way, you getting A and me getting B counts as
a different way.
Note 3: We might be so generous that we both take no cards, giving everything to our
friends.
Input: First line contains an integer N (<= 15). Second line contains N space-separated
integers (<= 10^10).
Output: A single integer, the number of ways to choose two disjoint subsets with equal
sums.
Sample Input:
3
112
Sample Output:
5
Explanation: For N = 3 with cards [1, 1, 2] (call them 1a, 1b, 2 to distinguish them), we need
two disjoint subsets with equal sums. The possible ways are:
Both empty: ({}, {}) (sum 0 = 0), remaining [1a, 1b, 2] to friends.
I take 1a, you take 1b: ({1a}, {1b}) (sum 1 = 1), remaining [2] to friends.
I take 1b, you take 1a: ({1b}, {1a}) (sum 1 = 1), remaining [2] to friends (distinct per Note 2).
I take both 1s, you take 2: ({1a, 1b}, {2}) (sum 1+1 = 2), nothing to friends.
I take 2, you take both 1s: ({2}, {1a, 1b}) (sum 2 = 1+1), nothing to friends.
Total: 5 ways. Other combinations (e.g., ({1a}, {2})) give unequal sums and are excluded.
Given an array of N integers, write a recursive function to compute the sum of all possible
subset sums. That is, generate all subsets, calculate their sum, and return the total sum of all
these subset sums.
Input:
N=3
arr = {1, 2, 3}
Output:
24
Explanation:
All subsets and their sums:
{}
-> 0
{1} -> 1
{2} -> 2
{3} -> 3
{1,2} -> 3
{1,3} -> 4
{2,3} -> 5
{1,2,3} -> 6
Total sum = 0 + 1 + 2 + 3 + 3 + 4 + 5 + 6 = 24
Given an integer N, write a recursive function to generate all possible valid parentheses
combinations of length 2N.
A string is valid if:
Every opening parenthesis '(' has a corresponding closing parenthesis ')'.
The parentheses are balanced, meaning that for every opening parenthesis, there's a
corresponding closing parenthesis, and they are properly nested, with no closing parenthesis
appearing before its corresponding opening parenthesis.
Input:
N=3
Output:
((()))
(()())
(())()
()(())
()()()
Given a string s consisting of digits from 0-9, a fibonacci split of the string is defined as a
partition of the string into n parts p_1, p_2,.. p_n such that:
n >= 3
0 <= p_i <= 2^31
p_i + p_(i+1) = p_(i+2) for all i in [1, n-2]
for any i, p_i must not have leading zeroes except when p_i is 0 itself
For example, for the string "123456579", [123, 456, 579] is a valid fibonacci split and for the
string "1101111", [11, 0, 11, 11] and [110, 1, 111] are valid fibonacci splits.
Given an input string, your task is to find the total number of valid fibonacci splits and also
the splits. You have to implement the function find_fibonacci_splits whose return type is
int**, (essentially a 2D matrix) where the first row contains a single element return_size
which is the total number of valid splits and the next return_size rows of the matrix
represents a fibonacci split, the first element being the number of partitions for that
particular split and then the further elements represent the actual elements in the split.
For example, the string "123456579" has only 1 valid fibonacci splits [123, 456, 579]. So you
will return a 2D matrix with only 2 rows where the first row will contain the integer 1
denoting the total number of splits. The first element of the second row will be 3, denoting
the number of elements in the split and the next 3 elements in the second row will be 123,
456, 579 in order.
Input format:
The input will contain 1 line, representing the string.
Output format:
The first line of the output will contain a single integer n, representing the number of splits.
Each of the next n lines will contain a split.
There is a print function embedded in the driver code. This will print the output on the
screen. Don't change the print function at all, the testcases will fail. You just have to
implement the find_fibonacci_splits function and any other helper function you may want
to add.
The maximum length of the input string will be 20.
You are developing a Convolutional Neural Network (CNN) for image recognition, but you forgot to include a pooling
function in your library. Pooling is an essential step in CNNs that reduces the size of an image while preserving important
features. Instead of using an external library, you decide to implement pooling manually using dynamic memory
allocation.
Pooling works by dividing an image into small non-overlapping regions (e.g., 2×2) and applying a function to each region:
1. Max-Pooling: Selects the largest value in each region, keeping dominant features (e.g., edges, shapes).
2. Min-Pooling: Selects the smallest value, emphasizing subtle patterns (e.g., shadows, textures).
Your task is to apply pooling (either min or max) to a 2D matrix representing a grayscale image and output the reduced
matrix.
Input Format:
1. First line: Two integers N and M (1 <= N, M <= 100) — representing the number of rows and columns in the matrix.
2. Second line: A single integer P (1 <= P <= min(N, M)) — the pooling size. N and M must be divisible by P.
3. Third line: A single character T, which determines the pooling type: 'm' for Max-Pooling and 'n' for Min-Pooling. It is
case sensitive.
4. Next N lines: Each line contains M integers (0 to 255), representing the grayscale pixel values of the image.
Output Format:
Return a (N/P) × (M/P) pooled matrix after applying the specified pooling operation.
Note:
1. Use dynamic memory allocation (malloc and free) to efficiently handle different matrix size
Example Test Case 1:
Input:
44
2
m
1 3 2 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
6 8
14 16
Explanation:
In this test case, the given input matrix is of size 4×4, and the pooling size is 2×2, meaning we will divide the matrix into
non-overlapping 2×2 blocks. Since the pooling type is 'm' (max-pooling), we take the largest value from each 2×2 block.
The first block (top-left) consists of the numbers {1, 3, 5, 6}, where the maximum value is 6. And similarly for others.
Example Test Case 2:
Input:
44
2
n
1 3 2 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
1 2
9 11
You were working on a data transmission system where strings were being serialized before
being sent over the network. However, the receiver on the other end forgot to implement
the deserialization logic. Now, your task is to restore the original array of strings from a
given serialized input.
The serialized format follows these rules:
1. Each string is stored with its length followed by a delimiter (~) at the end.
2. Only lowercase English alphabets (a-z) are considered valid in the deserialized output.
For example, a serialized version of ["apple", "banana", "cherry"] would be:
apple5~banana6~cherry6~
Your task is to extract and store these words dynamically in an array and print in one line
each.
Input Format:
A single line containing the serialized string.
Output Format:
Print each restored string on a new line.
Constraints:
1. 1 <= Length of Serialized String <= 10^5
2. 1 <= Number of Words <= 10^4
3. Each word contains only lowercase English letters (a-z).
Sample Test Case 1:
Input:
apple5~banana6~cherry6~
Output:
apple
banana
cherry
Sample Test Case 2:
Input:
hello5~world5~test4~
Output:
hello
world
test
Timmy is exploring a m × n grid, but this time, the grid is filled with obstacles and costs.
- Some cells contain obstacles (-1), which Timmy cannot step on.
- Other cells have a cost value (1-9), representing the energy required to step on them.
- Timmy starts at the top-left corner (0,0) and must reach the bottom-right corner (m-1, n1) with the minimum total cost.
- He can only move right or down at each step.
Your task is to determine the minimum cost required for Timmy to reach the goal. If no
valid path exists, return -1.
Note:
1. Use dynamic memory allocation (malloc and free) to efficiently handle memory.
Input Format
----------------mn
grid[0][0] --- grid[0][n - 1]
|
|
grid[m - 1][0] --- grid[m - 1][n - 1]
Constraints
--------------m, n <= 10
Sample Input
-----------------33
1 31
1 -1 1
4 21
Sample Output
-------------------7
Explanation
---------------Timmy can take the minimum cost path:
1 -> (Right) 3 -> (Down) 1 -> (Down) 2 -> (Right) 1
Total cost = 7
Write a C program that removes duplicate nodes from a sorted singly linked list. Your
program should not use any extra space and must perform the operation in-place.
Input:
A singly linked list where the elements are sorted in ascending order.
The linked list may have duplicate nodes.
Output:
A modified linked list with all duplicates removed.
Example 1:
Input:
5
11233
Output:
123
Example 2:
Input:
6
111233
Output:
123
Note:
Implement the fuctions shown in the template. Do not change the given syntax to solve the
problem
You are given two sorted singly linked lists. Your task is to merge them into a single sorted
linked list. The merged linked list should also be sorted in ascending order.
You are required to implement a function that merges two sorted linked lists into one,
without using extra space (i.e., do not use arrays or other data structures to store elements).
You need to implement the solution in the given template function:
// Function to merge two sorted linked lists
struct Node* mergeSortedLists(struct Node* list1, struct Node* list2) {}
Input:
Two sorted singly linked lists list1 and list2.
Each node of the list contains an integer.
Both lists are sorted in ascending order.
Output:
A single sorted linked list that contains all the nodes from both input lists, merged together
in ascending order.
Example 1:
Input:
5
1 2 3 4 10
4
6 7 8 11
Output:
1 2 3 4 6 7 8 10 11
Example 2:
Input:
3
138
5
24567
Output:
12345678
Constraints:
The number of nodes in each list can vary.
The nodes in both linked lists are already sorted.
Do not change the initial given template.
You are given a number n which represents the number of nodes in a singly linked list. Each of the following n lines
contains information for a node in the format:
age name
Where:
age is an integer (e.g., 25)
name is a string with a maximum of 10 characters (e.g., "Alice")
Your task is to complete the given C program that:
Constructs a singly linked list using the provided input.
Sorts the linked list in ascending alphabetical order of names.
If two nodes have the same name, the one with the higher age comes first.
Finally, the sorted list should be printed, each node on a new line in the format:
What You Need to Implement:
You are given only the main() function. Your task is to implement the following functions:
1) Node* createNode(int age, char* name)
Allocates memory for a new node
Stores age and name in the node
Initializes the next pointer to NULL
Returns a pointer to the new node
2) void sortList(Node* head)
Sorts the linked list alphabetically by name
If names are the same, the node with the higher age should come first
You can use any sorting technique of your choice
3) void printList(Node* head)
Prints each node of the linked list in the format:
age name
Input Format:
First line: Integer n (number of nodes)
Next n lines: Each line contains an integer and a string separated by space
Output Format:
n lines: each with the age and name of the sorted linked list node
Constraints:
1 <= n <= 1000
1 <= age <= 120
name contains only alphabetical characters (no spaces)
Sample Input:
4
25 Alice
30 Bob
22 Alice
35 Charlie
Sample Output:
25 Alice
22 Alice
30 Bob
35 Charlie
Note:
Any solution that does not use a linked list or does not follow the above pattern will receive a zero.
You’re managing a messaging app. Each message in a group chat is stored as a node in a singly linked list.
Each message has:
An integer timestamp
A string username (max 10 chars)
A string message content (max 100 chars)
There are n messages, each on a new line in the format:
timestamp username content
Your task is to:
Build a linked list of messages.
Remove all duplicate messages from the same user — i.e., if a user sends the same content more than once, only keep their first such message.
Finally, print the cleaned chat messages in order of appearance.
What you need to implement?
You are given int main() with input logic. Your task is to implement the following four functions:
1) Node* createMessage(int timestamp, char* username, char* content)
Purpose:
Creates a new node representing a message.
Parameters:
timestamp: Integer representing when the message was sent.
username: The name of the user who sent the message (max 10 characters).
content: The actual message text (max 100 characters).
Returns:
A pointer to the newly created node.
2) Node* removeDuplicates(Node* head)
Purpose:
Builds a new linked list excluding duplicate messages from the same user.
Parameters:
head: The head of the original linked list.
Returns:
The head of the new cleaned linked list.
3) void printChat(Node* head)
Purpose:
Prints the linked list in the required format.
Parameters:
head: The head of the final linked list.
Input Format:
n
timestamp1 username1 content1
timestamp2 username2 content2
...
timestampn usernamen contentn
Output Format:
timestamp username content
(Only for messages that are not duplicates from the same user in same order as input)
Constraints
1 <= n <= 1000
0 <= timestamp <= 100000
username: max 10 lowercase letters
content: max 100 printable characters, no spaces in this version (or enclose in quotes if using spaces)
Sample Input:
6
101 alice hello
102 bob hi
103 alice hello
104 bob hi
105 alice hey
106 bob hey
Sample Output:
101 alice hello
102 bob hi
105 alice hey
106 bob hey
This problem is aimed at giving you a flavor of designing a system.
You are approached by an online delivery shipping firm, which asks you to write them code for some tasks they face. The products they ship have some
attributes, which are as follows:
Product ID (Integer) [This is unique for every product]
Product label (String)
Manufacturer (String)
All strings are of maximum length 100 and contain only alphanumeric characters.
The products arrive one by one, and a common queue is maintained for all of them. Also, there is a fixed set of manufacturers the company has a tie-up with:
Nike
Adidas
Reebok
Puma
Diadora
You are to automate some repetitive tasks. The tasks are as follows:
1) Add a new product to the queue.
2) Deliver the next product of the queue and print the product information delivered.
3) Query how many products of a given manufacturer is currently present in the queue.
4) Query how many products of a given manufacturer has been shipped already.
Initially, the product queue is empty. It is also guaranteed that when new products are added, all information is consistent, i.e., it is a valid product from a valid
partner manufacturer.
**It is necessary to maintain the queue as a linked list and there is a penalty for not doing so.
Input Format
The first line contains an integer n, denoting the number of tasks to be performed.
The following n lines can be of the following types:
1 Product_ID Product_label Manufacturer (Eg. 1 12 Bottle Puma)
2
3 Manufacturer (Eg. 3 Adidas)
4 Manufacturer (Eg. 4 Nike)
Output Format
We are supposed to take the following actions for each type of input from {1,2,3,4}
1) Insert the product with the given attributes at the back of the queue. Then print Product_ID ADDED (Eg. 23 ADDED)
2) If the queue is non empty, remove the product at the front of the queue and print all 3 attributes of the delivered product in a space separated manner. If
queue is empty, print NOTHING TO DELIVER NOW
3) Print an integer corresponding to the answer (print -1 if the manufacturer is not a partner manufacturer)
4) Print an integer corresponding to the answer (print -1 if the manufacturer is not a partner manufacturer)
Note that all outputs are in a new line.
Example Input
6
2
1 23 Bottle Adidas
1 56 Shoes Nike
3 Adidas
2
3 Adidas
Example Output
NOTHING TO DELIVER NOW
23 ADDED
56 ADDED
1
23 Bottle Adidas
0
Explanation
Initially, queue is empty. So nothing to deliver initially.
Then 2 products added.
Query return 1 since we have 1 product of Adidas.
Adidas product delivered, so details are printed.
Query returns 0, since Adidas product has been removed from queue.
Note: A queue using a linked list is a dynamic data structure that implements the First-In, First-Out (FIFO) principle, similar to a waiting line. It's built using
nodes in a linked list, where each node holds data and a pointer to the next node. This implementation allows for efficient insertion at the rear (tail) and removal
from the front (head) of the queue.
Given the positions of houses and heaters on a horizontal line, return the minimum radius
of heaters so that those heaters could cover all houses.
Example 1:
Input:
3123
12
Output: 1
Explanation: The only heater was placed in the position 2, and if we use the radius 1
standard, then all the houses can be warmed.
Example 2:
Input:
41234
214
Output: 1
Explanation: The two heaters were placed at positions 1 and 4. We need to use a radius 1
standard, then all the houses can be warmed.
Example 3:
Input:
215
12
Output: 3
Constraints:
1 <= houses.length, heaters.length <= 3 * 10^4
1 <= houses[i], heaters[i] <= 10^9
Input Format:
The first line contains an integer n followed by n space-separated integers — the positions
of the houses.
The second line contains an integer m followed by m space-separated integers — the
positions of the heaters.
Output Format:
A single integer representing the minimum radius required for the heaters to warm all the
houses
You are given a singly linked list. The linked list is structured as:
L0 -> L1 -> ... -> Ln - 1 -> Ln
Your task is to reorder the list to follow this specific pattern:
L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ...
You must reorder the nodes themselves - you cannot modify the values in the nodes.
Complete the following function:
void reorderList(struct ListNode* head);
head: A pointer to the first node of a singly linked list.
Do not return anything from the function.
You must modify the list in-place and finally print the reordered list, with node values
separated by spaces.
Structure Details:
struct ListNode {
int val;
struct ListNode *next;
};
Examples:
Example 1:
Input: head = [1, 2, 3, 4]
Output:
1423
Example 2:
Input: head = [1, 2, 3, 4, 5]
Output:
15243
Constraints:
The number of nodes in the list is between 1 and 50000.
1 <= Node.val <= 1000
You may not change the values of the nodes, only rearrange the node links.
You must print the entire reordered list after performing the operations.
Write a program to perform two tasks involving pointer-based string manipulation. You must use pointers exclusively to manipulate strings.
Avoid using array indexing (square brackets []) or standard library string functions (strlen, strcpy, strcat, strchr, strstr, etc.). All modifications
should be performed directly on the input string in-place. You have to use pointer to solve this problem, otherwise, you will be given 0.
Part 1: Sentence Modification (Rotate and Replace)
You are required to write a function named rotate_and_replace that modifies a given sentence. The sentence will contain words separated by
spaces, and punctuation or other non-space characters within a word are considered part of that word.
Your function must perform the following steps on each word in the sentence:
Rotate each word by moving its first character to the end of that word. For example, the word "Hello" would become "elloH".
After rotating, replace every alphabetic character located at an odd-numbered position within the rotated word (positions 1, 3, 5, etc., counting
from 1) with a specified replacement character provided by the user. Non-alphabetic characters at these positions should remain unchanged.
Your function should modify the original sentence directly and use pointer manipulation only.
Constraints for Part 1:
The input sentence length will not exceed 100 characters.
No additional arrays or strings are allowed apart from the original input sentence.
Pointer-based operations only; no array indexing or built-in string library functions.
Example for Part 1:
Input sentence: Hello World!
Replacement character: #
Output sentence after modification: #l#o# #r#d!W
Part 2: Substring Occurrence Counting
You are required to write a function named count_substring_occurrences that counts and returns how many times a specified substring occurs
in the sentence obtained from Part 1.
The substring counting should include overlapping occurrences as well.
You must perform this counting exclusively using pointers.
Constraints for Part 2:
Pointer-based operations only; no array indexing or standard string functions allowed.
Example for Part 2:
Modified sentence (from Part 1): #l#o# #r#d!W
Substring to search: #o#
Output: The substring occurs 1 time.
Input Format:
Your program will receive three lines of input:
The first line contains the sentence (up to 100 characters).
The second line contains a single character, representing the replacement character.
The third line contains the substring whose occurrences you need to count in the modified sentence.
Output Format:
Your program must produce exactly two lines of output:
The first line displays the modified sentence.
The second line displays the integer count representing how many times the substring appears in the modified sentence.
Sample Input 1 :
Hello World!
#
#o#
Sample Output 1:
#l#o# #r#d!W
1
Sample Input 2 :
Good Luck, Students!
@
u@
Sample Ouput 2:
@o@G @c@,@ @u@e@t@!@
1
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )