Skip to content

Commit 98bf74b

Browse files
authored
Merge branch 'smv1999:master' into circular-queue
2 parents adf77dc + 13aa69b commit 98bf74b

File tree

5 files changed

+428
-0
lines changed

5 files changed

+428
-0
lines changed

Arrays/triplet_sum.cpp

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/******************************************************************************
2+
3+
Given an array arr of size n and an integer X.
4+
Find if there's a triplet in the array which sums up to the given integer X.
5+
6+
*******************************************************************************/
7+
8+
//SOLUTION (in C++)
9+
10+
#include <bits/stdc++.h>
11+
12+
using namespace std;
13+
14+
void findTripletSum(int A[], int n, int X)
15+
{
16+
sort(A, A+n); //sort the array, it becomes easy to take the sum.
17+
int i, j, k, count = 0;
18+
for(i = 0;i<=n-3;i++) //i should only run till n-3 as we need three numbers for a triplet.
19+
{
20+
j = i+1;
21+
k = n-1;
22+
while(j<k) //two-pointer appraoch is used.
23+
{
24+
if(A[i] + A[j] + A[k] < X) //since the array is sorted, if the sum if less than X, the we need to increment j.
25+
{
26+
j++;
27+
}
28+
else if(A[i] + A[j] + A[k] > X) //If the sum is greater than X, we need to decrement k.
29+
{
30+
k--;
31+
}
32+
else if(A[i] + A[j] + A[k] == X) //If the sum is equal to X we need to increement j and decrement k, so that we may find other combinations of the given sum.
33+
{
34+
j++;
35+
k--;
36+
count++;
37+
}
38+
}
39+
}
40+
if(count == 0)
41+
cout<<"The triplet doesn't exists"<<endl;
42+
else
43+
cout<<"The triplet exists"<<endl;
44+
}
45+
46+
int main()
47+
{
48+
int n, X;
49+
cout<<"Enter n"<<endl;
50+
cin>>n;
51+
cout<<"Enter the sum you want to find"<<endl;
52+
cin>>X;
53+
cout<<"Enter the array elements"<<endl;
54+
int A[n];
55+
for(int i = 0;i<n;i++)
56+
{
57+
cin>>A[i];
58+
}
59+
findTripletSum(A, n, X);
60+
return 0;
61+
}

