0% found this document useful (0 votes)
13 views8 pages

AP Intermediate UD

Uploaded by

Ujjawal Agarwal
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)
13 views8 pages

AP Intermediate UD

Uploaded by

Ujjawal Agarwal
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/ 8

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Advanced Programming – Intermediate Problems


Name: Udit Dagar UID: 21BCS8633
Branch: BE-CSE Section: 905-B
Subject Name: AP Lab Subject Code: 21CSP-351

• Problem 1:
Given a sorted array A of size N. Find number of elements which are less than or
equal to given element X.

int countOfElements(vector<int> A, int N, int X) {


int left = 0;
int right = N - 1;
int count = 0;

while (left <= right) {


int mid = left + (right - left) / 2;

if (A[mid] <= X) {
count = mid + 1;
left = mid + 1;
} else {
right = mid - 1;
}
}
return count;
}

• Input:
N=6
A[] = {1, 2, 4, 5, 8, 10}
X=9
• Output:
5

• Problem 2:
Given a Binary Tree with all unique values and two nodes value, n1 and n2. The task
is to find the lowest common ancestor of the given two nodes. We may assume that
either both n1 and n2 are present in the tree or none of them are present.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

TreeNode* lca(TreeNode* root, int n1, int n2) {


if (root == nullptr)
return nullptr;

vector<TreeNode*> path1, path2;

if (!findPath(root, n1, path1) || !findPath(root, n2, path2))


return nullptr;

int i;
for (i = 0; i < path1.size() && i < path2.size(); i++) {
if (path1[i] != path2[i])
break;
}

return path1[i - 1];


}

• Input:
n1 = 3 , n2 = 4
5
/
2
/\
34
• Output:
2

• Problem 3:
Serialization is the process of converting a data structure or object into a sequence of
bits so that it can be stored in a file or memory buffer, or transmitted across a
network connection link to be reconstructed later in the same or another computer
environment. Design an algorithm to serialize and deserialize a binary tree. There is
no restriction on how your serialization/deserialization algorithm should work. You
just need to ensure that a binary tree can be serialized to a string and this string can
be deserialized to the original tree structure.

Algorithm:
To serialize and deserialize a binary tree, you can use any traversal method (e.g.,
preorder, inorder, postorder). Here, I'll demonstrate serialization and deserialization
using preorder traversal. Preorder traversal ensures that the root node is visited first,
followed by its left and right subtrees.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

For serialization:
1. Perform a preorder traversal of the binary tree.
2. Append each node's value to the serialized string.
3. Use a special character (e.g., "#" or "null") to represent null nodes.
For deserialization:
1. Split the serialized string into tokens.
2. Recursively build the binary tree using the tokens.
3. When encountering a token representing a node's value, create the node.
4. When encountering a token representing null, return nullptr.

• Problem 4:
Given an array arr[] of size N, the task is to find the length of the Longest Increasing
Subsequence (LIS) i.e., the longest possible subsequence in which the elements of
the subsequence are sorted in increasing order.

