You are on page 1of 35

1.

program to find the smallest number which greater than a given number and has same set of digits
as given number
#include <stdio.h>
#include <string.h>
// Function to swap two digits in a string
void swap(char *str, int i, int j) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}

// Function to find the smallest number greater than num with the same set of digits
void findNextNumber(char *num) {
int n = strlen(num);
int i;

// Find the rightmost digit that is smaller than the digit to its right
for (i = n - 2; i >= 0; i--) {
if (num[i] < num[i + 1]) {
break;
}
}

// If no such digit is found, then there is no next number


if (i == -1) {
printf("No greater number with the same set of digits.\n");
return;
}

// Find the smallest digit on the right side of num[i] that is greater than num[i]
int smallestGreater = i + 1;
for (int j = i + 2; j < n; j++) {
if (num[j] > num[i] && num[j] < num[smallestGreater]) {
smallestGreater = j;
}
}

// Swap the digits at positions i and smallestGreater


swap(num, i, smallestGreater);

// Sort the digits to the right of i in ascending order


for (int j = i + 1; j < n - 1; j++) {
for (int k = i + 1; k < n - 1; k++) {
if (num[k] > num[k + 1]) {
swap(num, k, k + 1);
}
}
}

printf("The next greater number with the same set of digits: %s\n", num);
}

int main() {
char num[20];
printf("Enter a number: ");
scanf("%s", num);
findNextNumber(num);
return 0;
}
Output:
Enter a number: 123
The next greater number with the same set of digits: 132
P2: Given a set of time intervals in any order, merge all overlapping intervals into one and output the
result which should have only mutually exclusive intervals.
#include<stdlib.h>
#include<stdlib.h>
struct interval
{
int start;
int end;
};
int CompareIntervals(const void *a,const void *b)
{
return ((struct interval *)a)->start-((struct interval *)b)->start;
}
void mergeIntervals(struct interval intervals[],int n)
{
if(n<=0)
return;
qsort(intervals,n,sizeof(struct interval),CompareIntervals);
int resultIndex =0;
for(int i=1;i<n;i++)
{
if(intervals[resultIndex].end>=intervals[i].start)
{

intervals[resultIndex].end=intervals[i].end>intervals[resultIndex].end?intervals[i].end:intervals[resultI
ndex].end;
}
else
{
resultIndex++;
intervals[resultIndex] = intervals[i];
}
}
printf("merged intervals :\n");
for(int i=0;i<=resultIndex;i++)
{
printf("[ %d,%d]",intervals[i].start,intervals[i].end);

printf("\n");
}

int main()
{
struct interval intervals[]= {{1,3},{2,16},{8,10},{15,18}};
int n =sizeof(intervals)/sizeof(intervals[0]);
mergeIntervals(intervals,n);
return 0;
}
output:
merged intervals :
[ 1,18]
P3 : Given an expression string exp, write a program to examine whether the pairs and the orders of
“{“, “}”, “(“, “)”, “[“, “]” are correct in the given expression.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

// Structure to represent a stack


struct Stack {
char data;
struct Stack* next;
};

typedef struct Stack Stack;

// Function to initialize a new stack


Stack* createStack() {
return NULL;
}

// Function to check if the stack is empty


bool isEmpty(Stack* stack) {
return stack == NULL;
}

// Function to push an element onto the stack


Stack* push(Stack* stack, char item) {
Stack* newNode = (Stack*)malloc(sizeof(Stack));
newNode->data = item;
newNode->next = stack;
return newNode;
}
// Function to pop an element from the stack
Stack* pop(Stack* stack) {
if (isEmpty(stack)) {
printf("Error: Trying to pop from an empty stack.\n");
exit(1);
}
Stack* temp = stack;
stack = stack->next;
free(temp);
return stack;
}

// Function to check if two characters are a matching pair


bool isMatchingPair(char char1, char char2) {
return (char1 == '(' && char2 == ')') ||
(char1 == '{' && char2 == '}') ||
(char1 == '[' && char2 == ']');
}

// Function to check if an expression has balanced pairs


bool isBalancedExpression(const char* expression) {
Stack* stack = createStack();

for (int i = 0; expression[i]; i++) {


if (expression[i] == '(' || expression[i] == '{' || expression[i] == '[') {
stack = push(stack, expression[i]);
} else if (expression[i] == ')' || expression[i] == '}' || expression[i] == ']') {
if (isEmpty(stack)) {
return false;
}

if (!isMatchingPair(stack->data, expression[i])) {
return false;
}

stack = pop(stack);
}
}

return isEmpty(stack);
}

int main() {
char expression[100];
printf("Enter an expression: ");
scanf("%s", expression);

if (isBalancedExpression(expression)) {
printf("The expression is balanced.\n");
} else {
printf("The expression is not balanced.\n");
}

return 0;
}
Output:
Enter an expression: [[]]
The expression is balanced.
4.Given an array, print the Next Greater Element (NGE) for every element.

#include <stdio.h>
// Function to find and print the Next Greater Element for each element
void printNGE(int arr[], int size) {
int nextGreater[size]; // Array to store NGE for each element
int stack[size]; // Stack to keep track of indices

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


nextGreater[i] = -1; // Initialize as -1, indicating no NGE found yet
}

int top = -1; // Initialize the stack top

// Process each element in the array


for (int i = 0; i < size; i++) {
// Check if the stack is not empty and the current element is greater
// than the element at the index stored in the stack
while (top >= 0 && arr[i] > arr[stack[top]]) {
nextGreater[stack[top]] = arr[i]; // Set NGE for the element in the stack
top--; // Pop the element from the stack
}
// Push the current element's index onto the stack
stack[++top] = i;
}

// Print the NGE for each element


for (int i = 0; i < size; i++) {
printf("NGE for %d = %d\n", arr[i], nextGreater[i]);
}
}

int main() {
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);

int arr[size];
printf("Enter the elements of the array:\n");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

printf("Next Greater Elements:\n");


printNGE(arr, size);

return 0;
}
Output:
Enter the size of the array: 3
Enter the elements of the array:
1
2
3
Next Greater Elements:
NGE for 1 = 2
NGE for 2 = 3
NGE for 3 = -1
5.Given an array of integers heights representing the histogram's bar height where the width of each
bar is 1, return the area of the largest rectangle in the histogram.
#include <stdio.h>
#include <stdlib.h>

#define MAX(a, b) ((a) > (b) ? (a) : (b))

typedef struct {
int height;
int index;
} StackElement;

int largestRectangleArea(int* heights, int heightsSize) {


int maxArea = 0;
StackElement* stack = malloc(sizeof(StackElement) * (heightsSize + 1));
int stackTop = -1;

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


int currentHeight = (i == heightsSize) ? 0 : heights[i];

while (stackTop >= 0 && stack[stackTop].height > currentHeight) {


int poppedHeight = stack[stackTop].height;
stackTop--;

int width = (stackTop < 0) ? i : (i - stack[stackTop].index - 1);


maxArea = MAX(maxArea, width * poppedHeight);
}

stackTop++;
stack[stackTop].height = currentHeight;
stack[stackTop].index = i;
}
free(stack);
return maxArea;
}

int main() {
int heights[] = {2, 1, 5, 6, 2, 3};
int heightsSize = sizeof(heights) / sizeof(heights[0]);

int result = largestRectangleArea(heights, heightsSize);


printf("The largest rectangle area is: %d\n", result);

return 0;
}
Output:
The largest rectangle area is: 10
P6: Given a Linked List and a number N, write a function that returns the value at the Nth node from
the end of the Linked List
#include <stdio.h>
#include <stdlib.h>
// Definition for singly-linked list.
struct ListNode {
int val;
struct ListNode *next;
};

int getNthFromEnd(struct ListNode* head, int n) {


struct ListNode* fast = head;
struct ListNode* slow = head;

// Move the fast pointer n nodes ahead


for (int i = 0; i < n; i++) {
if (fast == NULL) {
return -1; // Assuming -1 indicates an error
}
fast = fast->next;
}

// Move both pointers simultaneously until fast reaches the end


while (fast != NULL) {
fast = fast->next;
slow = slow->next;
}

return slow->val;
}

// Helper function to create a new node


struct ListNode* newNode(int val) {
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = val;
node->next = NULL;
return node;
}

int main() {
struct ListNode* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(5);

int n = 2; // Get the value of the 2nd node from the end

int result = getNthFromEnd(head, n);


if (result != -1) {
printf("The value at the %dth node from the end is: %d\n", n, result);
} else {
printf("Invalid value of n or empty list.\n");
}

// Free the memory allocated for the linked list nodes


struct ListNode* current = head;
while (current != NULL) {
struct ListNode* temp = current;
current = current->next;
free(temp);
}

return 0;
}
Output:
The value at the 2th node from the end is: 4
7.Merge Two sorted Linked Lists

#include <stdio.h>
#include <stdlib.h>

// Define the structure for a linked list node


struct Node {
int data;
struct Node* next;
};

// Function to insert a new node at the end of a linked list


struct Node* append(struct Node* head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;

if (head == NULL) {
head = newNode;
} else {
struct Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}

return head;
}

// Function to merge two sorted linked lists


struct Node* mergeSortedLists(struct Node* list1, struct Node* list2) {
struct Node* mergedList = NULL;
struct Node* tail = NULL;

while (list1 != NULL && list2 != NULL) {


if (list1->data <= list2->data) {
if (mergedList == NULL) {
mergedList = list1;
tail = list1;
} else {
tail->next = list1;
tail = list1;
}
list1 = list1->next;
} else {
if (mergedList == NULL) {
mergedList = list2;
tail = list2;
} else {
tail->next = list2;
tail = list2;
}
list2 = list2->next;
}
}

if (list1 != NULL) {
tail->next = list1;
} else if (list2 != NULL) {
tail->next = list2;
}

return mergedList;
}
// Function to display a linked list
void displayList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}

int main() {
struct Node* list1 = NULL;
struct Node* list2 = NULL;

// Populate the linked lists with sorted data


list1 = append(list1, 1);
list1 = append(list1, 3);
list1 = append(list1, 5);

list2 = append(list2, 2);


list2 = append(list2, 4);
list2 = append(list2, 6);

printf("List 1: ");
displayList(list1);
printf("List 2: ");
displayList(list2);

struct Node* mergedList = mergeSortedLists(list1, list2);

printf("Merged List: ");


displayList(mergedList);

return 0;
}
Output:
List 1: 1 -> 3 -> 5 -> NULL
List 2: 2 -> 4 -> 6 -> NULL
Merged List: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL
P8 Find the Height of the Binary Tree

#include <stdio.h>
#include <stdlib.h>

// Define the structure for a binary tree node


struct Node {
int data;
struct Node* left;
struct Node* right;
};

// Function to create a new node


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Function to calculate the height of a binary tree


int findHeight(struct Node* root) {
if (root == NULL) {
return -1; // Height of an empty tree is -1
}

int leftHeight = findHeight(root->left);


int rightHeight = findHeight(root->right);

return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;


}
int main() {
// Construct a binary tree
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);

int height = findHeight(root);


printf("Height of the binary tree is: %d\n", height);

return 0;
}
Output:
Height of the binary tree is: 2
P9: Deletion of a node in the BST

#include <stdio.h>
#include <stdlib.h>

// Define the structure for a binary tree node


struct Node {
int data;
struct Node* left;
struct Node* right;
};

// Function to create a new node


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Function to find the minimum value node in a BST


struct Node* findMin(struct Node* node) {
while (node->left != NULL) {
node = node->left;
}
return node;
}

// Function to delete a node from a BST


