Programming and Data Structures
Programming and Data Structures
print(~a)
# ~a= -a-1
Format Specifiers in C
The format specifier in C is used to tell the compiler about the type of data to be printed or scanned in input and output operations.
// driver code
int main()
{
unsigned int var;
Input:
Enter an integer: 25
Output:
Entered unsigned integer: 25
Printing -10 using %u: 4294967286
-10 will be converted to its positive equivalent and printed as 4294967286 (assuming 32-bit unsigned integers).
// driver code
int main()
{
float a = 12.67;
printf("Using %%f: %f\n", a);
printf("Using %%e: %e\n", a);
printf("Using %%E, %E", a);
return 0;
}
Output
Using %f: 12.670000
Using %e: 1.267000e+01
Using %E, 1.267000E+01
#include <stdio.h>
int main()
{
int a = 67;
printf("%o\n", a);
return 0;
}
Output
103
Output
3c5e
3C5E
int main()
{
char a[] = "Hi Geeks";
printf("%s\n", a);
return 0;
}
Output
Hi Geeks
#include <stdio.h>
int main()
{
int a = 10;
printf("The Memory Address of a: %p\n",(void*)&a);
return 0;
}
Output
The Memory Address of a: 0x7ffe9645b3fc
Tree
A tree data structure is a hierarchical structure that is used to represent and organize data in a way that is easy to navigate and search. It is a collection of
nodes that are connected by edges and has a hierarchical relationship between the nodes.
Types of Tree data structures:
Binary tree: In a binary tree, each node can have a maximum of two children linked to it. Some common types of binary trees include full binary trees,
complete binary trees, balanced binary trees, and degenerate or pathological binary trees.
Ternary Tree: A Ternary Tree is a tree data structure in which each node has at most three child nodes, usually distinguished as “left”, “mid” and
“right”.
N-ary Tree or Generic Tree : Generic trees are a collection of nodes where each node is a data structure that consists of records and a list of references
to its children(duplicate references are not allowed). Unlike the linked list, each node stores the address of multiple nodes.
Degree in Tree:
Degree of a node is the total number of children of that node.
Degree of a tree is the highest degree of a node among all the nodes in the tree.
Example-
Level-
Example-
Total number of edges that lies on the longest path from any leaf node to a particular node is called as height of that node.
Height of a tree is the height of root node.
Height of all leaf nodes = 0
Total number of edges from root node to a particular node is called as depth of that node.
Depth of a tree is the total number of edges from root node to a leaf node in the longest path.
Depth of the root node = 0
The terms “level” and “depth” are used interchangeably.
Forest-
A forest is a set of disjoint trees.
The left subtree of a node contains only nodes with keys lesser than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
The left and right subtree each must also be a binary search tree.
Question:
Solution:
2. AVL Tree
AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees cannot be more than one for all
nodes.
Example of AVL Tree shown below:
The below tree is AVL because the differences between the heights of left and right subtrees for every node are less than or equal to 1
2. Right Rotation:
If a node is added to the left subtree of the left subtree, the AVL tree may get out of balance, we do a single right rotation.
3. Left-Right Rotation :
A left-right rotation is a combination in which first left rotation takes place after that right rotation executes.
4. Right-Left Rotation :
A right-left rotation is a combination in which first right rotation takes place after that left rotation executes.
Deletion may disturb the balance factor of an AVL tree and therefore the tree needs to be rebalanced in order to maintain the AVLness. For this purpose,
we need to perform rotations. The two types of rotations are L rotation and R rotation. Here, we will discuss R rotations. L rotations are the mirror images
of them.
If the node which is to be deleted is present in the left sub-tree of the critical node, then L rotation needs to be applied, if the node which is to be deleted is
present in the right sub-tree of the critical node, the R rotation will be applied.
If the node B has 0 balance factor, and the balance factor of node A disturbed upon deleting the node X, then the tree will be rebalanced by rotating tree
using R0 rotation.
Example:
Delete the node 30 from the AVL tree shown in the following image.
Solution:
In this case, the node B has balance factor 0, therefore the tree will be rotated by using R0 rotation as shown in the following image. The node B(10)
becomes the root, while the node A is moved to its right. The right child of node B will now become the left child of node A.
R1 Rotation (Node B has balance factor 1)
R1 Rotation is to be performed if the balance factor of Node B is 1.
Example:
Delete Node 55 from the AVL tree shown in the following image.
Solution:
Deleting 55 from the AVL Tree disturbs the balance factor of the node 50 i.e. node A which becomes the critical node. This is the condition of R1 rotation
in which, the node A will be moved to its right (shown in the image below). The right of B is now become the left of A (i.e. 45).
The process involved in the solution is shown in the following image.
Example:
Delete the node 60 from the AVL tree shown in the following image.
Solution:
in this case, node B has balance factor -1. Deleting the node 60, disturbs the balance factor of the node 50 therefore, it needs to be R-1 rotated. The node C
i.e. 45 becomes the root of the tree with the node B(40) and A(50) as its left and right child.
3. Red Black Tree
A red-black tree is a kind of self-balancing binary search tree where each node has an extra bit, and that bit is often interpreted as the color (red or black).
These colors are used to ensure that the tree remains balanced during insertions and deletions. Although the balance of the tree is not perfect, it is good
enough to reduce the searching time and maintain it around O(log n) time, where n is the total number of elements in the tree.
4. B – Tree
A B-tree is a type of self-balancing tree data structure that allows efficient access, insertion, and deletion of data items. B-trees are commonly used in
databases and file systems, where they can efficiently store and retrieve large amounts of data. A B-tree is characterized by a fixed maximum degree (or
order), which determines the maximum number of child nodes that a parent node can have. Each node in a B-tree can have multiple child nodes and
multiple keys, and the keys are used to index and locate data items.
1. Search O(log n)
2. Insert O(log n)
3. Delete O(log n)
Properties of B-Tree:
5. B+ Tree
A B+ tree is a variation of the B-tree that is optimized for use in file systems and databases. Like a B-tree, a B+ tree also has a fixed maximum degree and
allows efficient access, insertion, and deletion of data items. However, in a B+ tree, all data items are stored in the leaf nodes, while the internal nodes only
contain keys for indexing and locating the data items. This design allows for faster searches and sequential access of the data items, as all the leaf nodes are
linked together in a linked list.
6. Segment Tree
In computer science, a Segment Tree, also known as a statistic tree, is a tree data structure used for storing information about intervals, or segments. It
allows querying which of the stored segments contain a given point. It is, in principle, a static structure; that is, it’s a structure that cannot be modified once
it’s built. A similar data structure is the interval tree.
A segment tree for a set I of n intervals uses O(n log n) storage and can be built in O(n log n) time. Segment trees support searching for all the intervals
that contain a query point in time O(log n + k), k being the number of retrieved intervals or segments.
Consider an array A of size N and a corresponding Segment Tree T:
1. The root of T will represent the whole array A[0:N−1].
2. Each leaf in the Segment Tree T will represent a single element A[i] such that 0≤i<N.
3. The internal nodes in the Segment Tree T represents the union of elementary intervals A[i:j] where 0≤i<j<N.
The root of the Segment Tree represents the whole array A[0:N−1]. Then it is broken down into two half intervals or segments and the two children of the root
in turn represent the A[0:(N−1)/2] and A[(N−1)/2+1:(N−1)]. So in each step, the segment is divided into half and the two children represent those two halves.
So the height of the segment tree will be log2N.
Binary Heap
A Binary Heap is a complete Binary Tree which is used to store data efficiently to get the max or min element based on its structure. A Binary Heap is
either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property
must be recursively true for all nodes in Binary Tree.
Examples of Min Heap:
10 10
/ \ / \
20 100 15 30
/ / \ / \
30 40 50 100 40
// Heap Sort in C
#include <stdio.h>
// Heap sort
for (int i = n - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
// Print an array
void printArray(int arr[], int n) {
for (int i = 0; i < n; ++i)
printf("%d ", arr[i]);
printf("\n");
}
// Driver code
int main() {
int arr[] = {1, 12, 9, 5, 6, 10};
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n);
Time Complexity
Best O(nlog n)
Worst O(nlog n)
Average O(nlog n)
Graph
A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that
connect any two nodes in the graph. More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is denoted by G(E, V).
Types of Graphs:
1. Finite Graphs
A graph is said to be finite if it has a finite number of vertices and a finite number of edges.
2. Infinite Graph:
A graph is said to be infinite if it has an infinite number of vertices as well as an infinite number of edges.
3. Trivial Graph:
A graph is said to be trivial if a finite graph contains only one vertex and no edge. It is also known as a singleton graph or a single vertex graph.
4. Simple Graph:
A simple graph is a graph that does not contain more than one edge between the pair of vertices.
5. Multi Graph:
Any graph which contains some parallel edges but doesn’t contain any self-loop.
6. Null Graph:
A null graph is a graph with no edges. A null graph can also be referred to as an edgeless graph, an isolated graph, or a discrete graph
7. Complete Graph:
A simple graph with n vertices is called a complete graph if the degree of each vertex is n-1, that is, one vertex is attached with n-1 edges or the rest of the
vertices in the graph. A complete graph is also called Full Graph.
8. Pseudo Graph:
A graph G with a self-loop and some multiple edges is called a pseudo graph.
9. Regular Graph:
If a graph is regular, then every vertex has the same degree.
10. Bipartite Graph:
A bipartite graph is a graph in which the vertices can be divided into two disjoint sets, such that no two vertices within the same set are adjacent. In other
words, it is a graph in which every edge connects a vertex of one set to a vertex of the other set.
13. Subgraph:
A graph G1 = (V1, E1) is called a subgraph of a graph G(V, E) if V1(G) is a subset of V(G) and E1(G) is a subset of E(G) such that each edge of G1 has
same end vertices as in G.
Tree Edge: It is an edge that is present in the tree obtained after applying DFS on the graph. All the Green edges are tree edges.
Forward Edge: It is an edge (u, v) such that v is a descendant but not part of the DFS tree. An edge from 1 to 8 is a forward edge.
Back edge: It is an edge (u, v) such that v is the ancestor of node u but is not part of the DFS tree. Edge from 6 to 2 is a back edge. Presence of
back edge indicates a cycle in directed graph.
Cross Edge: It is an edge that connects two nodes such that they do not have any ancestor and a descendant relationship between them(in case
of DFS). The edge from node 5 to 4 is a cross edge.
Example:
Time Complexity(DFS):
Since all the nodes and vertices are visited, the average time complexity for DFS on a graph is O(V + E), where V is the number of vertices and E is the
number of edges. In case of DFS on a tree, the time complexity is O(V), where V is the number of nodes.
If the graph is a directed graph, then in this graph, each vertex must have an in-degree and out-degree.
Tree Order
The order of the tree represents the maximum number of children a tree’s node could have. So when we say we have a B-Tree of order N, It means every
node of that B-Tree can have a maximum of N children.
Tree Degree
The degree of a tree represents the maximum degree of a node in the tree.
Infix notation
An infix notation is a notation in which an expression is written in a usual or normal format. It is a notation in which the operators lie between the operands.
The examples of infix notation are A+B, A*B, A/B, etc.
In order to parse any expression, we need to take care of two things, i.e., Operator precedence and Associativity. Operator precedence means the precedence
of any operator over another operator.
Precedence order
1. Parenthesis { }, ( ), [ ]
2. Exponential notation ^
3. Multiplication and Division *, /
4. Addition and Subtraction +, -
Associativity means when the operators with the same precedence exist in the expression. For example, in the expression, i.e., A + B - C, '+' and '-' operators
are having the same precedence, so they are evaluated with the help of associativity. Since both '+' and '-' are left-associative, they would be evaluated as (A +
B) - C.
Associativity order
1. ^ Right to Left
2. *, / Left to Right
3. +, - Left to Right
Q Q
+ + Q
T + QT
* +* QT
V +* QTV
/ +*/ QTV
U +*/ QTVU
/ +*// QTVU
W +*// QTVUW
* +*//* QTVUW
) +*//*) QTVUW
P +*//*) QTVUWP
^ +*//*)^ QTVUWP
O +*//*)^ QTVUWPO
( +*//* QTVUWPO^
+ ++ QTVUWPO^*//*
N ++ QTVUWPO^*//*N
* ++* QTVUWPO^*//*N
M ++* QTVUWPO^*//*NM
- ++- QTVUWPO^*//*NM*
L ++- QTVUWPO^*//*NM*L
+ ++-+ QTVUWPO^*//*NM*L
K ++-+ QTVUWPO^*//*NM*LK
QTVUWPO^*//*NM*LK+-++
The above expression, i.e., QTVUWPO^*//*NM*LK+-++, is not a final expression. We need to reverse this expression to obtain the prefix expression.
Scan the given prefix expression from right to left character by character.
If the character is an operand, push it into the stack.
if the character is an operator, pop the top two values from stack.
Concatenate this operator with these two values (1st top value+operator+2nd top value) to get a new string.
Now push this resulting string back into the stack.
Repeat this process until the end of prefix expression. Now the value in the stack is the desired infix expression.
*-A/BC-/AKL *-A/BC-/AK L
*-A/BC-/AKL *-A/BC-/A LK
*-A/BC-/AKL *- ((A/K)-L)(B/C)A
*-A/BC-/AKL * ((A/K)-L)(A-(B/C))
*-A/BC-/AKL ((A-(B/C))*((A/K)-L))
A+B*C/(E-F)+(D+G-H) A
A+B*C/(E-F)+(D+G-H) A +
A+B*C/(E-F)+(D+G-H) AB +
A+B*C/(E-F)+(D+G-H) AB +*
A+B*C/(E-F)+(D+G-H) ABC +*
A+B*C/(E-F)+(D+G-H) ABC* +/
A+B*C/(E-F)+(D+G-H) ABC*EF- +/
A+B*C/(E-F)+(D+G-H) ABC*EF-/+ +
A+B*C/(E-F)+(D+G-H) ABC*EF-/+ +(
A+B*C/(E-F)+(D+G-H) ABC*EF-/+D +(
A+B*C/(E-F)+(D+G-H) ABC*EF-/+DG+H- +
A+B*C/(E-F)+(D+G-H) ABC*EF-/+DG+H-+
Scan the given postfix expression from left to right character by character.
If the character is an operand, push it into the stack.
But if the character is an operator, pop the top two values from stack.
Concatenate this operator with these two values (2nd top value + operator + 1 st top value) to get a new string.
Now push this resulting string back into the stack.
Repeat this process until the end of postfix expression. Now the value in the stack is the infix expression.
ab*c+ b*c+ a
ab*c+ *c+ ab
ab*c+ c+ (a*b)
A0b*c+ + (a*b)c
ab*c+ ((a*b)+c)
Question
Solution:
Note: If the question ask for Row major order, then A[I][J] = B + ((J - LC) + (I – LR) * N) * W
where N = no. of columns.
Question:
Solution:
Question:
Question:
Question:
Question:
Question:
Question:
Question:
Question:
Solution:
256 (Two fifty six)
Question:
Solution:
Question:
Question:
Solution:
If G is a graph with n vertices and p components, then G has n-p edges. Hence graph G has 9-3 = 6 edges.
Question:
Question:
Question:
Solution:
Question:
Question:
Question:
Solution:
Question:
Solution: x3 = 4(four)
Question:
Solution:
2004
2040
Question:
Question:
Question:
Solution:
Option A
Question:
Question:
Question:
Question:
Solution: 35(Three five)
Question:
Solution:
Question:
Solution:
Question:
Solution:
Question:
Solution: