0% found this document useful (0 votes)
165 views37 pages

IV B BCS401 Assignment-1

Uploaded by

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

IV B BCS401 Assignment-1

Uploaded by

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

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

CANARA ENGINEERING COLLEGE

Programme: B.E. CIE: ASSIGNMENT – 1 Semester: IV

Course Title: ANALYSIS AND DESIGN OF ALGORITHMS Course Code: BCS401

Date: 26/05/2024 Submission: 19/06/2024 Section: B

Group Question
No No Question
Design a code to find all the common elements in two sorted lists of numbers.
Example: For the lists 2, 5, 5, 5 and 2, 2, 3, 5, 5, 7, the output should be 2, 5, 5. What is the
1
maximum number of comparisons your algorithm makes if the lengths of the two given lists
are m and n, respectively?
Given an unsorted array of integers nums, develop a C function to find the length of the
longest consecutive elements sequence.
You must design an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2] Output: 4
2
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore, its length
is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1] Output: 9

Given an integer array arr, develop a C code to find the length of the longest subarray,
which is a mountain. Return 0 if there is no mountain subarray. An array arr is a mountain
array if and only if:
arr.length >= 3
There exists some index i (0-indexed) with 0 < i < arr.length - 1
such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
3
Example 1:
Input: arr = [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: arr = [2,2,2]
Output: 0
Explanation: There is no mountain.
Alice has some number of cards and develop a c code to rearrange the cards into groups so
that each group is of size groupSize, and consists of groupSize consecutive cards.
Given an integer array hand where hand[i] is the value written on the ith card and an
integer groupSize, return true if she can rearrange the cards, or false otherwise.
Example 1:
Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3
4 Output: true
Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]
Example 2:
Input: hand = [1,2,3,4,5], groupSize = 4
Output: false
Explanation: Alice's hand can not be rearranged into groups of 4.
G1
The MEX of an array is the minimum non-negative integer that is not present in it. For
example,
• The MEX of array [2,5,0,1] is 3, because it contains 0,1,2 and 5 but not 3.
• The MEX of array [1,2,5] is 0, because 0 is the smallest non-negative integer not
present in the array.
• The MEX of array [0,1,2,3] is 4.
1 You are given a permutation 𝑃 of the integers {0,1,2,…,𝑁−1}.

For each 𝑖 from 1 to 𝑁, develop a C code to find the number of subarrays of the permutation
𝑃 such that the MEX of the subarray is equal to 𝑖. An array 𝐵 is a subarray of an array 𝐴 if 𝐵
can be obtained from array by deletion of several (possibly, zero or all) elements from the
beginning and several (possibly, zero or all) elements from the end. In particular, an array is
a subarray of itself.
Fredo is assigned a task today. He is given an array A containing N integers. His task is to
update all elements of array to some minimum value x, that is, A[i]=x;1<=i<=N; such that
product of all elements of this new array is strictly greater than the product of all elements of
the initial array. Note that x should be as minimum as possible such that it meets the given
condition. Design a C code to find the value of x.

2
Input Format:
The first line consists of an integer N , denoting the number of elements in the array.
The next line consists of N space separated integers, denoting the array elements.
Output Format:
The only line of output consists of value of x.

You are given a string s of lowercase English letters and an integer array shifts of the same
length.Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z'
becomes 'a'). For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'. Now for each
shifts[i] = x, we want to shift the first i + 1 letters of s, x times. Develop a C function to
identify the final string after all such shifts to s are applied.

3 Example 1: Input: s = "abc", shifts = [3,5,9] Output: "rpl"


Explanation: We start with "abc".
After shifting the first 1 letters of s by 3, we have "dbc".
After shifting the first 2 letters of s by 5, we have "igc".
After shifting the first 3 letters of s by 9, we have "rpl", the answer.
Example 2: Input: s = "aaa", shifts = [1,2,3] Output: "gfd"

The Hamming distance between two integers is the number of positions at which the
corresponding bits are different. Given two integers x and y, develop a C function to find the
Hamming distance between them.

Example 1: Input: x = 1, y = 4 Output: 2

Explanation:
4
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.

Example 2: Input: x = 3, y = 1 Output: 1


G2
G3 1 A permutation of length N is an array of N integers such that every integer from 1 to N
appears exactly once. For example, [2,3,5,4,1] is a permutation of length 5 , while [1,2,2],
[4,5,1,3] are not permutations.
You are given two integers N,K. Find a permutation P of length N such that Pi+Pi+1>=K for
each 1<=i<N.
If there are multiple permutations find the lexicographically smallest one. Print -1 if no such
permutation exists.

A permutation P is lexicographically smaller than a permutation Q of the same length N if


there exists an index 1<=i<=N such that P1= Q1 , P2= Q2 …….and Pi < Qi

Sample Input
2
65
46
Sample Output
142356
-1
Consider an array of numeric strings where each string is a positive number with anywhere
from 1 to 10^6 digits. Develop a C code to sort the array's elements in non-decreasing, or
ascending order of their integer values and return the sorted array.
2
Example:
Unsorted=[‘1’, ‘200’, ‘150’, ‘3’]
Return the array ['1', '3', '150', '200'].
Given an integer array nums of size n, develop a C code to find the minimum number of
moves required to make all array elements equal. In one move, you can increment or
decrement an element of the array by 1.

Example 1:
Input: nums = [1,2,3]
Output: 2
3
Explanation:
Only two moves are needed (remember each move increments or decrements one element):
[1,2,3] => [2,2,3] => [2,2,2]

Example 2:
Input: nums = [1,10,2,9]
Output: 16
Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i],
nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].
Develop a function to return true if there is a 132 pattern in nums, otherwise, return false.

Example 1:

Input: nums = [1,2,3,4]


Output: false
Explanation: There is no 132 pattern in the sequence.
4
Example 2:
Input: nums = [3,1,4,2]
Output: true
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].

Example 3:
Input: nums = [-1,3,2,0]
Output: true
Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
G4 1 Determine which pair or pairs of elements in a array have the smallest absolute difference
between them.

Example
arr =[5,2,3,4,1]
Sorted: arr' =[1,2,3,4,5]. Several pairs have the minimum difference as 1: [(1,2),(2,3)(3,4)
(4,5)] . Return the array as [1,2,2,3,3,4,4,5] .

Note
As shown in the example, pairs may overlap.

Given a list of unsorted integers, arr , find the pair of elements that have the smallest
absolute difference between them. If there are multiple pairs, find them all.
Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all
the integers in the range [1, n] that do not appear in nums.
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
2 Output: [5,6]

Example 2:
Input: nums = [1,1]
Output: [2]
A country is represented as a matrix of the size N*M and each cell is considered to be a city.
There are Q missions and you are required to accomplish K missions to receive the tourist
certification. In each mission, you are given a source and destination and you need to travel
from source to destination. Each city contains a development cost that depicts the state of
development of the city. The development cost of a mission is considered to be the
maximum development cost in the path between source and destination. The overall
development cost for the certification is the maximum development cost of all the
accomplished missions.

Your task is to minimize the overall development cost to achieve the certificate.