int longestIncreasingSubsequence(vector<int>& arr) {


int n = arr.size();
if (n == 0)
return 0;

vector<int> dp(n, 1);

for (int i = 1; i < n; ++i) {


for (int j = 0; j < i; ++j) {
if (arr[i] > arr[j]) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
}

int max_length = 1;
for (int i = 0; i < n; ++i) {
max_length = max(max_length, dp[i]);
}

return max_length;
}

Input:
arr[] = {3, 10, 2, 1, 20}
Output:
3
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

• Problem 5:
The task is to complete the insert() function which is used to implement Insertion
Sort.

void insert(int arr[], int i) {


int key = arr[i];
int j = i - 1;

while (j >= 0 && arr[j] > key) {


arr[j + 1] = arr[j];
j--;
}

arr[j + 1] = key;
}

void insertionSort(int arr[], int n) {


for (int i = 1; i < n; i++) {
insert(arr, i);
}
}

Input:
N=5
arr[] = { 4, 1, 3, 9, 7}
Output:
13479

• Problem 6:
Given an MxN matrix where each element can either be 0 or 1. We need to find the
shortest path between a given source cell to a destination cell. The path can only be
createdout of a cell if its value is 1.

int shortestPath(int mat[ROW][COL], Cell src, Cell dest) {


if (mat[src.row][src.col] == 0 || mat[dest.row][dest.col] == 0)
return -1;

int rowNum[] = {-1, 0, 0, 1};


int colNum[] = {0, -1, 1, 0};

queue<Cell> q;

bool visited[ROW][COL] = {false};


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
visited[src.row][src.col] = true;
q.push(src);

int dist[ROW][COL] = {0};

while (!q.empty()) {
Cell curr = q.front();
q.pop();

if (curr.row == dest.row && curr.col == dest.col)


return dist[curr.row][curr.col];

for (int i = 0; i < 4; i++) {


int row = curr.row + rowNum[i];
int col = curr.col + colNum[i];
if (isValid(row, col) && mat[row][col] && !visited[row][col]) {
visited[row][col] = true;
q.push({row, col});
dist[row][col] = dist[curr.row][curr.col] + 1;
}
}
}

return -1;
}

Input:
mat[ROW][COL] = {{1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{1, 0, 1, 0, 1, 1, 1, 0, 1, 1 },
{1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
{0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
{1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
{1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
{1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }};
Source = {0, 0};
Destination = {3, 4};
Output:
Shortest Path is 11
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

• Problem 7:
Given a linked list of N nodes. The task is to reverse this list.

ListNode* reverseLinkedList(ListNode* head) {


ListNode* prev = nullptr;
ListNode* curr = head;
ListNode* next = nullptr;

while (curr != nullptr) {


next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}

return prev;
}

Input:
LinkedList: 1->2->3->4->5->6
Output: 6 5 4 3 2 1

• Problem 8:
Given two strings S and P where S consists of only lowercase English alphabets
while P consists of lowercase English alphabets as well as special characters ‘.’and
‘*’, the task
is to implement a function to test regular expression such that:
'.' Matches any single character.
'*' Matches zero or more of the preceding elements.

bool isMatch(string s, string p) {


int m = s.size();
int n = p.size();

vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));

dp[0][0] = true;
for (int j = 1; j <= n; j++) {
if (p[j - 1] == '*')
dp[0][j] = dp[0][j - 2];
}

for (int i = 1; i <= m; i++) {


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
for (int j = 1; j <= n; j++) {
if (s[i - 1] == p[j - 1] || p[j - 1] == '.') {
dp[i][j] = dp[i - 1][j - 1];
} else if (p[j - 1] == '*') {
dp[i][j] = dp[i][j - 2];
if (p[j - 2] == s[i - 1] || p[j - 2] == '.')
dp[i][j] = dp[i][j] || dp[i - 1][j];
}
}
}

return dp[m][n];
}

Input: s = "aaa", p = "a"


Output: false

• Problem 9:
Given the head of a singly linked list, reverse the list, and return the reversed list.

ListNode* reverseList(ListNode* head) {


ListNode *prev = nullptr;
ListNode *curr = head;
ListNode *next = nullptr;

while (curr != nullptr) {


next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}

return prev;
}

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


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

• Problem 10:
Given a sorted array of distinct integers and a target value, return the index if the
target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n) runtime complexity.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Algorithm:
1. Initialize two pointers left and right to the beginning and end of the sorted
array nums, respectively.
2. Iterate while left is less than or equal to right: a. Calculate the middle index
mid as left + (right - left) / 2. b. If the element at index mid is equal to the
target, return mid. c. If the element at index mid is less than the target, update
left = mid + 1. d. If the element at index mid is greater than the target, update
right = mid - 1.
3. If the target is not found during the iteration, return the left index, which
represents the index where the target should be inserted.
This algorithm utilizes binary search to find the target value or determine the index
where it should be inserted in the sorted array. It achieves a time complexity of O(log
n), where n is the number of elements in the array.

You might also like