0% found this document useful (0 votes)
47 views

Practice DSA Problems ET

Uploaded by

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

Practice DSA Problems ET

Uploaded by

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

DSA Practice Problems For ET

(by bharat)

Q1. Detect cycle in a directed graph

Given a Directed Graph with V vertices (Numbered from 0 to V-1) and E edges, check
whether it contains any cycle or not.

Input:
First line contains two integers V and E which represent the number of vertex
and number of edges in directed graph respectively.

Next all lines contains two integers v1 and v2which represent the two vertex
and edge between it.
Output:
Print true or false (graph has cycle or not)

Example test case:


Input Output
5 5 true
1 2
2 3
3 1
1 4
2 0

Q2. Number of Islands

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's
(water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands
horizontally or vertically. You may assume all four edges of the grid are all surrounded
by water.

Input:
First line contains two integers m and n which represent the number of rows
and number of columns in 2D binary grid respectively.

Next all lines contains all elements of matrix.


Output:
Print integer which represent the number of islands in 2D grid
Example test case:
Input Output
5 5 4
1 0 1 0 1
1 1 0 1 1
1 0 0 0 1
0 1 1 1 0
0 0 1 0 0

Q3. check graph is bipartite

There is an undirected graph with n nodes, where each node is numbered between 0
and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that
node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge
between node u and node v. The graph has the following properties:

➔ There are no self-edges (graph[u] does not contain u).


➔ There are no parallel edges (graph[u] does not contain duplicate values).
➔ If v is in graph[u], then u is in graph[v] (the graph is undirected).
➔ The graph may not be connected, meaning there may be two nodes u and v such
that there is no path between them.

A graph is bipartite if the nodes can be partitioned into two independent sets A and B
such that every edge in the graph connects a node in set A and a node in set B.
Input:
First line contains two integers V and E which represent the number of vertex
and number of edges in directed graph respectively.

Next all lines contains two integers v1 and v2 which represent the two vertex
and edge between it.
Output:
print true or false (graph is bipartite or not)

Example test case:


Input Output
55 true
02
24
43
31
03

Q4. Trapping rain water

Given N non-negative integers representing an elevation map where the width of each
bar is 1, compute how much water it can trap after raining.
Input:
First line contains a integer N represents the length of array.
Second line contains all N elements of array

Output:
Print total water trapped inside array

Constraints:
1<=N<=2x10^4;

Example test case:


Input Output
11 6
1 0 2 1 0 1 3 2 1 2 1
7 7
1 5 0 3 6 2 1

Q5. Find next greater element

We are given a circular array, print the next greater number for every element. If it is
not found print -1 for that number. To find the next greater number for element Ai ,
start from index i + 1 and go uptil the last index after which we start looking for the
greater number from the starting index of the array since array is circular.
Input:

First line contains the length of the array n. Second line contains the n space separated
integers.

Output:

Print n space separated integers each representing the next greater element.

Example:

Input: 3
1 2 3

Output: 2 3 -1

Q6. ADD TWO NUMBERS

You are given two non-empty linked lists representing two non-negative integers. The
digits are stored in reverse order, and each of their nodes contains a single digit. Add
the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number
0 itself.

Input:
First line contains length of both linked list n1 and n2.
Second line contains the all n1 elements present in linked list 1
Third line contains the all n2 elements present in linked list 1

Output:
All elements of final linked which contains sum.
Example test case:
Input Output
3 3 023
632
48

Q7. Nearly sorted array

Given an array of N elements, where each element is at most K away from its
target position, devise an algorithm that sorts in O(N log K) time.

Input:
First line contains length of array n and k which represent the how much the
array element away from its target position.
Second line contains the all n elements present in array
Output:
All elements of sorted array.
Example test case:
Input Output
6 3 2 3 6 8 12 56
2 6 3 12 56 8

Q8. Nth Ugly Number

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Given an integer N, return the nth ugly number.

Example: for 10th ugly number [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first
10 ugly numbers so the 10th ugly number will be 12.

Input:
First line contains a integer N.
Output:
Print the Nth Ugly Number

Constraints:
1<=N<=1690

Example test case:


Input Output
10 12
104 1800

Q9. Find Maximum Height of binary Tree

A binary tree's maximum height is the number of nodes along the longest path from the
root node down to the farthest leaf node.

Input:
First line contains value all Nodes of Tree
Note: all -1 input denotes NULL node

Output:
Return An integer which determine maximum height

Example test case:


Input Output
1 2 3 4 6 -1 5 -1 -1 7 -1 -1 -1 -1 -1 4

Q10. Check whether tree is balanced binary tree.

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of
every node never differs by more than one.
Input:
First line contains value all Nodes of Tree
Note: all -1 input denotes NULL node

Output:
Return true or false for balanced binary tree

Example test case:


Input Output
5 6 7 3 -1 9 -1 -1 10 -1 -1 2 -1 -1 -1 false

Q11. Sum Root to Leaf Numbers

You are given the root of a binary tree containing digits from 0 to 9 only.
Each root-to-leaf path in the tree represents a number.

For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.

A leaf node is a node with no children.

Input:
First line contains value all Nodes of Tree
Note: all -1 input denotes NULL node

Output:
Return the total sum of all root-to-leaf numbers. Test cases are generated so that the
answer will fit in a 32-bit integer.

Example test case:


Input Output
1 2 3 -1 -1 -1 -1 25

Q12. Lowest Common Ancestor in Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the
tree.

The lowest common ancestor is defined between two nodes p and q as the lowest node
in T that has both p and q as descendants (where we allow a node to be a descendant
of itself).
Input:
First line contains value all Nodes of Tree
Note: all -1 input denotes NULL node

Second line contains two integers which represents the value of two nodes p
and q respectively

Output:
Return the value of lowest common ancestor of p and q node

Example test case:


Input Output
1 2 3 -1 -1 4 5 -1 -1 -1 -1 3
45

Q13. Construct a Balanced Binary search Tree from sorted array

Given an sorted array you need construct a balanced binary tree using
every element of array

Balanced binary tree: difference between left and right sub tree must be
less than or equal to 1

Input:
First line contains a integer N which denotes the size of input sorted array

Second line contains all element of array

Output:
Return the level order traversal of constructed binary search tree

Example test case:

Input Output
5 31425
12345

Q14 Kth Element form last Linked List


Given a linked list with n nodes. Find the kth element from last without computing the length of the
linked list.

Input Format

First line contains space separated integers representing the node values of the linked list. The list
ends when the input comes as '-1'. The next line contains a single integer k.

Constraints

n < 10^5

Output Format

Output a single line containing the node value at the kth element from last.

Example:

Sample Input

1 2 3 4 5 6 -1
3

Sample Output

Note: The linked list is 1 2 3 4 5 6. -1 is not included in the list. So the third element from the last is
4

Q15. Triplet From LinkedList


Given three linked lists, say a, b and c, find one node from each list such that the sum of the values
of the nodes is equal to a given number say, Target. As any number of answers can be possible
return the first one you get while traversing.

Input Format

The First Line contains 3 Integers n, m and k as the Size of the Three LinedLists. Next 3 Lines
contains n, m and k integers Respectively as the elements of Linked Lists. Next Line contains the an
Integer as Target.

Constraints

The Size of the Lists can be different.

Output Format

Display the 3 elements from each of the Lists whose sum is equals to the target separated by
space.

Sample Input

3 3 3
12 6 29
23 5 8
90 20 59
101

Sample Output

6 5 90

Explanation

In the Given Sample Input, 6, 5 and 90 from lists 1, 2 and 3 respectively add to give 101.

Q16. Maximum Length of a Concatenated String with Unique Characters


Description:
You are given an array of strings arr. A string s is formed by the concatenation of
a subsequence of arr that has unique characters.
Return the maximum possible length of s.
A subsequence is an array that can be derived from another array by deleting some or no
elements without changing the order of the remaining elements.
INPUT:
First line contains a integer n which represent the size of vector of string
Second line contains all strings of vector
OUTPUT:
First line contains the length of largest string that can be form
Example Test case:
INPUT OUTPUT
3 4
un iq ue

Explanation: All the valid concatenations are:


- ""
- "un"
- "iq"
- "ue"
- "uniq" ("un" + "iq")
- "ique" ("iq" + "ue")

Maximum length is 4.

Constraints : n=size of vector of string


1<=n<=16
s[i] is string in vector of string
1<=s[i]<=26

Q17. Rat in a maze


Description
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination
at (N – 1, N – 1). Find all possible paths that the rat can take to reach from source to destination.
The directions in which the rat can move are ‘D'(down), ‘R’ (right), ‘L’ (left), ‘U’(up). Value 0 at a
cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in
the matrix represents that rat can be travel through it. Return the list of paths in
lexicographically increasing order.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot
move to any other cell.
INPUT:
First line contains a integer n which represent the number of column and rows in 2D vector
Second line contains all elements of 2D vector
OUTPUT:
First line contains all the paths that can be possible
Example Test case:
INPUT OUTPUT
3 DDRR
110 DRDR
110 RDDR
111 RDLDRR

Constraints : n=size of column and row


1<n<=10

Q18. N Queen Problem

Description:

The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two
queens attack each other.
For example, the following is a solution for the 4 Queen problem.
The expected output is in the form of a matrix that has ‘Q‘s for the blocks where queens are
placed and the empty spaces are represented by ‘.’ . For example, the following is the output
matrix for the above 4-Queen solution.
INPUT:
First line contains a integer n which represent the number of column and rows in 2D vector
OUTPUT:
First line contains all possible n queen matrix
Example Test case:
INPUT OUTPUT
4 .Q..
...Q
Q...
..Q.

..Q.
Q...
...Q
.Q..

Constraints : n=size of column and row


1<n<=10

Q19. Write a recursive function which prints subsequences of the array which
sum to target.

Input Format
Take an input N, a number. Take N more inputs and store that in an array. Take an input target (
a number).

Output Format
print the subsets in separate lines.

Constraints
0 < N < 100

Input Output

3 3
123 12
3

Explanation
The sum of all elements in the subsets {3} and {1,2} equals 3.

Q20 .Given an integer 'n'. Print all the possible pairs of 'n' balanced parentheses.
The output strings should be printed in the sorted order considering '(' has higher value than ')'.

Input Format
Single line containing an integral value 'n'.

Output Format
Print the balanced parentheses strings with every possible solution on a new line.

Input Output

2 ()()
(())

Q21.Take as input N, the size of the array. Take N more inputs and store that in an array. Take
as input M, a number. Write a recursive function which returns the last index at which M is found
in the array and -1 if M is not found anywhere. Print the value returned.

Input Format
Enter a number N and add N more numbers to an array, then enter number M to be searched

Output Format
Display the last index at which the number M is found

Sample input:

Input Output

5 3
3
2
1
2
3
2

22. Given an integer N, now you have to convert all zeros of N to 5.


Input Format
The first Line takes input integer N, denoting the number.

Output Format
Print the number after replacing all 0's with 5.

Sample test case:

Input Output

103 153

Test cases:

Input Output

103 153

10090 15595

100 155

19901 19951

50505050 55555555

Q23.Take as input N, a number. Print odd numbers in decreasing sequence (up until 0) and
even numbers in increasing sequence (up until N) using Recursion

Input Format
Take as input N

Output Format
Print odd numbers in decreasing sequence (up until 0) and even numbers in increasing
sequence (up until N)
Sample test case:

Input Output

5 5
3
1
2
4

24.You are given an N*M grid. Each cell (i,j) in the grid is either blocked, or empty. The rat can
move from a position towards left, right, up or down on the grid.
Initially rat is on the position (1,1). It wants to reach position (N,M) where it's cheese is waiting
for. If a path exists-it is always unique. Find that path and help the rat reach its cheese.

Input Format
First line contains 2 integers N and M denoting the rows and columns in the grid.
Next N line contains M characters each. An 'X' in position (i,j) denotes that the cell is blocked
and ans 'O' denotes that the cell is empty.

Output Format
Print N lines, containing M integers each. A 1 at a position (i,j) denotes that the (i,j)th cell is
covered in the path and a 0 denotes that the cell is not covered in the path.
If a path does not exists then print "NO PATH FOUND"

Sample test case:

Input Output

5 4 1 0 0 0
OXOO 1 1 0 0
OOOX 0 1 0 0
XOXO 0 1 1 0
XOOX 0 0 1 1
XXOO

Q23.Given a boolean matrix mat[M][N] of size M X N, modify it such that if a matrix cell mat[i][j]
is 1 (or true) then make all the cells of ith row and jth column as 1.

Input Format
First line contains two integers m and n denoting the dimensions of the matrix Next m lines
contain n integers each.
Output Format
Print the modified matrix

Input Output

22 11
10 10
00

24.Given an n x m matrix, where every row and column is sorted in increasing order, and a
number x . Find if element x is present in the matrix or not.

Input Format
First line consists of two space separated integers N and M, denoting the number of element in
a row and column respectively. Second line of each test case consists of N*M space separated
integers denoting the elements in the matrix in row major order. Third line of each test case
contains a single integer x, the element to be searched.

Output Format
Print 1 if the element is present in the matrix, else 0.

Sample Test Case:

Input Output

33 0
3 30 38
44 52 54
57 60 69
62

Explanation
Search the element in the sorted matrix. If the element is present print 1 otherwise print 0. In the
sample input,in first case 62 is not present in the matrix so 0 is printed. Similarly, for second
case 55 is present in the matrix so 1 is printed.

Q25.Given a N*N matrix. The task is to find the index of column with maximum sum. That is the
column whose sum of elements are maximum.
Input Format
First line contains the N ,size of the square matrix. Next N lines contains N integers each
denoting the elements of the matrix

Output Format
Print N lines each containing N elements. These are the elements of the new matrix.

Sample Input

Input Output

7 6 341
90 40 1 3 39 59 90
48 72 67 32 73 19 27
22 37 47 68 1 5 55
81 5 39 53 38 86 21
1 32 7 44 2 65 47
68 13 24 28 69 81 43
16 34 67 3 82 26 35

Explanation:
6th column has the highest sum that is 341.

26 .Given a 2D array of size N x N. Rotate the array 90 degrees anti-clockwise.

Input Format
First line contains a single integer N. Next N lines contain N space separated integers.

Output Format
Print N lines with N space separated integers of the rotated array.

Sample test case:

Input Output

4 4 8 12 16
1234 3 7 11 15
5678 2 6 10 14
9 10 11 12 1 5 9 13
13 14 15 16

Q27.Take an input N, a number. Take N more inputs and store that in an array. Take an input
target, a number
a. Write a recursive function which prints subsets of the array which sum to target.

b. Write a recursive function which counts the number of subsets of the array which sum to
target. Print the value returned.

Input Format
Take an input N, a number. Take N more inputs and store that in an array. Take an input target,
a number

Output Format
Display the number of subsets and print the subsets in a space separated manner.

Input Output

3 12 3
1 2
2
3
3

Q28.Take as input S, a string. Write a function that toggles the case of all characters in the
string. Print the value returned.

Input Format
String

Output Format:
String

Sample Input:

Input Output

abC ABc

Explanation
Toggle Case means to change UpperCase character to LowerCase character and vice-versa.
Q29.Take as input S, a string. Write a function that replaces every even character with the
character having just higher ASCII code and every odd character with the character having just
lower ASCII code. Print the value returned.

Input Format
String

Output Format
String

Sample Test Case:

Input Output

abcg badf

Q30.Take as input S, a string. Write a function that returns true if the string is a palindrome and
false otherwise. Print the value returned.
Input Format
String

Output Format
Boolean

Sample input:

Input Output

abba true

Explanation
A string is said to be palindrome if reverse of the string is same as string. For example, “abba” is
palindrome as it's reverse is "abba", but “abbc” is not palindrome as it's reverse is "cbba".

31.Take as input S, a string. Write a function that returns the character with maximum frequency.
Print the value returned.

Input Format
String

Output Format
Character

Sample Input

Input Output

aaabacb a

Explanation
For the given input string, a appear 4 times. Hence, it is the most frequent character.

Q32.Take as input a 2-d array. Print the 2-D array in spiral form anti-clockwise.

Input Format
Two integers M(row) and N(column) and further M * N integers(2-d array numbers).

Output Format
All M * N integers separated by commas with 'END' written in the end(as shown in example).

Sample Input

Input Output

44 11, 21, 31, 41, 42, 43, 44, 34, 24, 14, 13,
11 12 13 14 12, 22, 32, 33, 23, END
21 22 23 24
31 32 33 34
41 42 43 44

Explanation
For spiral level anti-clockwise traversal, Go for first column-> last row ->last column-> first row
and then do the same traversal for the remaining matrix .
Q33. Unique Paths

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.

Input Format
Two integers M(row) and N(column).

Output Format
Print the total number of unique paths can be formed

Sample Input

Input Output

45 35

Constraints : m=size of row, n= size of column


1<m,n<=600

The test cases are generated so that the answer will be less than or equal to 2 * 10^9

34. Heapy the array

You are given an array , your task is to rearrange the whole array so it can form a
max heap order

Input Format
First line contains an Integer N which represents the size of array.

Second line contains all the N elements of the array

Output Format
Print the max heap order of the array .

Sample Input
Input Output

8 10 7 9 3 4 1 5 2
2 4 1 7 10 9 5 3

Constraints : m=size of row, n= size of column


1<m,n<=600
Explanation: when all the parent node are greater than its children then the CBT is max
heap

35. Coin change

You are given an integer array coins representing coins of different


denominations and an integer amount representing a total amount of money.

You may assume that you have an infinite number of each kind of coin.

Input Format

First line contains Two Integers ‘N’ which represents the size of coins array and ‘Amount’ which
represents the total money you need to make .

Second line contains all the N elements of the coins array

Output Format

Print 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, Print -1.

Sample Input

Input Output

4 12 3
2351

Constraints : N=Coins array size, Amount= total sum


1<=N<=12
1<=Amount<=1000
36. House robber

You are a professional robber planning to rob houses along a street. Each house has a certain
amount of money stashed, the only constraint stopping you from robbing each of them is that
adjacent houses have security systems connected and it will automatically contact the police if
two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house,

Input Format

First line contains a Integers ‘N’ which represents the size of house array.

Second line contains all the N elements of the house array

Output Format

Print the maximum amount of money you can rob tonight without alerting the police

Sample Input

Input Output

5 9
14235

Constraints : N=house array size


1<=N<=100

37. Nth Fibonacci

Given a number n, print n-th Fibonacci Number.


Nth term= (N-1)th term + (N-2)th term

Note : As the answer might be large, return the final answer modulo 10^9 + 7

Input Format

First line contains a Integers ‘N’.


Output Format

Print Nth Fibonacci Number

Sample Input

Input Output

Constraints : N=term number you need to find


1<=N<=10000

38. Jump game

You are given an integer array nums. You are initially positioned at the array's first index, and
each element in the array represents your maximum jump length at that position.

Input Format

First line contains a Integers ‘N’ which represents the size of nums array.

Second line contains all the N elements of the nums array

Output Format

Print true if you can reach the last index, or false otherwise.

Sample Input

Input Output

5 true
23114

Constraints : N=size of nums array


1<=N<=10000

You might also like