Note:
A path can visit a particular cell multiple time. It is possible to go up, down, left, and right
from any cell. It is not necessary to accomplish the first K missions. You can accomplish any
3
K missions out of the given Q missions.
It is not necessary to travel from a source to a destination by using the shortest path. You are
allowed to take any path to travel from a source to a destination

Sample Input
3332
1 3 12
14 7 2
564
1112
2113
3123
Sample Output
6
4 You are given the root of a binary tree where each node has a value in the range [0,
25] representing the letters 'a' to 'z'. Develop a C code that return the lexicographically
smallest string that starts at a leaf of this tree and ends at the root.

As a reminder, any shorter prefix of a string is lexicographically smaller.


For example, "ab" is lexicographically smaller than "aba".

A leaf of a node is a node that has no children.

Example 1: Input: root = [0,1,2,3,4,3,4] Output: "dba"

Example 2: Input: root = [25,1,3,1,3,0,2] Output: "adz"

Example 3:

Input: root = [2,2,1,null,1,0,null,0]Output: "abc"


G5 Ram and Shyam each directed one movie. A reviewer rates the two movies, awarding points
on a scale from 1 to 100 for three categories: writing, originality, and direction.

The rating for Ram's movie is the triplet a = (a[0], a[1], a[2]), and the rating for Shyam's
movie is the triplet b = (b[0], b[1], b[2]).

The task is to find their comparison points by comparing a[0] with b[0], a[1] with b[1], and
1 a[2] with b[2].

If a[i] > b[i], then Ram is awarded 1 point.


If a[i] < b[i], then Shyam is awarded 1 point.
If a[i] = b[i], then neither person receives a point.
Comparison points is the total points a person earned.

Given a and b, determine their respective comparison points.


2 Given a m x n grid filled with non-negative numbers, find a path from top left to bottom
right, which minimizes the sum of all numbers along its path. Note: You can only move
either down or right at any point in time.
Example 1:
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.

Example 2:
Input: grid = [[1,2,3],[4,5,6]]
Output: 12
The array-form of an integer num is an array representing its digits in left to right order.
For example, for num = 1321, the array form is [1,3,2,1]. Given num, the array-form of an
integer, and an integer k, develop C function to return the array-form of the integer num + k.

Example 1:
Input: num = [1,2,0,0], k = 34
Output: [1,2,3,4]
Explanation: 1200 + 34 = 1234
3
Example 2:
Input: num = [2,7,4], k = 181
Output: [4,5,5]
Explanation: 274 + 181 = 455

Example 3:
Input: num = [2,1,5], k = 806
Output: [1,0,2,1]
Explanation: 215 + 806 = 1021
There is a broken calculator that has the integer startValue on its display initially. In one
operation, you can:
 multiply the number on display by 2, or
 subtract 1 from the number on display.
Given two integers startValue and target, develop a C code to return the minimum number
of operations needed to display target on the calculator.
Example 1:
Input: startValue = 2, target = 3
Output: 2
Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
4
Example 2:
Input: startValue = 5, target = 8
Output: 2
Explanation: Use decrement and then double {5 -> 4 -> 8}.

Example 3:
Input: startValue = 3, target = 10
Output: 3
Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.
G6 1 Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix arr is shown below:
123
456
989
The left-to-right diagonal 1+5+9 =15 . The right to left diagonal 3+5+9=17 . Their absolute
difference is |15-17|=2 .
Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.

Note: - 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.


- 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.

Example s='12:01:00PM' --------Return '12:01:00'.


s='12:01:00AM'-------- Return '00:01:00'.
2
Function Description

Complete the timeConversion function in the editor below. It should return a new string
representing the input time in 24 hour format.
timeConversion has the following parameter(s): string s: a time in 12 hour format
Returns :string: the time in 24 hour format
You are given a binary array nums and an integer k. A k-bit flip is choosing a subarray of
length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1
in the subarray to 0. Develop a C code to return the minimum number of k-bit flips required
so that there is no 0 in the array. If it is not possible, return -1.
Note: A subarray is a contiguous part of an array.
Example 1:
Input: nums = [0,1,0], k = 1
3 Output: 2
Explanation: Flip nums[0], then flip nums[2].

Example 2:
Input: nums = [1,1,0], k = 2
Output: -1
Explanation: No matter how we flip subarrays of size 2, we cannot make the array become
[1,1,1].
An array is squareful if the sum of every pair of adjacent elements is a perfect square. Given
an integer array nums, Develop a C code to return the number of permutations of nums that
are squareful.

Two permutations perm1 and perm2 are different if there is some index i such that
perm1[i] != perm2[i].

4 Example 1:
Input: nums = [1,17,8]
Output: 2
Explanation: [1,8,17] and [17,8,1] are the valid permutations.

Example 2:
Input: nums = [2,2,2]
Output: 1
G7 1 Two children, Lily and Ron, want to share a chocolate bar. Each of the squares has an
integer on it. Lily decides to share a contiguous segment of the bar selected such that:
The length of the segment matches Ron's birth month, and the sum of the integers on the
squares is equal to his birth day.

Determine how many ways she can divide the chocolate.

Example
s=[2,2,1,3,2]
d=4
m=2

Lily wants to find segments summing to Ron's birth day, d=4 with a length equalling his
birth month,m2 . In this case, there are two segments meeting her criteria: [2,2]and [1,3].
John Watson knows of an operation called a right circular rotation on an array of integers.
One rotation operation moves the last array element to the first position and shifts all
remaining elements right one. To test Sherlock's abilities, Watson provides Sherlock with an
array of integers. Sherlock is to perform the rotation operation a number of times then
determine the value of the element at a given position.
For each array, perform a number of right circular rotations and return the values of the
elements at the given indices.
2
Example: a=[3,4,5], k=2, queries=[1,2]
Here k is the number of rotations on a, and queries holds the list of indices to report. First
we perform the two rotations: [3.4.5]--> [5,3,4]-->[4,5,3]

Now return the values from the zero-based indices 1 and 2 as indicated in the queries
array.a[1]=5, a[2]=3

Given an m x n matrix mat, develop a C code to return an array of all the elements of the
array in a diagonal order.

Example 1:

Input: mat = [[1,2,3],[4,5,6],[7,8,9]]


Output: [1,2,4,7,5,3,6,8,9]

Example 2:
Input: mat = [[1,2],[3,4]]
Output: [1,2,3,4]
Given an integer array nums, develop a C code to return all the different possible non-
decreasing subsequences of the given array with at least two elements. You may return the
answer in any order.

Example 1:
Input: nums = [4,6,7,7]
4
Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]

Example 2:
Input: nums = [4,4,3,2,1]
Output: [[4,4]]

G8 1 Given five positive integers, find the minimum and maximum values that can be calculated
by summing exactly four of the five integers. Then print the respective minimum and
maximum values as a single line of two space-separated long integers.

Example
arr=[1,3,5,7,9]

The minimum sum is 1+3+5+7=16 and the maximum sum is 3+5+7+9=24 .

The function prints


16 24
Given a sorted integer array arr, two integers k and x, develop a C code to return the k
closest integers to x in the array. The result should also be sorted in ascending order.
An integer a is closer to x than an integer b if:

|a - x| < |b - x|, or
|a - x| == |b - x| and a < b
2
Example 1:
Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]

Example 2:
Input: arr = [1,2,3,4,5], k = 4, x = -1
Output: [1,2,3,4]
You are given an integer array nums that is sorted in non-decreasing order. Determine if it is
possible to split nums into one or more subsequences such that both of the following
conditions are true:
 Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly
one more than the previous integer).
 All subsequences have a length of 3 or more.
Return true if you can split nums according to the above conditions, or false otherwise.

A subsequence of an array is a new array that is formed from the original array by deleting
3
some (can be none) of the elements without disturbing the relative positions of the remaining
elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not).

Example 1:
Input: nums = [1,2,3,3,4,5]
Output: true
Explanation: nums can be split into the following subsequences:
[1,2,3,3,4,5] --> 1, 2, 3
[1,2,3,3,4,5] --> 3, 4, 5
A person wants to determine the most expensive computer keyboard and USB drive that can
be purchased with a give budget. Given price lists for keyboards and USB drives and a
budget, find the cost to buy them. If it is not possible to buy both items, return -1.

Example
4 b = 60
keyboards = [40, 50, 60]
drives = [5, 8,12]

The person can buy a 40 keyboards + 12 USB drives = 52, or a 50 keyboards + 8 USB drives
= 58. Choose the latter as the more expensive option and return 58.
G9 1 Given an array of integers nums sorted in non-decreasing order, find the starting and ending
position of a given target value.

If target is not found in the array, return [-1, -1].


write an algorithm with O(log n) runtime complexity.

Example 1: Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]


Example 2: Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1]
Example 3: Input: nums = [], target = 0 Output: [-1,-1]
You are given an integer array nums. The adjacent integers in nums will perform the float
division. For example, for nums = [2,3,4], we will evaluate the expression "2/3/4".
However, you can add any number of parenthesis at any position to change the priority of
operations. You want to add these parentheses such the value of the expression after the
evaluation is maximum. Develop a C code to return the corresponding expression that has
the maximum value in string format.

Note: your expression should not contain redundant parenthesis.

Example 1:
2 Input: nums = [1000,100,10,2]
Output: "1000/(100/10/2)"
Explanation: 1000/(100/10/2) = 1000/((100/10)/2) = 200
However, the bold parenthesis in "1000/((100/10)/2)" are redundant since they do not
influence the operation priority.
So you should return "1000/(100/10/2)".
Other cases:
1000/(100/10)/2 = 50
1000/(100/(10/2)) = 50
1000/100/10/2 = 0.5
1000/100/(10/2) = 2
Given an array of integers nums and an integer k, develop a C code to return the number of
contiguous subarrays where the product of all the elements in the subarray is strictly less
than k.
Example 1:
Input: nums = [10,5,2,6], k = 100
Output: 8
3 Explanation: The 8 subarrays that have product less than 100 are:
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.

Example 2:
Input: nums = [1,2,3], k = 0
Output: 0
4 We define a magic square to be an n * n matrix of distinct positive integers from 1 to n^2
where the sum of any row, column, or diagonal of length n is always equal to the same
number: the magic constant.
You will be given a 3 * 3 matrix s of integers in the inclusive range [1, 9]. We can convert
any digit a to any other digit b in the range [1, 9] at cost of | a - b |. Given s, convert it into a
magic square at minimal cost.
Print this cost on a new line.
Note: The resulting magic square must contain distinct integers in the inclusive range [1, 9].
Example
$s = [[5, 3, 4], [1, 5, 8], [6, 4, 2]]

The matrix looks like this:


534
158
642

We can convert it to the following magic square:


834
159
672
This took three replacements at a cost of |5 - 8| + |8 - 9| + |4 - 7| = 7.
Given n pairs of parentheses, write a function to generate all combinations of well-formed
parentheses.
1
Example 1: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2: Input: n = 1 Output: ["()"]
Given two integer arrays nums1 and nums2, develop a C code to return the maximum
length of a subarray that appears in both arrays.

Example 1:
Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
Output: 3
2
Explanation: The repeated subarray with maximum length is [3,2,1].

Example 2:
Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
Output: 5
Explanation: The repeated subarray with maximum length is [0,0,0,0,0].
The distance of a pair of integers a and b is defined as the absolute difference between a and
b. Given an integer array nums and an integer k, develop C function to return the kth
smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length.

Example 1:
Input: nums = [1,3,1], k = 1
Output: 0
Explanation: Here are all the pairs:
3
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.

Example 2:
Input: nums = [1,1,1], k = 2
Output: 0
Given an array of integers, determine the minimum number of elements to delete to leave
only elements of equal value.
Example
arr = [1, 2, 2, 3]
Delete the 2 elements 1 and 3 leaving arr = [2, 2]. If both twos plus either the 1 or the 3 are
deleted, it takes 3 deletions to leave either [3] or [1]. The minimum number of deletions is 2.

4 Sample Input
STDIN Function
----- --------
5 arr[] size n = 5
33213 arr = [3, 3, 2, 1, 3]

Sample Output
G10 2
G11 1 Develop a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".

Example 1: Input: strs = ["flower","flow","flight"] Output: "fl"


Example 2: Input: strs = ["dog","racecar","car"] Output: ""
Explanation: There is no common prefix among the input strings.
Design a max stack that supports peekMax and popMax operation.
 peekMax() -- Retrieve the maximum element in the stack.
2
 popMax() -- Retrieve the maximum element in the stack, and remove it. If you find
more than one maximum elements, only remove the top-most one.
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of
elements in this subset satisfies:
Si % Sj = 0 or Sj % Si = 0.

If there are multiple solutions, return any subset is fine.

3 Example 1:
Input: [1,2,3]
Output: [1,2] ([1,3] will also be ok)

Example 2:
Input: [1,2,4,8]
Output: [1,2,4,8]
The Utopian Tree goes through 2 cycles of growth every year. Each spring, it doubles in
height. Each summer, its height increases by 1 meter. A Utopian Tree sapling with a height
of 1 meter is planted at the onset of spring. How tall will the tree be after growth cycles?

For example, if the number of growth cycles is n = 5, the calculations are as follows:

Period Height
0 1
4 1 2
2 3
3 6
4 7
5 14

utopianTree function has the following parameter(s): int n: the number of growth cycles to
simulate
Returns: int: the height of the tree after the given number of cycles
G12 Given an array of distinct integers candidates and a target integer target, return a list of all
unique combinations of candidates where the chosen numbers sum to target. You may
return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two
combinations are unique if the frequency of at least one of the chosen numbers is different.

1 Example 1: Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]]


Explanation: 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple
times. 7 is a candidate, and 7 = 7. These are the only two combinations.

Example 2: Input: candidates = [2,3,5], target = 8


Output: [[2,2,2,2],[2,3,3],[3,5]]

Example 3: Input: candidates = [2], target = 1 Output: []