struct Node* deleteNode(struct Node* root, int key) {
if (root == NULL) {
return root;
}

if (key < root->data) {


root->left = deleteNode(root->left, key);
} else if (key > root->data) {
root->right = deleteNode(root->right, key);
} else {
// Node with only one child or no child
if (root->left == NULL) {
struct Node* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct Node* temp = root->left;
free(root);
return temp;
}

// Node with two children: Get the inorder successor (smallest in the right subtree)
struct Node* temp = findMin(root->right);
root->data = temp->data;

// Delete the inorder successor


root->right = deleteNode(root->right, temp->data);
}
return root;
}

// Function to perform inorder traversal of a BST


void inorderTraversal(struct Node* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
}

int main() {
struct Node* root = createNode(50);
root->left = createNode(30);
root->right = createNode(70);
root->left->left = createNode(20);
root->left->right = createNode(40);
root->right->left = createNode(60);
root->right->right = createNode(80);

printf("Inorder traversal before deletion: ");


inorderTraversal(root);
printf("\n");

int keyToDelete = 50;


root = deleteNode(root, keyToDelete);

printf("Inorder traversal after deleting %d: ", keyToDelete);


inorderTraversal(root);
printf("\n");

return 0;
}
Output:
Inorder traversal before deletion: 20 30 40 50 60 70 80
Inorder traversal after deleting 50: 20 30 40 60 70 80
P10: Given Two Binary Trees Check whether the two binary trees are mirrored or not

#include <stdio.h>
#include <stdlib.h>

// Define the structure for a binary tree node


struct Node {
int data;
struct Node* left;
struct Node* right;
};

// Function to create a new node


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Function to check if two binary trees are mirrored
int areMirrored(struct Node* root1, struct Node* root2) {
// Base cases
if (root1 == NULL && root2 == NULL) {
return 1; // Both trees are empty
}
if (root1 == NULL || root2 == NULL) {
return 0; // One tree is empty while the other is not
}

// Compare values and check the mirrored structure


return (root1->data == root2->data) &&
areMirrored(root1->left, root2->right) &&
areMirrored(root1->right, root2->left);
}

int main() {
// Construct two binary trees
struct Node* root1 = createNode(1);
root1->left = createNode(2);
root1->right = createNode(2);
root1->left->left = createNode(3);
root1->left->right = createNode(4);
root1->right->left = createNode(4);
root1->right->right = createNode(3);

struct Node* root2 = createNode(1);


root2->left = createNode(2);
root2->right = createNode(2);
root2->left->left = createNode(3);
root2->left->right = createNode(4);
root2->right->left = createNode(4);
root2->right->right = createNode(3);

if (areMirrored(root1, root2)) {
printf("The two binary trees are mirrored.\n");
} else {
printf("The two binary trees are not mirrored.\n");
}

return 0;
}
Output:
The two binary trees are mirrored.
#include <stdio.h>
P11: Given Tree is BST or not?

#include <stdlib.h>
struct node
{
int data;
struct node* left;
struct node* right;
};

static struct node *prev = NULL;

/*Function to check whether the tree is BST or not*/


int is_bst(struct node* root)
{
if (root)
{
if (!is_bst(root->left)) //moves towards the leftmost child of the tree and checks for the BST
return 0;
if (prev != NULL && root->data <= prev->data)
return 0;
prev = root;
return is_bst(root->right); //moves the corresponding right child of the tree and checks for the
BST
}
return 1;
}

struct node* newNode(int data)


{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}

int main()
{

struct node *root = newNode(40);


root->left = newNode(20);
root->right = newNode(60);
root->left->left = newNode(10);
root->left->right = newNode(30);
root->right->right = newNode(80);
root->right->right->right = newNode(90);
if (is_bst(root))
printf("TREE 1 Is BST");
else
printf("TREE 1 Not a BST");
prev = NULL;

struct node *root1 = newNode(50);


root1->left = newNode(20);
root1->right = newNode(30);
root1->left->left = newNode(70);
root1->left->right = newNode(80);
root1->left->left->right = newNode(40);
root1->left->left->left = newNode(90);
if (is_bst(root1))
printf("TREE 2 Is BST \t");
else
printf("TREE 2 Not a BST");
return 0;
}
Output:
TREE 1 Is BST
TREE 2 Not a BST
P12 For a Given Graph find the Minimum Spanning Tree using Prims Algorithm

#include <stdio.h>
#include <stdbool.h>
#include <limits.h>

#define V 5 // Number of vertices in the graph

// Function to find the vertex with the minimum key value


int minKey(int key[], bool mstSet[]) {
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++) {


if (!mstSet[v] && key[v] < min) {
min = key[v];
min_index = v;
}
}

return min_index;
}

// Function to print the MST


void printMST(int parent[], int graph[V][V]) {
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++) {
printf("%d - %d \t%d\n", parent[i], i, graph[i][parent[i]]);
}
}

// Function to construct and find the MST using Prim's algorithm


void primMST(int graph[V][V]) {
int parent[V]; // Array to store the constructed MST
int key[V]; // Key values used to pick minimum weight edge
bool mstSet[V]; // To represent set of vertices included in MST

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


key[i] = INT_MAX;
mstSet[i] = false;
}

key[0] = 0; // Start from the first vertex


parent[0] = -1; // First node is always the root of MST

for (int count = 0; count < V - 1; count++) {


int u = minKey(key, mstSet);

mstSet[u] = true;

for (int v = 0; v < V; v++) {


if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}

// Print the constructed MST


printMST(parent, graph);
}

int main() {
int graph[V][V] = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};

// Print the MST using Prim's algorithm


primMST(graph);

return 0;
}
Output:
Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5
P13: For a Given Graph find the Minimum Spanning Tree using Kruskal’s Algorithm

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define V 5 // Number of vertices in the graph


#define E 7 // Number of edges in the graph

// Structure to represent an edge in the graph


struct Edge {
int src, dest, weight;
};

// Structure to represent a subset for union-find


struct Subset {
int parent, rank;
};

// Function to find the set of an element (using path compression)


int find(struct Subset subsets[], int i) {
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}

// Function to perform union of two sets (using rank)


void unionSets(struct Subset subsets[], int x, int y) {
int rootX = find(subsets, x);
int rootY = find(subsets, y);

if (subsets[rootX].rank < subsets[rootY].rank)


subsets[rootX].parent = rootY;
else if (subsets[rootX].rank > subsets[rootY].rank)
subsets[rootY].parent = rootX;
else {
subsets[rootY].parent = rootX;
subsets[rootX].rank++;
}
}

// Comparator function to sort edges by weight


int compareEdges(const void* a, const void* b) {
return ((struct Edge*)a)->weight - ((struct Edge*)b)->weight;
}

// Function to find the MST using Kruskal's algorithm


void kruskalMST(struct Edge edges[]) {
struct Subset subsets[V];
for (int i = 0; i < V; i++) {
subsets[i].parent = i;
subsets[i].rank = 0;
}

int mstWeight = 0; // Total weight of MST

qsort(edges, E, sizeof(edges[0]), compareEdges); // Sort edges by weight

printf("Edges in the MST:\n");


for (int i = 0, count = 0; count < V - 1; i++) {
int srcRoot = find(subsets, edges[i].src);
int destRoot = find(subsets, edges[i].dest);

if (srcRoot != destRoot) {
printf("(%d, %d) weight: %d\n", edges[i].src, edges[i].dest, edges[i].weight);
mstWeight += edges[i].weight;
unionSets(subsets, srcRoot, destRoot);
count++;
}
}

printf("Total weight of MST: %d\n", mstWeight);


}

int main() {
struct Edge edges[E] = {
{0, 1, 2}, {0, 3, 6}, {1, 2, 3},
{1, 3, 8}, {1, 4, 5}, {2, 4, 7},
{3, 4, 9}
};

kruskalMST(edges);

return 0;
}
Output:
Edges in the MST:
(0, 1) weight: 2
(1, 2) weight: 3
(1, 4) weight: 5
(0, 3) weight: 6
Total weight of MST: 1

You might also like