Bit Manipulation/rotate_bits.cpp

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*A rotation (or circular shift) is an operation similar to shift except that the
2+
bits that fall off at one end are put back to the other end.
3+
In left rotation, the bits that fall off at left end are put back at right end.
4+
In right rotation, the bits that fall off at right end are put back at left end.
5+
*/
6+
7+
#include <bits/stdc++.h>
8+
using namespace std;
9+
10+
// Left Rotate 'cnt' number of bits of the given number 'n'
11+
int left_rotate_bits(int n, int cnt)
12+
{
13+
int msb;
14+
15+
// 32 is the total number of bits used to store an INT variable in C++
16+
for(cnt = cnt % 31;cnt>0;cnt--)
17+
{
18+
//Store the current MSB in a temporary variable
19+
msb = (n >> 31) & 1;
20+
//Left rotate the given number by one bit
21+
n = (n<<1);
22+
//Set the dropped MSB as the new LSB
23+
n = n | msb;
24+
}
25+
return n;
26+
}
27+
28+
// Right Rotate 'cnt' number of bits of the given number 'n'
29+
int right_rotate_bits(int n, int cnt)
30+
{
31+
int lsb;
32+
33+
// 32 is the total number of bits used to store an INT variable in C++
34+
for(cnt = cnt % 31;cnt>0;cnt--)
35+
{
36+
//Store the current LSB in a temporary variable
37+
lsb = n & 1;
38+
//Right rotate the given number by one bit and drop its LSB
39+
n = (n >> 1) & (~(1 << 31));
40+
//Set the dropped LSB as the new MSB
41+
n = n | (lsb << 31);
42+
}
43+
return n;
44+
}
45+
46+
47+
int main()
48+
{
49+
int n,cnt,left,right;
50+
cout<<"\nEnter the number : ";
51+
cin>>n;
52+
53+
cout<<"How many bits do you want to rotate : ";
54+
cin>>cnt;
55+
56+
//Call the sort function
57+
left = left_rotate_bits(n, cnt);
58+
right = right_rotate_bits(n,cnt);
59+
60+
cout<<"The Left-rotated number is : "<<left<<endl;
61+
cout<<"The Right-rotated number is : "<<right<<endl;
62+
63+
return 0;
64+
}
65+
66+
/*
67+
INPUT
68+
Enter the number : 39
69+
How many bits do you want to rotate : 17
70+
OUTPUT
71+
The Left-rotated number is : 5111808
72+
The Right-rotated number is : 1277952
73+
74+
Time Complexity: O(n)
75+
Space Complexity: O(1)
76+
*/
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
# Lowest Common Ancestor in Binary Tree
2+
# Time Complexity : O(n) , Space Complexity : O(1)
3+
4+
"""
5+
Binary trees are trees where any node can have only 0, 1 or 2 children, which are sorted in any order.
6+
Lowest Common Ancestor (LCA) of two given nodes is the shared ancestor of n1 and n2 that is located farthest from the root
7+
or the last common node that occurs on the paths from root node to those nodes.
8+
9+
Here, we first check if both numbers exist in tree or not, with exists_in_tree() function by recursively traversing the trees.
10+
If yes then we find the LCA of both the elements with find_lca() function, which follows as :
11+
if LCA isnt found yet, but current node is one of the elements, then current node is the LCA
12+
else look for LCA in left and right subtree
13+
if both elements are found in different subtrees, make current node as LCA
14+
else if they are in same sub tree, return the LCA of that subtree
15+
16+
"""
17+
18+
19+
class Node :
20+
"""Class to define nodes of binary tree, with attributes data to store values, and left and right pointers"""
21+
def __init__(self, value) :
22+
self.data = value
23+
self.left = None
24+
self.right = None
25+
26+
def find_lca(node, n1, n2):
27+
"""Finds LCA of 2 numbers by recursively searching in left and right subtree
28+
input args : current node, the numbers whose lca is to be found, isFound list telling if the particular element is found
29+
returns : lca if found else None
30+
Time complexity : O(n), Space complexity : O(1)
31+
"""
32+
if node==None:
33+
return None
34+
35+
# if one element is found in current node, we return it
36+
# in normal case, both elements are found in different subtrees, called recursively, which is handeled later in this function
37+
# there may also be the case when one element is ancestor of another, which is handeled here, as this node is tha lca
38+
if node.data == n1:
39+
return node
40+
elif node.data == n2:
41+
return node
42+
43+
# Recursive calls
44+
lca_left = find_lca(node.left, n1, n2)
45+
lca_right = find_lca(node.right, n1, n2)
46+
47+
if lca_left and lca_right: # if both are not none, that is 1 element is found in each subtree
48+
return node # that means, current node is the lca
49+
else: # both numbers in same sub tree
50+
return lca_left if lca_left!=None else lca_right # return lca whichever is not none
51+
52+
53+
def exists_in_tree(node, n):
54+
"""This function finds if an element exists in a tree or not by recursively traversing the tree
55+
input : current node and the element to be found
56+
output : returns True if it exists, False if not
57+
Time complexity : O(n), Space complexity : O(1)
58+
"""
59+
if node == None:
60+
return False
61+
if node.data == n:
62+
return True
63+
64+
if exists_in_tree(node.left, n) or exists_in_tree(node.right, n):
65+
return True
66+
else:
67+
return False
68+
69+
70+
71+
def lowest_common_ancestor_binary_tree(root, n1, n2):
72+
"""This function checks if both elements are present in binary tree or not, and depending upon that returns proper value
73+
input : root node of the tree, numbers whose lca is to be found
74+
output : returns calculated LCA, if both exist, else None
75+
Both Time and Space complexity are : O(1)
76+
"""
77+
if exists_in_tree(root,n1) and exists_in_tree(root,n2): # if both the elements exist in the tree
78+
return find_lca(root, n1, n2) # then we calculate its LCA
79+
else :
80+
return None # otherwise we give answer None
81+
82+
83+
84+
def print_output(lca, n1, n2):
85+
"""Prints LCA of two numbers with a proper message if it exists"""
86+
if lca == None:
87+
print("\nElement does not exist in tree.\n")
88+
else:
89+
print(f"\nlca({n1}, {n2}) = {lca.data}\n")
90+
91+
92+
#============================= DRIVER CODE =============================
93+
if __name__ == "__main__":
94+
95+
root = Node(1)
96+
root.left = Node(2)
97+
root.right = Node(3)
98+
root.left.left = Node(4)
99+
root.left.right = Node(5)
100+
root.right.left = Node(6)
101+
root.right.right = Node(7)
102+
103+
"""
104+
1
105+
/ \
106+
2 3
107+
/ \ /\
108+
4 5 6 7
109+
"""
110+
111+
112+
lca = lowest_common_ancestor_binary_tree(root, 4, 5)
113+
print_output(lca, 4, 5)
114+
lca = lowest_common_ancestor_binary_tree(root, 2, 5)
115+
print_output(lca, 2, 5)
116+
lca = lowest_common_ancestor_binary_tree(root, 4, 2)
117+
print_output(lca, 4, 2)
118+
119+
120+
# OTHER EXAMPLES
121+
122+
"""lca = lowest_common_ancestor_binary_tree(root, 4, 7)
123+
print_output(lca, 4, 7)
124+
lca = lowest_common_ancestor_binary_tree(root, 2, 3)
125+
print_output(lca, 2, 3)
126+
lca = lowest_common_ancestor_binary_tree(root, 2, 1)
127+
print_output(lca, 2, 1)"""
128+
129+
"""lca = lowest_common_ancestor_binary_tree(root, 1, 8)
130+
print_output(lca, 1, 8)
131+
lca = lowest_common_ancestor_binary_tree(root, 1, 1)
132+
print_output(lca, 1, 1)
133+
lca = lowest_common_ancestor_binary_tree(root, 2, 6)
134+
print_output(lca, 2, 6)"""
135+
136+
"""lca = lowest_common_ancestor_binary_tree(root, 9, 8)
137+
print_output(lca, 9, 8)
138+
lca = lowest_common_ancestor_binary_tree(root, -1, 1)
139+
print_output(lca, -1, 1)
140+
lca = lowest_common_ancestor_binary_tree(root, -5, -6)
141+
print_output(lca, -5, -6)"""
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/* Write a program to implement all pair of Shortest path for
2+
a given graph (Floyed- Warshall Algorithm) using
3+
Dynamic Programing approach.
4+
5+
1 2 3 4 5
6+
__ _ _ _ _ _
7+
|
8+
1 | 0 3 8 X -4
9+
2 | X 0 X 1 7
10+
3 | X 4 0 X X ==> D[0]
11+
4 | 2 X -5 0 X
12+
5 | X X X 6 0
13+
14+
15+
1 2 3 4 5
16+
__ _ _ _ _ _
17+
|
18+
1 | X 1 1 X 1
19+
2 | X X X 2 2
20+
3 | X 3 X 3 X ==> pi[0]
21+
4 | X X 4 X X
22+
5 | X X X 5 X
23+
24+
*/
25+
26+
#include<stdio.h>
27+
#define infinity 1000000
28+
int D[100][100],PI[100][100],i,j,n,k;
29+
int main(){
30+
printf("Enter no. of nodes: ");
31+
scanf("%d",&n);
32+
for(i=1;i<=n;i++){
33+
for(j=1;j<=n;j++){
34+
if (i==j){
35+
D[i][j] = 0;
36+
}
37+
if (i!=j){
38+
printf("Enter cost of D[%d][%d] ", i,j);
39+
scanf("%d", &D[i][j]);
40+
}
41+
}
42+
printf("\n");
43+
}
44+
for(i=1;i<=n;i++){
45+
for(j=1;j<=n;j++){
46+
printf("Enter value of PI[%d][%d] ", i,j);
47+
scanf("%d", &PI[i][j]);
48+
}
49+
printf("\n");
50+
}
51+
printf("\n\nMatrix D\n\n");
52+
for(i=1;i<=n;i++){
53+
for(j=1;j<=n;j++){
54+
printf("%d ",D[i][j]);
55+
}
56+
printf("\n");
57+
}
58+
printf("\n\nMatrix PI\n\n");
59+
for(i=1;i<=n;i++){
60+
for(j=1;j<=n;j++){
61+
printf("%d ",PI[i][j]);
62+
}
63+
printf("\n");
64+
}
65+
for(k=1;k<=n;k++){
66+
for(i=1;i<=n;i++){
67+
for(j=1;j<=n;j++){
68+
if(D[i][j] > (D[i][k] + D[k][j])){
69+
D[i][j] = (D[i][k] + D[k][j]);
70+
PI[i][j] = PI[k][j];
71+
}
72+
}
73+
}
74+
}
75+
printf("\n\nFinal D Matrix\n\n");
76+
for(i=1;i<=n;i++){
77+
for(j=1;j<=n;j++){
78+
printf("%d ",D[i][j]);
79+
}
80+
printf("\n");
81+
}
82+
printf("\n\nFinal PI Matrix\n\n");
83+
for(i=1;i<=n;i++){
84+
for(j=1;j<=n;j++){
85+
printf("%d ",PI[i][j]);
86+
}
87+
printf("\n");
88+
}
89+
}

0 commit comments

Comments
 (0)