2 Given a string s that consists of only uppercase English letters, you can perform at most k
operations on that string. In one operation, you can choose any character of the string and
change it to any other uppercase English character. Find the length of the longest sub-string
containing all repeating letters you can get after performing the above operations.

Example 1:
Input: s = "ABAB", k = 2
Output: 4
Explanation:
Replace the two 'A's with two 'B's or vice versa.

Example 2:
Input: s = "AABABBA", k = 1
Output: 4
Explanation:
Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.
Find Largest Value in Each Tree Row.You need to find the largest value in each row of a
binary tree.

Example:
Input:

3 1
/\
3 2
/\ \
5 3 9

Output: [1, 3, 9]
Given an input string s and a pattern p, implement regular expression matching with support
for '.' and '*' where:
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).

Example 1:
4 Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:
Input: s = "aa", p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a'
once, it becomes "aa".
G13 Given an unsorted integer array nums. Return the smallest positive integer that is not present
in nums. You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary
space.

Example 1:
Input: nums = [1,2,0] Output: 3
Explanation: The numbers in the range [1,2] are all in the array.
1
Example 2:
Input: nums = [3,4,-1,1] Output: 2
Explanation: 1 is in the array but 2 is missing.

Example 3:
Input: nums = [7,8,9,11,12] Output: 1
Explanation: The smallest positive integer 1 is missing.
2 Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could
be horizontal, vertical, diagonal or anti-diagonal.

Example:
Input:
[[0,1,1,0],
[0,1,1,0],
[0,0,0,1]]
Output: 3
Compare two version numbers version1 and version2.
If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0.

You may assume that the version strings are non-empty and contain only digits and the
character. The . character does not represent a decimal point and is used to separate number
sequences. For instance, 2.5 is not "two and a half" or "half way to version three", it is the
fifth second-level revision of the second first-level revision.

You may assume the default revision number for each level of a version number to be 0. For
3 example, version number 3.4 has a revision number of 3 and 4 for its first and second level
revision number. Its third and fourth level revision number are both 0.

Example 1:
Input: version1 = "0.1", version2 = "1.1"
Output: -1

Example 2:
Input: version1 = "1.0.1", version2 = "1"
Output: 1
You are given a 0-indexed array of integers nums of length n. You are initially positioned at
nums[0]. Each element nums[i] represents the maximum length of a forward jump from
index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where: 0 <= j
<= nums[i] and i + j < n.

Return the minimum number of jumps to reach nums[n - 1].

Example 1:
4
Input: nums = [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from
index 0 to 1, then 3 steps to the last index.

Example 2:
Input: nums = [2,3,0,1,4]
Output: 2
G14 1 XYZ University has the following grading policy: Every student receives grade a in the
inclusive range from 0 to 100 . Any grade less than 40 is a failing grade.
Sam is a professor at the university and likes to round each student's grade according to
these rules:

If the difference between the grade and the next multiple of 5 is less than 3, round grade
up to the next multiple of 5.

If the value of grade is less than 38, no rounding occurs as the result will still be a failing
grade.

Examples:
grade= 84 round to 85 (85 - 84 is less than 3)
grade=29 do not round (result is less than 40)
grade=57 do not round (60 - 57 is 3 or higher)

Given the initial value of grade for each of Sam's n students, Develop a code to automate
the rounding process
Identify and group the anagrams together from a given array of strings strs. You can return
the answer in any order. An Anagram is a word or phrase formed by rearranging the letters
of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

2 Example 2:
Input: strs = [""]
Output: [[""]]

Example 3:
Input: strs = ["a"]
Output: [["a"]]

Given an m x n matrix, develop a C code to return all elements of the matrix in spiral order.
Example 1:

Input: matrix = [[1,2,3], [4,5,6], [7,8,9]]


3 Output: [1,2,3,6,9,8,7,4,5]
Example 2:

Input: matrix = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]


Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Given a string s, develop C code to return the longest palindromic substring in s.
Example 1:
Input: s = "babad"
Output: "bab"
4 Explanation: "aba" is also a valid answer.

Example 2:
Input: s = "cbbd"
Output: "bb"
G15 1 Given an array of non-negative integers.
Find out three elements from this array that form a triangle of the maximum perimeter with
the Greedy approach.
Input : {6, 1, 6, 5, 8, 4}
Output : 20
Input : {2, 20, 7, 55, 1, 33, 12, 4}
Output : Triangle formation is not possible.
Input: {33, 6, 20, 1, 8, 12, 5, 55, 4, 9}
Output: 41
You are given an integer array, coins representing coins of different denominations and an
integer amount representing a total amount of money. Develop a C code to return the fewest
number of coins that you need to make up that amount. If that amount of money cannot be
made up by any combination of the coins, return -1.
Example 1:
Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
2
Example 2:
Input: coins = [2], amount = 3
Output: -1

Example 3:
Input: coins = [1], amount = 0
Output: 0
Given the head of a singly linked list, group all the nodes with odd indices together followed
by the nodes with even indices, and return the reordered list. The first node is considered
odd, and the second node is even, and so on. Note that the relative order inside both the even
and odd groups should remain as it was in the input. You must solve the problem in O(1)
extra space complexity and O(n) time complexity.
Example 1:

3
Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]
Example 2:

Input: head = [2,1,3,5,6,4,7]


Output: [2,3,6,7,1,5,4]
4 Given an integer array nums, find the subarray with the largest sum, and return its sum.

Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.

Example 2:
Input: nums = [1]
Output: 1
Explanation: The subarray [1] has the largest sum 1.

Example 3:
Input: nums = [5,4,-1,7,8]
Output: 23
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23
G16 Find the number of ways to construct an array such that consecutive positions contain
different values.
Specifically, we want to construct an array with 𝑛 elements such that each element [contains
1 a value] between 1 and 𝑘, inclusive. We also want the first and last elements of the array to
be 1 and 𝑥. Given 𝑛, 𝑘 and 𝑥, find the number of ways to construct such an array. Use
Dynamic Programming approach solve the above prolem.
For example, for 𝑛=4, 𝑘=3 and 𝑥=2 there are 3 ways
The thief has found himself a new place for his thievery again. There is only one entrance to
this area, called root. Besides the root, each house has one and only one parent house. After a
tour, the smart thief realized that all houses in this place form a binary tree. It will
automatically contact the police if two directly-linked houses were broken into on the same
night. Given the root of the binary tree, return the maximum amount of money the thief can
rob without alerting the police.
Example 1:

2 Input: root = [3,2,3,null,3,null,1]


Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

Input: root = [3,4,5,1,3,null,1]


Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
3 Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n),
ans[i] is the number of 1's in the binary representation of i.
Example 1:
Input: n = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10

Example 2:
Input: n = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
You are given an m x n integer array grid. There is a robot 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.

An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes
cannot include any square that is an obstacle.

Return the number of possible unique paths that the robot can take to reach the bottom-right
4 corner.

G17 Consider the two integer arrays nums1 and nums2 that both have the same length. The task
is to find a pair of indices (i, j) where i < j that makes the pair beautiful. A pair is considered
beautiful if the expression |nums1[i] - nums1[j]| + |nums2[i] - nums2[j]| results in the
smallest possible value when compared to this value for all other pairs of distinct indices. In
other words, the Manhattan distance between points (nums1[i], nums2[i]) and (nums1[j],
nums2[j]) should be the smallest of all possible pairs. Apply divide and conquer algorithm.
1
If there is more than one such beautiful pair, you are asked to return the lexicographically
smallest one.
Recall that a pair (i1, j1) is said to be lexicographically smaller than another pair (i2, j2) if
either i1 < i2, or if i1 == i2 then j1 < j2. In essence, you are being asked to find the closest
two points (in terms of Manhattan distance) in the Cartesian plane, where the x and y
coordinates of the points are given by nums1 and nums2 respectively, and if there are several
pairs of points with the same smallest distance, return the pair with the smallest indices.
2 Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize
the product of those integers. Develop a C code that returns the maximum product.
Example 1:
Input: n = 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: n = 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Given two integer arrays nums1 and nums2, develop a C code that return an array of their
intersection. Each element in the result must appear as many times as it shows in both arrays
and you may return the result in any order.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
3 Output: [2,2]

Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Explanation: [9,4] is also accepted
You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb
1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
4
Example 2:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
G18 Priyanka works for an international toy company that ships by a container. Her task is to
determine the lowest-cost way to combine her orders for shipping. She has a list of item
weights. The shipping company has a requirement that all items loaded in a container must
weigh less than or equal to 4 units plus the weight of the minimum weight item. All items
that meet the requirement will be shipped in one container.

The goal is to find the smallest number of containers that can be contracted to ship the items
based on the given list of weights.
1
It is about resource allocation and be approached using the greedy algorithm concept

For example, there are items with weights w = [1,2,3,4,5,10,11,12,13]. This can be broken
into two containers: [1,2,3,4,5] and [10,11,12,13] . Each container will contain items
weighing within units of the minimum weight item i.e the minimum weight 1 will have a
group of items ≥ (1+4), since that takes 2,3,4 and 5 the next available minimum weight is 10,
so our next group will the all the weights that fall within ≥ 10 and ≤ (10+4), which in this
case is all the elements left. The answer here is 2.
2 Develop a C function to reverse only all the vowels in the string s. The vowels are 'a', 'e', 'i',
'o', and 'u', and they can appear in both lower and upper cases, more than once.
Example 1:
Input: s = "hello"
Output: "holle"
3 Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x <
10^3.
Example 1:
Input: n = 2
Output: 91
Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding
11,22,33,44,55,66,77,88,99

Example 2:
Input: n = 0
Output: 1
Given two strings word1 and word2, return the minimum number of operations required to
convert word1 to word2.
You have the following three operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
4 rorse -> rose (remove 'r')
rose -> ros (remove 'e')

Example 2:
Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
G19 A group of friends want to buy a bouquet of flowers. The florist wants to maximize his
number of new customers and the money he makes. To do this, he decides he'll multiply the
price of each flower by the number of that customer's previously purchased flowers plus 1.
The first flower will be original price,(0+1)*original price , the next will be (1+1)*original
price and so on. Given the size of the group of friends, the number of flowers they want to
purchase and the original prices of the flowers, determine the minimum cost to purchase all
1
of the flowers.

For example, if there are k=3 friends that want to buy n=4 flowers that cost c=[1,2,3,4] each
will buy one of the flowers priced [2,3,4] at the original price. Having each purchased x=1
flower, the first flower in the list,c[0] , will now cost (current purchase + previous
purchase)*c[0]=(1+1)*1=2 . The total cost will be 2+3+4+2=11 .
Given a string s, rearrange the characters of s so that any two adjacent characters are not the
same. Develop C code that return any possible rearrangement of s or return "" if not possible.
Example 1:
Input: s = "aab"
2 Output: "aba"

Example 2:
Input: s = "aaab"
Output: ""
3 Given two integer arrays pushed and popped each with distinct values, return true if this
could have been the result of a sequence of push and pop operations on an initially empty
stack, or false otherwise.
Example 1:

Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]


Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4),
pop() -> 4,
push(5),
pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle
containing only 1's and return its area.
Example 1:

4 Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],


["1","0","0","1","0"]]
Output: 6

Example 2:
Input: matrix = [["0"]]
Output: 0

Example 3:
Input: matrix = [["1"]]
Output: 1
G20 Given a square grid of characters in the range ascii[a-z], rearrange elements of each row
alphabetically, ascending. Determine if the columns are also in ascending alphabetical order,
top to bottom. Return YES if they are or NO if they are not.

Example:
grid = [‘abc’, ‘ade’, ‘efg’]
1
The grid is illustrated below.
abc
ade
efg
The rows are already in alphabetical order. The columns a a e, b d f and c e g are also in
alphabetical order, so the answer would be YES. Only elements within the same row can be
rearranged. They cannot be moved to a different row.
2 You are given an integer array nums. In one move, you can pick an index i where 0 <= i <
nums.length and increment nums[i] by 1.Write a C code that return the minimum number of
moves to make every value in nums unique.
Example 1:

Input: nums = [1,2,2]


Output: 1
Explanation: After 1 move, the array could be [1, 2, 3].
Example 2:

Input: nums = [3,2,1,2,1,7]


Output: 6
Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7].
It can be shown with 5 or less moves that it is impossible for the array to have all unique
values.
Given the root node of a binary search tree and two integers low and high, return the sum of
values of all nodes with a value in the inclusive range [low, high].
Example 1:

Input: root = [10,5,15,3,7,null,18], low = 7, high = 15


Output: 32
Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.
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

An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes
cannot include any square that is an obstacle.

Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]


Output: 2
Explanation: There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right

G21 1 You will be given a list of integers, arr, and a single integer k. Calculate the minimum
unfairness value possible with an array of ‘k’ elements from the given array. You must
create an array of length k from elements of arr such that its unfairness is minimized. Call
that array subarr. Unfairness of an array is calculated as
max(subarr) - min(subarr)
Where:
* max denotes the largest integer in subarr.
* min denotes the smallest integer in subarr.
As an example, consider the array [1,4,7,2] with a k of 2. Pick any two elements, test subarr
= [4,7].
unfairness = max(4,7) - min(4,7) = 7-4 = 3
Testing for all pairs, the solution [1,2] provides the minimum unfairness.
Note: Integers in arr may not be unique.

Input Format
* The first line contains an integer n, the number of elements in array arr.
* The second line contains an integer k.
* Each of the next n lines contains an integer arr[i] where 0<=i<=n.
Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the
matrix such that its sum is no larger than k. It is guaranteed that there will be a rectangle with
a sum no larger than k.
Example 1:

Input: matrix = [[1,0,1],[0,-2,3]], k = 2


Output: 2
Explanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max
number no larger than k (k = 2).
Example 2:

Input: matrix = [[2,2,-1]], k = 3


Output: 3
You are given an n x n binary matrix grid where 1 represents land and 0 represents water.
An island is a 4-directionally connected group of 1's not connected to any other 1's. There
are exactly two islands in grid. You may change 0's to 1's to connect the two islands to form
one island. Return the smallest number of 0's you must flip to connect the two islands.
Example 1:
Input: grid = [[0,1],[1,0]]
Output: 1
3
Example 2:
Input: grid = [[0,1,0],[0,0,0],[0,0,1]]
Output: 2

Example 3:
Input: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
Output: 1
4 A message containing letters from A-Z can be encoded into numbers using the following
mapping:

'A' -> "1"


'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters
using the reverse of the mapping above (there may be multiple ways).

For example, "11106" can be mapped into:


"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)

Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6"
is different from "06".

Given a string s containing only digits, return the number of ways to decode it.

Example 1:
Input: s = "12"
Output: 2
Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).

Example 2:
Input: s = "226"
Output: 3
Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

Example 3:
Input: s = "06"
Output: 0
Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from
"06").
G22 You have recently started playing a brand new computer game called "Mr. President". The
game is about ruling a country, building infrastructures and developing it.
Your country consists of N cities and M bidirectional roads connecting them. Each road
has assigned a cost of its maintenance. The greatest achievement in the game is called "Great
administrator" and it is given to a player who manage to have all cities in the country
connected by roads in such a way that it is possible to travel between any two cities and that
the sum of maintenance costs of these roads is not greater than K.

This is very hard to accomplish, but you are very close to do it. More precisely, you have just
discovered a new method of transforming standard roads into super roads, with cost of
maintenance just 1, due to their extreme durability. The bad news is that it is very expensive
to transform a standard road into a super road, but you are so excited that you are going to do
it anyway. In addition, because you have a lot of other expenses, you also want to first
demolish as many roads as possible in order to safe some money on their maintenance first
1
and then start working on getting the achievement. You can demolish any road in the country
and that operation does not cost you anything. Because you want to spend the absolutely
minimum money in order to get the achievement, you are interested in the smallest number
of transformations of standard roads into super roads in such a way that you can do that.

Input_format:
In the first line there are 3 integers N, M and K denoting the number of cities in the country,
the number of roads in it and the desired sum of costs of maintenance. M lines describing
these roads follow. In each of them there are 3 integers A, B and C, where A and B denote
the endpoints of the road while C denotes the cost of its maintenance.

Output:
In a single line, output the minimum number of roads which need to be transformed in order
to get the achievement. If you cannot do it no matter what, output -1.
2 Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false. A
matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.
Example 1:
Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: true
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.

Example 2:

Input: matrix = [[1,2],[2,2]]


Output: false
Explanation:
The diagonal "[1, 2]" has different elements.
Given a string s consisting of words and spaces, return the length of the last word in the
string. A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.

Example 2:
3
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.

Example 3:
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.
4 Given an input string (s) and a pattern (p), implement wildcard pattern matching with
support for '?' and '*' where:

'?' Matches any single character.


'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).

Example 1:
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa", p = "*"
Output: true
Explanation: '*' matches any sequence.

Example 3:
Input: s = "cb", p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
G23 Given a n*n matrix where all numbers are distinct, find the maximum length path (starting
from any cell) such that all cells along the path are in increasing order with a difference of 1.
We can move in 4 directions from a given cell (i, j), i.e., we can move to (i+1, j) or (i, j+1)
or (i-1, j) or (i, j-1) with the condition that the adjacent cells have a difference of 1.
Example:
1 Input: mat[][] =
{{1, 2, 9}
{5, 3, 8}
{4, 6, 7}}
Output: 4
The longest path is 6-7-8-9.
Given two strings s and t, determine if they are isomorphic. Two strings s and t are
isomorphic if the characters in s can be replaced to get t. All occurrences of a character must
be replaced with another character while preserving the order of characters. No two
characters may map to the same character, but a character may map to itself.

Example 1:
Input: s = "egg", t = "add"
Output: true
2
Example 2:
Input: s = "foo", t = "bar"
Output: false

Example 3:
Input: s = "paper", t = "title"
Output: true
3 An additive number is a string whose digits can form an additive sequence. A valid additive
sequence should contain at least three numbers. Except for the first two numbers, each
subsequent number in the sequence must be the sum of the preceding two. Given a string
containing only digits, develop a C code that return true if it is an additive number or false
otherwise.
Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1,
02, 3 is invalid.
Example 1:
Input: "112358"
Output: true
Explanation:
The digits can form an additive sequence: 1, 1, 2, 3, 5, 8.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8

Example 2:
Input: "199100199"
Output: true
Explanation:
The additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
Given an integer n, develop a C code that returns all the structurally unique BST's (binary
search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in
any order.

Example 1:
4 Input: n = 3
Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]

Example 2:
Input: n = 1
Output: [[1]]
G24 ABC National Bank has a simple policy for warning clients about possible fraudulent
account activity. If the amount spent by a client on a particular day is greater than or equal to
double the client's median spending for a trailing number of days, they send the client a
notification about potential fraud. The bank doesn't send the client any notifications until
they have at least that trailing number of prior days' transaction data. Given the number of
trailing days and a client's total daily expenditures for a period of days, find and print the
number of times the client will receive a notification over all days.

For example, d = 3 and expenditures = [10, 20, 30, 40, 50]. On the first three days, they just
collect spending data. At day 4, we have trailing expenditures of [10, 20, 30]. The median is
20 and the day's expenditure is 40. Because 40≥2∗20, there will be a notice. The next day,
our trailing expenditures are [20, 30, 40] and the expenditures are 50. This is less than 2∗30
1 so no notice will be sent. Over the period, there was one notice sent.

Note: The median of a list of numbers can be found by arranging all the numbers from
smallest to greatest. If there is an odd number of numbers, the middle one is picked. If there
is an even number of numbers, median is then defined to be the average of the two middle
values.

Sample Input 9 (no of elements) 5(size)


234236845
Sample Output 0
2

2 Given an array arr of positive integers, consider all binary trees such that:
Each node has either 0 or 2 children;
The values of arr correspond to the values of each leaf in an in-order traversal of the tree.
The value of each non-leaf node is equal to the product of the largest leaf value in its left and
right subtree, respectively. Among all possible binary trees considered, return the smallest
possible sum of the values of each non-leaf node.

A node is a leaf if and only if it has zero children.


Example 1:
Input: arr = [6,2,4]
Output: 32
Explanation: There are two possible trees shown.
The first has a non-leaf node sum 36, and the second has non-leaf node sum 32.
Example 2:

Input: arr = [4,11]


Output: 44
You are given a string s consisting only of characters 'a' and 'b'. You can delete any number
of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that
i < j and s[i] = 'b' and s[j]= 'a'. Develop a C code to find the minimum number of deletions
needed to make string s balanced.
3 Example 1:
Input: s = "aababbab"
Output: 2
Explanation: You can either:
Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or
Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb").
Given the roots of two binary trees p and q, develop a function to check if they are the same
or not.Two binary trees are considered the same if they are structurally identical, and the
nodes have the same value.
Example 1:
Input: p = [1,2,3], q = [1,2,3]
Output: true
4
Example 2:
Input: p = [1,2], q = [1,null,2]
Output: false
Example 3:
Input: p = [1,2,1], q = [1,1,2]
Output: false
G25 You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
1 [
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
2 You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional
roads between some intersections. The inputs are generated such that you can reach any
intersection from any other intersection and that there is at most one road between any two
intersections.
You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei]
means that there is a road between intersections ui and vi that takes timei minutes to travel.
You want to know in how many ways you can travel from intersection 0 to intersection n - 1
in the shortest amount of time. Return the number of ways you can arrive at your destination
in the shortest amount of time.
Example 1:

Input: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],


[4,6,2]]
Output: 4
Explanation: The shortest amount of time it takes to go from intersection 0 to intersection 6
is 7 minutes.
The four ways to get there in 7 minutes are:
-0➝6
-0➝4➝6
-0➝1➝2➝5➝6
-0➝1➝3➝5➝6
Given an integer array nums, move all the even integers at the beginning of the array
followed by all the odd integers. Develop a C function to find any array that satisfies above
condition.
Example 1:
Input: nums = [3,1,2,4]
3 Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

Example 2:
Input: nums = [0]
Output: [0]
4 Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around
its center).
Example 1:

Input: root = [1,2,2,3,4,4,3]


Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3]
Output: false
G26 Given an array coins[] of size N and a target value V, where coins[i] represents the coins of
different denominations. You have an infinite supply of each of coins. The task is to find
minimum number of coins required to make the given value V. If it’s not possible to make a
change, print -1. Use Dynamic Programming Approach to solve the above problem.
Examples:
1
Input: coins[] = {25, 10, 5}, V = 30
Output: Minimum 2 coins required We can use one coin of 25 cents and one of 5 cents

Input: coins[] = {9, 6, 5, 1}, V = 11


Output: Minimum 2 coins required We can use one coin of 6 cents and 1 coin of 5 cents
Develop a C code to generate lexicographic order string. You are given an array of n strings
strs, all of the same length. you may choose any deletion indices, and we delete all the
characters in those indices for each string. For example, if we have strs =
["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is
["bef", "vyz"]. Suppose after deletions, the final array has its elements in lexicographic order
(i.e., strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]) then return the minimum possible
number of deletion to generate lexicographic order str.

Example 1:
Input: strs = ["ca","bb","ac"]
Output: 1
Explanation:
2
After deleting the first column, strs = ["a", "b", "c"].
Now strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]).
We require at least 1 deletion since initially strs was not in lexicographic order, so the
answer is 1.

Example 2:
Input: strs = ["xc","yb","za"]
Output: 0
Explanation:
strs is already in lexicographic order, so we do not need to delete anything.
Note that the rows of strs are not necessarily in lexicographic order:
i.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...)
Design a max stack that supports Minstack and popMin operation.
 Minstack () -- Retrieve the minimum element in the stack.
3  popMin() -- Retrieve the minimum element in the stack, and remove it. If you find
more than one minimum elements, only remove the top-most one.
You must implement a solution with O(1) time complexity for each function.
4 Given the root of a binary tree, return the zigzag level order traversal of its nodes' values.
(i.e., from left to right, then right to left for the next level and alternate between).
Example 1:

Input: root = [3,9,20,null,null,15,7]


Output: [[3],[20,9],[15,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
G27 Marc loves cupcakes, but he also likes to stay fit. He eats n cupcakes in one sitting, and each
cupcake i has a calorie count c[i] . After eating a cupcake with c calories, he must walk at
least 2^j * c (where j is the number cupcakes he has already eaten) miles to maintain his
weight. Given the individual calorie counts for each of the cupcakes, find and print a long
integer denoting the minimum number of miles Marc must walk to maintain his weight. Note
that he can eat the cupcakes in any order.

1 Notes: Has to be done greedily so that you have to burn as less calories as possible
Input Format:
The first line contains an integer, N , denoting the number of cupcakes.
The second line contains N space-separated integers describing the respective calorie counts
of each cupcake, c[1]...c[n].
Output Format:
Print a long integer denoting the minimum number of miles Marc must walk to maintain his
weight.
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to
k. The same Fibonacci number can be used multiple times. Develop a C code to find
Fibonacci numbers that sum up to k.
Example 1:
Input: k = 7
Output: 2
2 Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.

Example 2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
You are given a string s, which contains stars *. In one operation, you can:
 Choose a star in s.
 Remove the closest non-star character to its left, as well as remove the star itself.
 Return the string after all stars have been removed.

Example 1:
Input: s = "abcd**cod*e"
Output: "abcoe"
3 Explanation: Performing the removals from left to right:
- The closest character to the 1st star is 'd' in "abcd**cod*e". s becomes "abc*cod*e".
- The closest character to the 2nd star is 'c' in "abc*cod*e". s becomes "abcod*e".
- The closest character to the 3rd star is 'd' in "abcod*e". s becomes "abcoe".
There are no more stars, so we return "abcoe".

Example 2:
Input: s = "erase*****"
Output: ""
Explanation: The entire string is removed, so we return an empty string.
4 Given the root of a binary tree, develop a code to identify its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root
node down to the farthest leaf node.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2:
Input: root = [1,null,2]
Output: 2
G28 Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4
directionally surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that
surrounded region.

Example 1:

Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],


["X","O","X","X"]]

Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]

Explanation: Notice that an 'O' should not be flipped if:


- It is on the border, or
- It is adjacent to an 'O' that should not be flipped.
The bottom 'O' is on the border, so it is not flipped.
The other three 'O' form a surrounded region, so they are flipped.

The frequency of an element is the number of times it occurs in an array. You are given an
integer array nums and an integer k. In one operation, you can choose an index of nums and
increment the element at that index by 1. Develop a C code that returns the maximum
possible frequency of an element after performing at most k operations.
2
Example 1:
Input: nums = [1,2,4], k = 5
Output: 3
Explanation: Increment the first element three times and the second element two times to
make nums = [4,4,4]. 4 has a frequency of 3.
3 Develop a C code to check if N and its double exist in the given array or not? Given an array
arr of integers, check if there exist two indices i and j such that:

i != j ….. where 0 <= i, j < arr.length


arr[i] == 2 * arr[j]
Example 1:
Input: arr = [10,2,5,3]
Output: true
Explanation: For i = 0 and j = 2, arr[i] == 10 == 2 * 5 == 2 * arr[j]

Example 2:
Input: arr = [3,1,7,11]
Output: false
Explanation: There is no i and j that satisfy the condition
Given an integer array nums where the elements are sorted in ascending order, convert it to a

height-balanced binary search tree.


Example 1:
Input: nums = [-10,-3,0,5,9]
4 Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:
Example 2:
Input: nums = [1,3]
Output: [3,1]
Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.
G29 Watson gives Sherlock an array of integers. His challenge is to find an element of the array
such that the sum of all elements to the left is equal to the sum of all elements to the right.
For instance, given the array
arr=[5,6,8,11],
1 8 is between two subarrays that sum to 11.
If your starting array is[1], that element satisfies the rule as left and right sum to 0.

Given arrays of integers determine whether there is an element that meets the criterion. If
there is, return YES. Otherwise, return NO.
2 The power of an integer x is defined as the number of steps needed to transform x into 1
using the following steps:
if x is even then x = x / 2
if x is odd then x = 3 * x + 1

For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 -->
16 --> 8 --> 4 --> 2 --> 1). Given three integers lo, hi and k. The task is to sort all integers in
the interval [lo, hi] by the power value in ascending order, if two or more integers have the
same power value sort them by ascending order. Return the kth integer in the range [lo, hi]
sorted by the power value. Notice that for any integer x (lo <= x <= hi) it is guaranteed that x
will transform into 1 using these steps and that the power of x is will fit in a 32-bit signed
integer.

Example 1:
Input: lo = 12, hi = 15, k = 2
Output: 13
Explanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)
The power of 13 is 9
The power of 14 is 17
The power of 15 is 17
The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element
which is 13.
Notice that 12 and 13 have the same power value and we sorted them in ascending order.
Same for 14 and 15.
Example 2:
Input: lo = 7, hi = 11, k = 4
Output: 7
Explanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6,
14].
The interval sorted by power is [8, 10, 11, 7, 9].
The fourth number in the sorted array is 7.

Given an integer array nums, develop a C ocde that returns an integer array counts where
counts[i] is the number of smaller elements to the right of nums[i].
Example 1:
Input: nums = [5,2,6,1]
Output: [2,1,1,0]
Explanation:
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
3
To the right of 1 there is 0 smaller element.

Example 2:
Input: nums = [-1]
Output: [0]

Example 3:
Input: nums = [-1,-1]
Output: [0,0]
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes
along the shortest path from the root node down to the nearest leaf node.

Example 1:
4 Input: root = [3,9,20,null,null,15,7]
Output: 2
Example 2:
Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5
G30 Given an input string s, reverse the order of the words. A word is defined as a sequence of
non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space. Note that s may
contain leading or trailing spaces or multiple spaces between two words. The returned string
should only have a single space separating the words. Do not include any extra spaces.

1 Example 1:

Input: s = "the sky is blue", Output: "blue is sky the"

Example 2:

Input: s = " hello world " , Output: "world hello"


Explanation: Your reversed string should not contain leading or trailing spaces.
2 A string s is called happy if it satisfies the following conditions:
 s only contains the letters 'a', 'b', and 'c'.
 s does not contain any of "aaa", "bbb", or "ccc" as a substring.
 s contains at most a occurrences of the letter 'a'.
 s contains at most b occurrences of the letter 'b'.
 s contains at most c occurrences of the letter 'c'.
Given three integers a, b, and c, return the longest possible happy string. If there are multiple
longest happy strings, return any of them. If there is no such string, return the empty string
"".
Example 1:
Input: a = 1, b = 1, c = 7
Output: "ccaccbcc"
Explanation: "ccbccacc" would also be a correct answer.
You have k lists of sorted integers in non-decreasing order. Develop a C function to find the
smallest range that includes at least one number from each of the k lists. We define the range
[a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.

Example 1:
Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]
Output: [20,24]
3 Explanation:
List 1: [4, 10, 15, 24,26], 24 is in range [20,24].
List 2: [0, 9, 12, 20], 20 is in range [20,24].
List 3: [5, 18, 22, 30], 22 is in range [20,24].

Example 2:
Input: nums = [[1,2,3],[1,2,3],[1,2,3]]
Output: [1,1]
4 Given the root of a binary tree and an integer targetSum, develop a code that return true if
the tree has a root-to-leaf path such that adding up all the values along the path equals
targetSum.
A leaf is a node with no children.

Example 1:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22


Output: true
Explanation: The root-to-leaf path with the target sum is shown.
Example 2:

Input: root = [1,2,3], targetSum = 5


Output: false
Explanation: There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
Example 3:
Input: root = [], targetSum = 0
Output: false
Explanation: Since the tree is empty, there are no root-to-leaf paths.

Students Groups:
4CB22CS052 – 4CB22CS053 => G1
4CB22CS054 – 4CB21CS055 => G2
4CB22CS056 – 4CB22CS057 => G3
4CB22CS058 – 4CB22CS059 => G4
4CB22CS060 – 4CB22CS061 => G5
4CB22CS062 – 4CB22CS063 => G6
4CB22CS064 – 4CB22CS065 => G7
4CB22CS066 – 4CB22CS067 => G8
4CB22CS068 – 4CB22CS069 => G9
4CB22CS070 – 4CB22CS071=> G10
4CB22CS072 – 4CB22CS073 => G11
4CB22CS074 – 4CB22CS075 => G12
4CB22CS076 – 4CB22CS077 => G13
4CB22CS078 – 4CB22CS079 => G14
4CB22CS080 – 4CB22CS081 => G15
4CB22CS082 – 4CB22CS083 => G16
4CB22CS084 – 4CB22CS085 => G17
4CB22CS086 – 4CB22CS087 => G18
4CB22CS088 – 4CB22CS089 => G19
4CB22CS090 – 4CB22CS091 => G20
4CB22CS092– 4CB22CS093 => G21
4CB22CS094 – 4CB22CS095 => G22
4CB22CS096 – 4CB22CS097 => G23
4CB22CS098 – 4CB22CS099 => G24
4CB22CS100 – 4CB22CS101 => G25
4CB21CS102 – 4CB22CS103 => G26
4CB22CS104 – 4CB22CS105 => G27
4CB22CS106 – 4CB22CS107 => G28
4CB22CS108 – 4CB22CS109 => G29
4CB22CS110 – => G30

Rubrics for Assessment:

SI.No. Criteria for Evaluation Marks


1 Punctuality in submission 1
4 Relevance, correctness of answers 1
5 Academic Honesty 1
Instructions to Students:
1. There are four questions in total for each group. Each question carries 3 marks, making a total
of 12 marks for the assignment.
2. Assignments should be submitted in handwritten format only.
3. Organize your answers in a structured format. Begin each question on a new page and clearly
label them with the question number.
4. For each question, provide:
i. Problem Statement: Clearly state the problem you are solving.
ii. Algorithm: Present a detailed algorithmic solution to the problem. Use pseudocode to
illustrate your algorithm.
iii. C Code: Write well-commented C code implementing the algorithm. Ensure your code is
readable and properly indented.
iv. Output: Include sample outputs demonstrating the functionality of your code.

5. Do not copy the assignments of other candidates. If copying is noticed, the assignments of
candidates who have copied as well as who have written originally both will be rejected.
6. The completed assignment should be submitted to the course instructor on or before 19/06/2022.
7. Evaluation criteria is tabulated in the above table, the same criteria will be adapted for all 4
questions.
8. Students are expected to take the screenshot of the output and paste it in assignment book.

Signature of Course Instructor with Date Signature of Course Coordinator with Date
Coverage of modules is adequate.

APPROVED

Signature of Senior Faculty/Expert with Date Signature of Senior Faculty/Expert with Date

Signature of Senior Faculty/Expert with Date Signature of Senior Faculty/Expert with Date

HEAD OF THE DEPARTMENT/CHAIRMAN – MODERATION COMMITTEE

You might also like