code
stringlengths 195
7.9k
| space_complexity
stringclasses 6
values | time_complexity
stringclasses 7
values |
---|---|---|
// LCM of given range queries using Segment Tree
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
// allocate space for tree
int tree[4 * MAX];
// declaring the array globally
int arr[MAX];
// Function to return gcd of a and b
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// utility function to find lcm
int lcm(int a, int b) { return a * b / gcd(a, b); }
// Function to build the segment tree
// Node starts beginning index of current subtree.
// start and end are indexes in arr[] which is global
void build(int node, int start, int end)
{
// If there is only one element in current subarray
if (start == end) {
tree[node] = arr[start];
return;
}
int mid = (start + end) / 2;
// build left and right segments
build(2 * node, start, mid);
build(2 * node + 1, mid + 1, end);
// build the parent
int left_lcm = tree[2 * node];
int right_lcm = tree[2 * node + 1];
tree[node] = lcm(left_lcm, right_lcm);
}
// Function to make queries for array range )l, r).
// Node is index of root of current segment in segment
// tree (Note that indexes in segment tree begin with 1
// for simplicity).
// start and end are indexes of subarray covered by root
// of current segment.
int query(int node, int start, int end, int l, int r)
{
// Completely outside the segment, returning
// 1 will not affect the lcm;
if (end < l || start > r)
return 1;
// completely inside the segment
if (l <= start && r >= end)
return tree[node];
// partially inside
int mid = (start + end) / 2;
int left_lcm = query(2 * node, start, mid, l, r);
int right_lcm = query(2 * node + 1, mid + 1, end, l, r);
return lcm(left_lcm, right_lcm);
}
// driver function to check the above program
int main()
{
// initialize the array
arr[0] = 5;
arr[1] = 7;
arr[2] = 5;
arr[3] = 2;
arr[4] = 10;
arr[5] = 12;
arr[6] = 11;
arr[7] = 17;
arr[8] = 14;
arr[9] = 1;
arr[10] = 44;
// build the segment tree
build(1, 0, 10);
// Now we can answer each query efficiently
// Print LCM of (2, 5)
cout << query(1, 0, 10, 2, 5) << endl;
// Print LCM of (5, 10)
cout << query(1, 0, 10, 5, 10) << endl;
// Print LCM of (0, 10)
cout << query(1, 0, 10, 0, 10) << endl;
return 0;
} | constant | linear |
// C++ program to find minimum and maximum using segment
// tree
#include <bits/stdc++.h>
using namespace std;
// Node for storing minimum and maximum value of given range
struct node {
int minimum;
int maximum;
};
// A utility function to get the middle index from corner
// indexes.
int getMid(int s, int e) { return s + (e - s) / 2; }
/* A recursive function to get the minimum and maximum
value in a given range of array indexes. The following
are parameters for this function.
st --> Pointer to segment tree
index --> Index of current node in the segment tree.
Initially 0 is passed as root is always at index 0 ss &
se --> Starting and ending indexes of the segment
represented by current node, i.e.,
st[index] qs & qe --> Starting and ending indexes of
query range */
struct node MaxMinUntill(struct node* st, int ss, int se,
int qs, int qe, int index)
{
// If segment of this node is a part of given range,
// then return
// the minimum and maximum node of the segment
struct node tmp, left, right;
if (qs <= ss && qe >= se)
return st[index];
// If segment of this node is outside the given range
if (se < qs || ss > qe) {
tmp.minimum = INT_MAX;
tmp.maximum = INT_MIN;
return tmp;
}
// If a part of this segment overlaps with the given
// range
int mid = getMid(ss, se);
left = MaxMinUntill(st, ss, mid, qs, qe, 2 * index + 1);
right = MaxMinUntill(st, mid + 1, se, qs, qe,
2 * index + 2);
tmp.minimum = min(left.minimum, right.minimum);
tmp.maximum = max(left.maximum, right.maximum);
return tmp;
}
// Return minimum and maximum of elements in range from
// index qs (query start) to qe (query end). It mainly uses
// MaxMinUtill()
struct node MaxMin(struct node* st, int n, int qs, int qe)
{
struct node tmp;
// Check for erroneous input values
if (qs < 0 || qe > n - 1 || qs > qe) {
printf("Invalid Input");
tmp.minimum = INT_MIN;
tmp.minimum = INT_MAX;
return tmp;
}
return MaxMinUntill(st, 0, n - 1, qs, qe, 0);
}
// A recursive function that constructs Segment Tree for
// array[ss..se]. si is index of current node in segment
// tree st
void constructSTUtil(int arr[], int ss, int se,
struct node* st, int si)
{
// If there is one element in array, store it in current
// node of segment tree and return
if (ss == se) {
st[si].minimum = arr[ss];
st[si].maximum = arr[ss];
return;
}
// If there are more than one elements, then recur for
// left and right subtrees and store the minimum and
// maximum of two values in this node
int mid = getMid(ss, se);
constructSTUtil(arr, ss, mid, st, si * 2 + 1);
constructSTUtil(arr, mid + 1, se, st, si * 2 + 2);
st[si].minimum = min(st[si * 2 + 1].minimum,
st[si * 2 + 2].minimum);
st[si].maximum = max(st[si * 2 + 1].maximum,
st[si * 2 + 2].maximum);
}
/* Function to construct segment tree from given array. This
function allocates memory for segment tree and calls
constructSTUtil() to fill the allocated memory */
struct node* constructST(int arr[], int n)
{
// Allocate memory for segment tree
// Height of segment tree
int x = (int)(ceil(log2(n)));
// Maximum size of segment tree
int max_size = 2 * (int)pow(2, x) - 1;
struct node* st = new struct node[max_size];
// Fill the allocated memory st
constructSTUtil(arr, 0, n - 1, st, 0);
// Return the constructed segment tree
return st;
}
// Driver code
int main()
{
int arr[] = { 1, 8, 5, 9, 6, 14, 2, 4, 3, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
// Build segment tree from given array
struct node* st = constructST(arr, n);
int qs = 0; // Starting index of query range
int qe = 8; // Ending index of query range
struct node result = MaxMin(st, n, qs, qe);
// Function call
printf("Minimum = %d and Maximum = %d ", result.minimum,
result.maximum);
return 0;
} | linear | logn |
/* C++ Program to find LCA of u and v by reducing the problem to RMQ */
#include<bits/stdc++.h>
#define V 9 // number of nodes in input tree
int euler[2*V - 1]; // For Euler tour sequence
int level[2*V - 1]; // Level of nodes in tour sequence
int firstOccurrence[V+1]; // First occurrences of nodes in tour
int ind; // Variable to fill-in euler and level arrays
// A Binary Tree node
struct Node
{
int key;
struct Node *left, *right;
};
// Utility function creates a new binary tree node with given key
Node * newNode(int k)
{
Node *temp = new Node;
temp->key = k;
temp->left = temp->right = NULL;
return temp;
}
// log base 2 of x
int Log2(int x)
{
int ans = 0 ;
while (x>>=1) ans++;
return ans ;
}
/* A recursive function to get the minimum value in a given range
of array indexes. The following are parameters for this function.
st --> Pointer to segment tree
index --> Index of current node in the segment tree. Initially
0 is passed as root is always at index 0
ss & se --> Starting and ending indexes of the segment represented
by current node, i.e., st[index]
qs & qe --> Starting and ending indexes of query range */
int RMQUtil(int index, int ss, int se, int qs, int qe, int *st)
{
// If segment of this node is a part of given range, then return
// the min of the segment
if (qs <= ss && qe >= se)
return st[index];
// If segment of this node is outside the given range
else if (se < qs || ss > qe)
return -1;
// If a part of this segment overlaps with the given range
int mid = (ss + se)/2;
int q1 = RMQUtil(2*index+1, ss, mid, qs, qe, st);
int q2 = RMQUtil(2*index+2, mid+1, se, qs, qe, st);
if (q1==-1) return q2;
else if (q2==-1) return q1;
return (level[q1] < level[q2]) ? q1 : q2;
}
// Return minimum of elements in range from index qs (query start) to
// qe (query end). It mainly uses RMQUtil()
int RMQ(int *st, int n, int qs, int qe)
{
// Check for erroneous input values
if (qs < 0 || qe > n-1 || qs > qe)
{
printf("Invalid Input");
return -1;
}
return RMQUtil(0, 0, n-1, qs, qe, st);
}
// A recursive function that constructs Segment Tree for array[ss..se].
// si is index of current node in segment tree st
void constructSTUtil(int si, int ss, int se, int arr[], int *st)
{
// If there is one element in array, store it in current node of
// segment tree and return
if (ss == se)st[si] = ss;
else
{
// If there are more than one elements, then recur for left and
// right subtrees and store the minimum of two values in this node
int mid = (ss + se)/2;
constructSTUtil(si*2+1, ss, mid, arr, st);
constructSTUtil(si*2+2, mid+1, se, arr, st);
if (arr[st[2*si+1]] < arr[st[2*si+2]])
st[si] = st[2*si+1];
else
st[si] = st[2*si+2];
}
}
/* Function to construct segment tree from given array. This function
allocates memory for segment tree and calls constructSTUtil() to
fill the allocated memory */
int *constructST(int arr[], int n)
{
// Allocate memory for segment tree
// Height of segment tree
int x = Log2(n)+1;
// Maximum size of segment tree
int max_size = 2*(1<<x) - 1; // 2*pow(2,x) -1
int *st = new int[max_size];
// Fill the allocated memory st
constructSTUtil(0, 0, n-1, arr, st);
// Return the constructed segment tree
return st;
}
// Recursive version of the Euler tour of T
void eulerTour(Node *root, int l)
{
/* if the passed node exists */
if (root)
{
euler[ind] = root->key; // insert in euler array
level[ind] = l; // insert l in level array
ind++; // increment index
/* if unvisited, mark first occurrence */
if (firstOccurrence[root->key] == -1)
firstOccurrence[root->key] = ind-1;
/* tour left subtree if exists, and remark euler
and level arrays for parent on return */
if (root->left)
{
eulerTour(root->left, l+1);
euler[ind]=root->key;
level[ind] = l;
ind++;
}
/* tour right subtree if exists, and remark euler
and level arrays for parent on return */
if (root->right)
{
eulerTour(root->right, l+1);
euler[ind]=root->key;
level[ind] = l;
ind++;
}
}
}
// Returns LCA of nodes n1, n2 (assuming they are
// present in the tree)
int findLCA(Node *root, int u, int v)
{
/* Mark all nodes unvisited. Note that the size of
firstOccurrence is 1 as node values which vary from
1 to 9 are used as indexes */
memset(firstOccurrence, -1, sizeof(int)*(V+1));
/* To start filling euler and level arrays from index 0 */
ind = 0;
/* Start Euler tour with root node on level 0 */
eulerTour(root, 0);
/* construct segment tree on level array */
int *st = constructST(level, 2*V-1);
/* If v before u in Euler tour. For RMQ to work, first
parameter 'u' must be smaller than second 'v' */
if (firstOccurrence[u]>firstOccurrence[v])
std::swap(u, v);
// Starting and ending indexes of query range
int qs = firstOccurrence[u];
int qe = firstOccurrence[v];
// query for index of LCA in tour
int index = RMQ(st, 2*V-1, qs, qe);
/* return LCA node */
return euler[index];
}
// Driver program to test above functions
int main()
{
// Let us create the Binary Tree as shown in the diagram.
Node * root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->left->right->left = newNode(8);
root->left->right->right = newNode(9);
int u = 4, v = 9;
printf("The LCA of node %d and node %d is node %d.\n",
u, v, findLCA(root, u, v));
return 0;
} | linear | linear |
// A Divide and Conquer Program to find maximum rectangular area in a histogram
#include <bits/stdc++.h>
using namespace std;
// A utility function to find minimum of three integers
int max(int x, int y, int z)
{ return max(max(x, y), z); }
// A utility function to get minimum of two numbers in hist[]
int minVal(int *hist, int i, int j)
{
if (i == -1) return j;
if (j == -1) return i;
return (hist[i] < hist[j])? i : j;
}
// A utility function to get the middle index from corner indexes.
int getMid(int s, int e)
{ return s + (e -s)/2; }
/* A recursive function to get the index of minimum value in a given range of
indexes. The following are parameters for this function.
hist --> Input array for which segment tree is built
st --> Pointer to segment tree
index --> Index of current node in the segment tree. Initially 0 is
passed as root is always at index 0
ss & se --> Starting and ending indexes of the segment represented by
current node, i.e., st[index]
qs & qe --> Starting and ending indexes of query range */
int RMQUtil(int *hist, int *st, int ss, int se, int qs, int qe, int index)
{
// If segment of this node is a part of given range, then return the
// min of the segment
if (qs <= ss && qe >= se)
return st[index];
// If segment of this node is outside the given range
if (se < qs || ss > qe)
return -1;
// If a part of this segment overlaps with the given range
int mid = getMid(ss, se);
return minVal(hist, RMQUtil(hist, st, ss, mid, qs, qe, 2*index+1),
RMQUtil(hist, st, mid+1, se, qs, qe, 2*index+2));
}
// Return index of minimum element in range from index qs (query start) to
// qe (query end). It mainly uses RMQUtil()
int RMQ(int *hist, int *st, int n, int qs, int qe)
{
// Check for erroneous input values
if (qs < 0 || qe > n-1 || qs > qe)
{
cout << "Invalid Input";
return -1;
}
return RMQUtil(hist, st, 0, n-1, qs, qe, 0);
}
// A recursive function that constructs Segment Tree for hist[ss..se].
// si is index of current node in segment tree st
int constructSTUtil(int hist[], int ss, int se, int *st, int si)
{
// If there is one element in array, store it in current node of
// segment tree and return
if (ss == se)
return (st[si] = ss);
// If there are more than one elements, then recur for left and
// right subtrees and store the minimum of two values in this node
int mid = getMid(ss, se);
st[si] = minVal(hist, constructSTUtil(hist, ss, mid, st, si*2+1),
constructSTUtil(hist, mid+1, se, st, si*2+2));
return st[si];
}
/* Function to construct segment tree from given array. This function
allocates memory for segment tree and calls constructSTUtil() to
fill the allocated memory */
int *constructST(int hist[], int n)
{
// Allocate memory for segment tree
int x = (int)(ceil(log2(n))); //Height of segment tree
int max_size = 2*(int)pow(2, x) - 1; //Maximum size of segment tree
int *st = new int[max_size];
// Fill the allocated memory st
constructSTUtil(hist, 0, n-1, st, 0);
// Return the constructed segment tree
return st;
}
// A recursive function to find the maximum rectangular area.
// It uses segment tree 'st' to find the minimum value in hist[l..r]
int getMaxAreaRec(int *hist, int *st, int n, int l, int r)
{
// Base cases
if (l > r) return INT_MIN;
if (l == r) return hist[l];
// Find index of the minimum value in given range
// This takes O(Logn)time
int m = RMQ(hist, st, n, l, r);
/* Return maximum of following three possible cases
a) Maximum area in Left of min value (not including the min)
a) Maximum area in right of min value (not including the min)
c) Maximum area including min */
return max(getMaxAreaRec(hist, st, n, l, m-1),
getMaxAreaRec(hist, st, n, m+1, r),
(r-l+1)*(hist[m]) );
}
// The main function to find max area
int getMaxArea(int hist[], int n)
{
// Build segment tree from given array. This takes
// O(n) time
int *st = constructST(hist, n);
// Use recursive utility function to find the
// maximum area
return getMaxAreaRec(hist, st, n, 0, n-1);
}
// Driver program to test above functions
int main()
{
int hist[] = {6, 1, 5, 4, 5, 2, 6};
int n = sizeof(hist)/sizeof(hist[0]);
cout << "Maximum area is " << getMaxArea(hist, n);
return 0;
} | linear | nlogn |
// C++ program to print all words in the CamelCase
// dictionary that matches with a given pattern
#include <bits/stdc++.h>
using namespace std;
// Alphabet size (# of upper-Case characters)
#define ALPHABET_SIZE 26
// A Trie node
struct TrieNode
{
TrieNode* children[ALPHABET_SIZE];
// isLeaf is true if the node represents
// end of a word
bool isLeaf;
// vector to store list of complete words
// in leaf node
list<string> word;
};
// Returns new Trie node (initialized to NULLs)
TrieNode* getNewTrieNode(void)
{
TrieNode* pNode = new TrieNode;
if (pNode)
{
pNode->isLeaf = false;
for (int i = 0; i < ALPHABET_SIZE; i++)
pNode->children[i] = NULL;
}
return pNode;
}
// Function to insert word into the Trie
void insert(TrieNode* root, string word)
{
int index;
TrieNode* pCrawl = root;
for (int level = 0; level < word.length(); level++)
{
// consider only uppercase characters
if (islower(word[level]))
continue;
// get current character position
index = int(word[level]) - 'A';
if (!pCrawl->children[index])
pCrawl->children[index] = getNewTrieNode();
pCrawl = pCrawl->children[index];
}
// mark last node as leaf
pCrawl->isLeaf = true;
// push word into vector associated with leaf node
(pCrawl->word).push_back(word);
}
// Function to print all children of Trie node root
void printAllWords(TrieNode* root)
{
// if current node is leaf
if (root->isLeaf)
{
for(string str : root->word)
cout << str << endl;
}
// recurse for all children of root node
for (int i = 0; i < ALPHABET_SIZE; i++)
{
TrieNode* child = root->children[i];
if (child)
printAllWords(child);
}
}
// search for pattern in Trie and print all words
// matching that pattern
bool search(TrieNode* root, string pattern)
{
int index;
TrieNode* pCrawl = root;
for (int level = 0; level < pattern.length(); level++)
{
index = int(pattern[level]) - 'A';
// Invalid pattern
if (!pCrawl->children[index])
return false;
pCrawl = pCrawl->children[index];
}
// print all words matching that pattern
printAllWords(pCrawl);
return true;
}
// Main function to print all words in the CamelCase
// dictionary that matches with a given pattern
void findAllWords(vector<string> dict, string pattern)
{
// construct Trie root node
TrieNode* root = getNewTrieNode();
// Construct Trie from given dict
for (string word : dict)
insert(root, word);
// search for pattern in Trie
if (!search(root, pattern))
cout << "No match found";
}
// Driver function
int main()
{
// dictionary of words where each word follows
// CamelCase notation
vector<string> dict = {
"Hi", "Hello", "HelloWorld", "HiTech", "HiGeek",
"HiTechWorld", "HiTechCity", "HiTechLab"
};
// pattern consisting of uppercase characters only
string pattern = "HT";
findAllWords(dict, pattern);
return 0;
} | linear | quadratic |
// C++ program to construct an n x n
// matrix such that every row and every
// column has distinct values.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
int mat[MAX][MAX];
// Fills non-one entries in column j
// Given that there is a "1" at
// position mat[i][j], this function
// fills other entries of column j.
void fillRemaining(int i, int j, int n)
{
// Initialize value to be filled
int x = 2;
// Fill all values below i as 2, 3, ...p
for (int k = i + 1; k < n; k++)
mat[k][j] = x++;
// Fill all values above i
// as p + 1, p + 2, .. n
for (int k = 0; k < i; k++)
mat[k][j] = x++;
}
// Fills entries in mat[][]
// with the given set of rules
void constructMatrix(int n)
{
// Alternatively fill 1s starting from
// rightmost and leftmost columns. For
// example for n = 3, we get { {_ _ 1},
// {1 _ _} {_ 1 _}}
int right = n - 1, left = 0;
for (int i = 0; i < n; i++)
{
// If i is even, then fill
// next column from right
if (i % 2 == 0)
{
mat[i][right] = 1;
// After filling 1, fill remaining
// entries of column "right"
fillRemaining(i, right, n);
// Move right one column back
right--;
}
// Fill next column from left
else
{
mat[i][left] = 1;
// After filling 1, fill remaining
// entries of column "left"
fillRemaining(i, left, n);
// Move left one column forward
left++;
}
}
}
// Driver code
int main()
{
int n = 5;
// Passing n to constructMatrix function
constructMatrix(n);
// Printing the desired unique matrix
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
printf("%d ",mat[i][j]);
printf ("\n");
}
return 0;
} | constant | quadratic |
// Given a binary matrix of M X N of integers,
// you need to return only unique rows of binary array
#include <bits/stdc++.h>
using namespace std;
#define ROW 4
#define COL 5
// The main function that prints
// all unique rows in a given matrix.
void findUniqueRows(int M[ROW][COL])
{
//Traverse through the matrix
for(int i=0; i<ROW; i++)
{
int flag=0;
//check if there is similar column
//is already printed, i.e if i and
//jth column match.
for(int j=0; j<i; j++)
{
flag=1;
for(int k=0; k<=COL; k++)
if(M[i][k]!=M[j][k])
flag=0;
if(flag==1)
break;
}
//if no row is similar
if(flag==0)
{
//print the row
for(int j=0; j<COL; j++)
cout<<M[i][j]<<" ";
cout<<endl;
}
}
}
// Driver Code
int main()
{
int M[ROW][COL] = {{0, 1, 0, 0, 1},
{1, 0, 1, 1, 0},
{0, 1, 0, 0, 1},
{1, 0, 1, 0, 0}};
findUniqueRows(M);
return 0;
} | constant | cubic |
// Given a binary matrix of M X N of integers,
// you need to return only unique rows of binary array
#include <bits/stdc++.h>
using namespace std;
#define ROW 4
#define COL 5
class BST
{
int data;
BST *left, *right;
public:
// Default constructor.
BST();
// Parameterized constructor.
BST(int);
// Insert function.
BST* Insert(BST *, int);
// Inorder traversal.
void Inorder(BST *);
};
//convert array to decimal
int convert(int arr[])
{
int sum=0;
for(int i=0; i<COL; i++)
{
sum+=pow(2,i)*arr[i];
}
return sum;
}
//print the column represented as integers
void print(int p)
{
for(int i=0; i<COL; i++)
{
cout<<p%2<<" ";
p/=2;
}
cout<<endl;
}
// Default Constructor definition.
BST :: BST() : data(0), left(NULL), right(NULL){}
// Parameterized Constructor definition.
BST :: BST(int value)
{
data = value;
left = right = NULL;
}
// Insert function definition.
BST* BST :: Insert(BST *root, int value)
{
if(!root)
{
// Insert the first node, if root is NULL.
return new BST(value);
}
//if the value is present
if(value == root->data)
return root;
// Insert data.
if(value > root->data)
{
// Insert right node data, if the 'value'
// to be inserted is greater than 'root' node data.
// Process right nodes.
root->right = Insert(root->right, value);
}
else
{
// Insert left node data, if the 'value'
// to be inserted is greater than 'root' node data.
// Process left nodes.
root->left = Insert(root->left, value);
}
// Return 'root' node, after insertion.
return root;
}
// Inorder traversal function.
// This gives data in sorted order.
void BST :: Inorder(BST *root)
{
if(!root)
{
return;
}
Inorder(root->left);
print( root->data );
Inorder(root->right);
}
// The main function that prints
// all unique rows in a given matrix.
void findUniqueRows(int M[ROW][COL])
{
BST b, *root = NULL;
//Traverse through the matrix
for(int i=0; i<ROW; i++)
{
//insert the row into BST
root=b.Insert(root,convert(M[i]));
}
//print
b.Inorder(root);
}
// Driver Code
int main()
{
int M[ROW][COL] = {{0, 1, 0, 0, 1},
{1, 0, 1, 1, 0},
{0, 1, 0, 0, 1},
{1, 0, 1, 0, 0}};
findUniqueRows(M);
return 0;
} | linear | quadratic |
// Given a binary matrix of M X N of integers,
// you need to return only unique rows of binary array
#include <bits/stdc++.h>
using namespace std;
#define ROW 4
#define COL 5
// A Trie node
class Node
{
public:
bool isEndOfCol;
Node *child[2]; // Only two children needed for 0 and 1
} ;
// A utility function to allocate memory
// for a new Trie node
Node* newNode()
{
Node* temp = new Node();
temp->isEndOfCol = 0;
temp->child[0] = temp->child[1] = NULL;
return temp;
}
// Inserts a new matrix row to Trie.
// If row is already present,
// then returns 0, otherwise insets the row and
// return 1
bool insert(Node** root, int (*M)[COL],
int row, int col )
{
// base case
if (*root == NULL)
*root = newNode();
// Recur if there are more entries in this row
if (col < COL)
return insert (&((*root)->child[M[row][col]]),
M, row, col + 1);
else // If all entries of this row are processed
{
// unique row found, return 1
if (!((*root)->isEndOfCol))
return (*root)->isEndOfCol = 1;
// duplicate row found, return 0
return 0;
}
}
// A utility function to print a row
void printRow(int(*M)[COL], int row)
{
int i;
for(i = 0; i < COL; ++i)
cout << M[row][i] << " ";
cout << endl;
}
// The main function that prints
// all unique rows in a given matrix.
void findUniqueRows(int (*M)[COL])
{
Node* root = NULL; // create an empty Trie
int i;
// Iterate through all rows
for (i = 0; i < ROW; ++i)
// insert row to TRIE
if (insert(&root, M, i, 0))
// unique row found, print it
printRow(M, i);
}
// Driver Code
int main()
{
int M[ROW][COL] = {{0, 1, 0, 0, 1},
{1, 0, 1, 1, 0},
{0, 1, 0, 0, 1},
{1, 0, 1, 0, 0}};
findUniqueRows(M);
return 0;
}
// This code is contributed by rathbhupendra | quadratic | quadratic |
// C++ code to print unique row in a
// given binary matrix
#include<bits/stdc++.h>
using namespace std;
void printArray(int arr[][5], int row,
int col)
{
unordered_set<string> uset;
for(int i = 0; i < row; i++)
{
string s = "";
for(int j = 0; j < col; j++)
s += to_string(arr[i][j]);
if(uset.count(s) == 0)
{
uset.insert(s);
cout << s << endl;
}
}
}
// Driver code
int main()
{
int arr[][5] = {{0, 1, 0, 0, 1},
{1, 0, 1, 1, 0},
{0, 1, 0, 0, 1},
{1, 1, 1, 0, 0}};
printArray(arr, 4, 5);
}
// This code is contributed by
// rathbhupendra | linear | quadratic |
// A C++ program to find the count of distinct substring
// of a string using trie data structure
#include <bits/stdc++.h>
#define MAX_CHAR 26
using namespace std;
// A Suffix Trie (A Trie of all suffixes) Node
class SuffixTrieNode
{
public:
SuffixTrieNode *children[MAX_CHAR];
SuffixTrieNode() // Constructor
{
// Initialize all child pointers as NULL
for (int i = 0; i < MAX_CHAR; i++)
children[i] = NULL;
}
// A recursive function to insert a suffix of the s
// in subtree rooted with this node
void insertSuffix(string suffix);
};
// A Trie of all suffixes
class SuffixTrie
{
SuffixTrieNode *root;
int _countNodesInTrie(SuffixTrieNode *);
public:
// Constructor (Builds a trie of suffies of the given text)
SuffixTrie(string s)
{
root = new SuffixTrieNode();
// Consider all suffixes of given string and insert
// them into the Suffix Trie using recursive function
// insertSuffix() in SuffixTrieNode class
for (int i = 0; i < s.length(); i++)
root->insertSuffix(s.substr(i));
}
// method to count total nodes in suffix trie
int countNodesInTrie() { return _countNodesInTrie(root); }
};
// A recursive function to insert a suffix of the s in
// subtree rooted with this node
void SuffixTrieNode::insertSuffix(string s)
{
// If string has more characters
if (s.length() > 0)
{
// Find the first character and convert it
// into 0-25 range.
char cIndex = s.at(0) - 'a';
// If there is no edge for this character,
// add a new edge
if (children[cIndex] == NULL)
children[cIndex] = new SuffixTrieNode();
// Recur for next suffix
children[cIndex]->insertSuffix(s.substr(1));
}
}
// A recursive function to count nodes in trie
int SuffixTrie::_countNodesInTrie(SuffixTrieNode* node)
{
// If all characters of pattern have been processed,
if (node == NULL)
return 0;
int count = 0;
for (int i = 0; i < MAX_CHAR; i++)
{
// if children is not NULL then find count
// of all nodes in this subtrie
if (node->children[i] != NULL)
count += _countNodesInTrie(node->children[i]);
}
// return count of nodes of subtrie and plus
// 1 because of node's own count
return (1 + count);
}
// Returns count of distinct substrings of str
int countDistinctSubstring(string str)
{
// Construct a Trie of all suffixes
SuffixTrie sTrie(str);
// Return count of nodes in Trie of Suffixes
return sTrie.countNodesInTrie();
}
// Driver program to test above function
int main()
{
string str = "ababa";
cout << "Count of distinct substrings is "
<< countDistinctSubstring(str);
return 0;
} | constant | linear |
#include <bits/stdc++.h>
using namespace std;
// Function to find minimum XOR pair
int minXOR(int arr[], int n)
{
// Sort given array
sort(arr, arr + n);
int minXor = INT_MAX;
int val = 0;
// calculate min xor of consecutive pairs
for (int i = 0; i < n - 1; i++) {
val = arr[i] ^ arr[i + 1];
minXor = min(minXor, val);
}
return minXor;
}
// Driver program
int main()
{
int arr[] = { 9, 5, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << minXOR(arr, n) << endl;
return 0;
} | constant | nlogn |
// A simple C++ program to find max subarray XOR
#include<bits/stdc++.h>
using namespace std;
int maxSubarrayXOR(int arr[], int n)
{
int ans = INT_MIN; // Initialize result
// Pick starting points of subarrays
for (int i=0; i<n; i++)
{
int curr_xor = 0; // to store xor of current subarray
// Pick ending points of subarrays starting with i
for (int j=i; j<n; j++)
{
curr_xor = curr_xor ^ arr[j];
ans = max(ans, curr_xor);
}
}
return ans;
}
// Driver program to test above functions
int main()
{
int arr[] = {8, 1, 2, 12};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Max subarray XOR is " << maxSubarrayXOR(arr, n);
return 0;
} | constant | quadratic |
// C++ program for a Trie based O(n) solution to find max
// subarray XOR
#include<bits/stdc++.h>
using namespace std;
// Assumed int size
#define INT_SIZE 32
// A Trie Node
struct TrieNode
{
int value; // Only used in leaf nodes
TrieNode *arr[2];
};
// Utility function to create a Trie node
TrieNode *newNode()
{
TrieNode *temp = new TrieNode;
temp->value = 0;
temp->arr[0] = temp->arr[1] = NULL;
return temp;
}
// Inserts pre_xor to trie with given root
void insert(TrieNode *root, int pre_xor)
{
TrieNode *temp = root;
// Start from the msb, insert all bits of
// pre_xor into Trie
for (int i=INT_SIZE-1; i>=0; i--)
{
// Find current bit in given prefix
bool val = pre_xor & (1<<i);
// Create a new node if needed
if (temp->arr[val] == NULL)
temp->arr[val] = newNode();
temp = temp->arr[val];
}
// Store value at leaf node
temp->value = pre_xor;
}
// Finds the maximum XOR ending with last number in
// prefix XOR 'pre_xor' and returns the XOR of this maximum
// with pre_xor which is maximum XOR ending with last element
// of pre_xor.
int query(TrieNode *root, int pre_xor)
{
TrieNode *temp = root;
for (int i=INT_SIZE-1; i>=0; i--)
{
// Find current bit in given prefix
bool val = pre_xor & (1<<i);
// Traverse Trie, first look for a
// prefix that has opposite bit
if (temp->arr[1-val]!=NULL)
temp = temp->arr[1-val];
// If there is no prefix with opposite
// bit, then look for same bit.
else if (temp->arr[val] != NULL)
temp = temp->arr[val];
}
return pre_xor^(temp->value);
}
// Returns maximum XOR value of a subarray in arr[0..n-1]
int maxSubarrayXOR(int arr[], int n)
{
// Create a Trie and insert 0 into it
TrieNode *root = newNode();
insert(root, 0);
// Initialize answer and xor of current prefix
int result = INT_MIN, pre_xor =0;
// Traverse all input array element
for (int i=0; i<n; i++)
{
// update current prefix xor and insert it into Trie
pre_xor = pre_xor^arr[i];
insert(root, pre_xor);
// Query for current prefix xor in Trie and update
// result if required
result = max(result, query(root, pre_xor));
}
return result;
}
// Driver program to test above functions
int main()
{
int arr[] = {8, 1, 2, 12};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Max subarray XOR is " << maxSubarrayXOR(arr, n);
return 0;
} | linear | linear |
// C++ code to demonstrate operations of Binary Index Tree
#include <iostream>
using namespace std;
/* n --> No. of elements present in input array.
BITree[0..n] --> Array that represents Binary Indexed Tree.
arr[0..n-1] --> Input array for which prefix sum is evaluated. */
// Returns sum of arr[0..index]. This function assumes
// that the array is preprocessed and partial sums of
// array elements are stored in BITree[].
int getSum(int BITree[], int index)
{
int sum = 0; // Initialize result
// index in BITree[] is 1 more than the index in arr[]
index = index + 1;
// Traverse ancestors of BITree[index]
while (index>0)
{
// Add current element of BITree to sum
sum += BITree[index];
// Move index to parent node in getSum View
index -= index & (-index);
}
return sum;
}
// Updates a node in Binary Index Tree (BITree) at given index
// in BITree. The given value 'val' is added to BITree[i] and
// all of its ancestors in tree.
void updateBIT(int BITree[], int n, int index, int val)
{
// index in BITree[] is 1 more than the index in arr[]
index = index + 1;
// Traverse all ancestors and add 'val'
while (index <= n)
{
// Add 'val' to current node of BI Tree
BITree[index] += val;
// Update index to that of parent in update View
index += index & (-index);
}
}
// Constructs and returns a Binary Indexed Tree for given
// array of size n.
int *constructBITree(int arr[], int n)
{
// Create and initialize BITree[] as 0
int *BITree = new int[n+1];
for (int i=1; i<=n; i++)
BITree[i] = 0;
// Store the actual values in BITree[] using update()
for (int i=0; i<n; i++)
updateBIT(BITree, n, i, arr[i]);
// Uncomment below lines to see contents of BITree[]
//for (int i=1; i<=n; i++)
// cout << BITree[i] << " ";
return BITree;
}
// Driver program to test above functions
int main()
{
int freq[] = {2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9};
int n = sizeof(freq)/sizeof(freq[0]);
int *BITree = constructBITree(freq, n);
cout << "Sum of elements in arr[0..5] is "
<< getSum(BITree, 5);
// Let use test the update operation
freq[3] += 6;
updateBIT(BITree, n, 3, 6); //Update BIT for above change in arr[]
cout << "\nSum of elements in arr[0..5] after update is "
<< getSum(BITree, 5);
return 0;
} | linear | nlogn |
/* C++ program to implement 2D Binary Indexed Tree
2D BIT is basically a BIT where each element is another BIT.
Updating by adding v on (x, y) means it's effect will be found
throughout the rectangle [(x, y), (max_x, max_y)],
and query for (x, y) gives you the result of the rectangle
[(0, 0), (x, y)], assuming the total rectangle is
[(0, 0), (max_x, max_y)]. So when you query and update on
this BIT,you have to be careful about how many times you are
subtracting a rectangle and adding it. Simple set union formula
works here.
So if you want to get the result of a specific rectangle
[(x1, y1), (x2, y2)], the following steps are necessary:
Query(x1,y1,x2,y2) = getSum(x2, y2)-getSum(x2, y1-1) -
getSum(x1-1, y2)+getSum(x1-1, y1-1)
Here 'Query(x1,y1,x2,y2)' means the sum of elements enclosed
in the rectangle with bottom-left corner's co-ordinates
(x1, y1) and top-right corner's co-ordinates - (x2, y2)
Constraints -> x1<=x2 and y1<=y2
/\
y |
| --------(x2,y2)
| | |
| | |
| | |
| ---------
| (x1,y1)
|
|___________________________
(0, 0) x-->
In this program we have assumed a square matrix. The
program can be easily extended to a rectangular one. */
#include<bits/stdc++.h>
using namespace std;
#define N 4 // N-->max_x and max_y
// A structure to hold the queries
struct Query
{
int x1, y1; // x and y co-ordinates of bottom left
int x2, y2; // x and y co-ordinates of top right
};
// A function to update the 2D BIT
void updateBIT(int BIT[][N+1], int x, int y, int val)
{
for (; x <= N; x += (x & -x))
{
// This loop update all the 1D BIT inside the
// array of 1D BIT = BIT[x]
for (int yy=y; yy <= N; yy += (yy & -yy))
BIT[x][yy] += val;
}
return;
}
// A function to get sum from (0, 0) to (x, y)
int getSum(int BIT[][N+1], int x, int y)
{
int sum = 0;
for(; x > 0; x -= x&-x)
{
// This loop sum through all the 1D BIT
// inside the array of 1D BIT = BIT[x]
for(int yy=y; yy > 0; yy -= yy&-yy)
{
sum += BIT[x][yy];
}
}
return sum;
}
// A function to create an auxiliary matrix
// from the given input matrix
void constructAux(int mat[][N], int aux[][N+1])
{
// Initialise Auxiliary array to 0
for (int i=0; i<=N; i++)
for (int j=0; j<=N; j++)
aux[i][j] = 0;
// Construct the Auxiliary Matrix
for (int j=1; j<=N; j++)
for (int i=1; i<=N; i++)
aux[i][j] = mat[N-j][i-1];
return;
}
// A function to construct a 2D BIT
void construct2DBIT(int mat[][N], int BIT[][N+1])
{
// Create an auxiliary matrix
int aux[N+1][N+1];
constructAux(mat, aux);
// Initialise the BIT to 0
for (int i=1; i<=N; i++)
for (int j=1; j<=N; j++)
BIT[i][j] = 0;
for (int j=1; j<=N; j++)
{
for (int i=1; i<=N; i++)
{
// Creating a 2D-BIT using update function
// everytime we/ encounter a value in the
// input 2D-array
int v1 = getSum(BIT, i, j);
int v2 = getSum(BIT, i, j-1);
int v3 = getSum(BIT, i-1, j-1);
int v4 = getSum(BIT, i-1, j);
// Assigning a value to a particular element
// of 2D BIT
updateBIT(BIT, i, j, aux[i][j]-(v1-v2-v4+v3));
}
}
return;
}
// A function to answer the queries
void answerQueries(Query q[], int m, int BIT[][N+1])
{
for (int i=0; i<m; i++)
{
int x1 = q[i].x1 + 1;
int y1 = q[i].y1 + 1;
int x2 = q[i].x2 + 1;
int y2 = q[i].y2 + 1;
int ans = getSum(BIT, x2, y2)-getSum(BIT, x2, y1-1)-
getSum(BIT, x1-1, y2)+getSum(BIT, x1-1, y1-1);
printf ("Query(%d, %d, %d, %d) = %d\n",
q[i].x1, q[i].y1, q[i].x2, q[i].y2, ans);
}
return;
}
// Driver program
int main()
{
int mat[N][N] = {{1, 2, 3, 4},
{5, 3, 8, 1},
{4, 6, 7, 5},
{2, 4, 8, 9}};
// Create a 2D Binary Indexed Tree
int BIT[N+1][N+1];
construct2DBIT(mat, BIT);
/* Queries of the form - x1, y1, x2, y2
For example the query- {1, 1, 3, 2} means the sub-matrix-
y
/\
3 | 1 2 3 4 Sub-matrix
2 | 5 3 8 1 {1,1,3,2} ---> 3 8 1
1 | 4 6 7 5 6 7 5
0 | 2 4 8 9
|
--|------ 0 1 2 3 ----> x
|
Hence sum of the sub-matrix = 3+8+1+6+7+5 = 30
*/
Query q[] = {{1, 1, 3, 2}, {2, 3, 3, 3}, {1, 1, 1, 1}};
int m = sizeof(q)/sizeof(q[0]);
answerQueries(q, m, BIT);
return(0);
} | quadratic | nlogn |
// A Simple C++ O(n^3) program to count inversions of size 3
#include<bits/stdc++.h>
using namespace std;
// Returns counts of inversions of size three
int getInvCount(int arr[],int n)
{
int invcount = 0; // Initialize result
for (int i=0; i<n-2; i++)
{
for (int j=i+1; j<n-1; j++)
{
if (arr[i]>arr[j])
{
for (int k=j+1; k<n; k++)
{
if (arr[j]>arr[k])
invcount++;
}
}
}
}
return invcount;
}
// Driver program to test above function
int main()
{
int arr[] = {8, 4, 2, 1};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Inversion Count : " << getInvCount(arr, n);
return 0;
} | constant | cubic |
// A O(n^2) C++ program to count inversions of size 3
#include<bits/stdc++.h>
using namespace std;
// Returns count of inversions of size 3
int getInvCount(int arr[], int n)
{
int invcount = 0; // Initialize result
for (int i=1; i<n-1; i++)
{
// Count all smaller elements on right of arr[i]
int small = 0;
for (int j=i+1; j<n; j++)
if (arr[i] > arr[j])
small++;
// Count all greater elements on left of arr[i]
int great = 0;
for (int j=i-1; j>=0; j--)
if (arr[i] < arr[j])
great++;
// Update inversion count by adding all inversions
// that have arr[i] as middle of three elements
invcount += great*small;
}
return invcount;
}
// Driver program to test above function
int main()
{
int arr[] = {8, 4, 2, 1};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Inversion Count : " << getInvCount(arr, n);
return 0;
} | constant | quadratic |
// C++ program to count the number of inversion
// pairs in a 2D matrix
#include <bits/stdc++.h>
using namespace std;
// for simplicity, we are taking N as 4
#define N 4
// Function to update a 2D BIT. It updates the
// value of bit[l][r] by adding val to bit[l][r]
void update(int l, int r, int val, int bit[][N + 1])
{
for (int i = l; i <= N; i += i & -i)
for (int j = r; j <= N; j += j & -j)
bit[i][j] += val;
}
// function to find cumulative sum upto
// index (l, r) in the 2D BIT
long long query(int l, int r, int bit[][N + 1])
{
long long ret = 0;
for (int i = l; i > 0; i -= i & -i)
for (int j = r; j > 0; j -= j & -j)
ret += bit[i][j];
return ret;
}
// function to count and return the number
// of inversion pairs in the matrix
long long countInversionPairs(int mat[][N])
{
// the 2D bit array and initialize it with 0.
int bit[N+1][N+1] = {0};
// v will store the tuple (-mat[i][j], i, j)
vector<pair<int, pair<int, int> > > v;
// store the tuples in the vector v
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j)
// Note that we are not using the pair
// (0, 0) because BIT update and query
// operations are not done on index 0
v.push_back(make_pair(-mat[i][j],
make_pair(i+1, j+1)));
// sort the vector v according to the
// first element of the tuple, i.e., -mat[i][j]
sort(v.begin(), v.end());
// inv_pair_cnt will store the number of
// inversion pairs
long long inv_pair_cnt = 0;
// traverse all the tuples of vector v
int i = 0;
while (i < v.size())
{
int curr = i;
// 'pairs' will store the position of each element,
// i.e., the pair (i, j) of each tuple of the vector v
vector<pair<int, int> > pairs;
// consider the current tuple in v and all its
// adjacent tuples whose first value, i.e., the
// value of –mat[i][j] is same
while (curr < v.size() &&
(v[curr].first == v[i].first))
{
// push the position of the current element in 'pairs'
pairs.push_back(make_pair(v[curr].second.first,
v[curr].second.second));
// add the number of elements which are
// less than the current element and lie on the right
// side in the vector v
inv_pair_cnt += query(v[curr].second.first,
v[curr].second.second, bit);
curr++;
}
vector<pair<int, int> >::iterator it;
// traverse the 'pairs' vector
for (it = pairs.begin(); it != pairs.end(); ++it)
{
int x = it->first;
int y = it->second;
// update the position (x, y) by 1
update(x, y, 1, bit);
}
i = curr;
}
return inv_pair_cnt;
}
// Driver program
int main()
{
int mat[N][N] = { { 4, 7, 2, 9 },
{ 6, 4, 1, 7 },
{ 5, 3, 8, 1 },
{ 3, 2, 5, 6 } };
long long inv_pair_cnt = countInversionPairs(mat);
cout << "The number of inversion pairs are : "
<< inv_pair_cnt << endl;
return 0;
} | quadratic | logn |
// Naive algorithm for building suffix array of a given text
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
// Structure to store information of a suffix
struct suffix
{
int index;
char *suff;
};
// A comparison function used by sort() to compare two suffixes
int cmp(struct suffix a, struct suffix b)
{
return strcmp(a.suff, b.suff) < 0? 1 : 0;
}
// This is the main function that takes a string 'txt' of size n as an
// argument, builds and return the suffix array for the given string
int *buildSuffixArray(char *txt, int n)
{
// A structure to store suffixes and their indexes
struct suffix suffixes[n];
// Store suffixes and their indexes in an array of structures.
// The structure is needed to sort the suffixes alphabetically
// and maintain their old indexes while sorting
for (int i = 0; i < n; i++)
{
suffixes[i].index = i;
suffixes[i].suff = (txt+i);
}
// Sort the suffixes using the comparison function
// defined above.
sort(suffixes, suffixes+n, cmp);
// Store indexes of all sorted suffixes in the suffix array
int *suffixArr = new int[n];
for (int i = 0; i < n; i++)
suffixArr[i] = suffixes[i].index;
// Return the suffix array
return suffixArr;
}
// A utility function to print an array of given size
void printArr(int arr[], int n)
{
for(int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver program to test above functions
int main()
{
char txt[] = "banana";
int n = strlen(txt);
int *suffixArr = buildSuffixArray(txt, n);
cout << "Following is suffix array for " << txt << endl;
printArr(suffixArr, n);
return 0;
} | linear | nlogn |
// C++ program to insert a node in AVL tree
#include<bits/stdc++.h>
using namespace std;
// An AVL tree node
class Node
{
public:
int key;
Node *left;
Node *right;
int height;
};
// A utility function to get the
// height of the tree
int height(Node *N)
{
if (N == NULL)
return 0;
return N->height;
}
// A utility function to get maximum
// of two integers
int max(int a, int b)
{
return (a > b)? a : b;
}
/* Helper function that allocates a
new node with the given key and
NULL left and right pointers. */
Node* newNode(int key)
{
Node* node = new Node();
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1; // new node is initially
// added at leaf
return(node);
}
// A utility function to right
// rotate subtree rooted with y
// See the diagram given above.
Node *rightRotate(Node *y)
{
Node *x = y->left;
Node *T2 = x->right;
// Perform rotation
x->right = y;
y->left = T2;
// Update heights
y->height = max(height(y->left),
height(y->right)) + 1;
x->height = max(height(x->left),
height(x->right)) + 1;
// Return new root
return x;
}
// A utility function to left
// rotate subtree rooted with x
// See the diagram given above.
Node *leftRotate(Node *x)
{
Node *y = x->right;
Node *T2 = y->left;
// Perform rotation
y->left = x;
x->right = T2;
// Update heights
x->height = max(height(x->left),
height(x->right)) + 1;
y->height = max(height(y->left),
height(y->right)) + 1;
// Return new root
return y;
}
// Get Balance factor of node N
int getBalance(Node *N)
{
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
// Recursive function to insert a key
// in the subtree rooted with node and
// returns the new root of the subtree.
Node* insert(Node* node, int key)
{
/* 1. Perform the normal BST insertion */
if (node == NULL)
return(newNode(key));
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
else // Equal keys are not allowed in BST
return node;
/* 2. Update height of this ancestor node */
node->height = 1 + max(height(node->left),
height(node->right));
/* 3. Get the balance factor of this ancestor
node to check whether this node became
unbalanced */
int balance = getBalance(node);
// If this node becomes unbalanced, then
// there are 4 cases
// Left Left Case
if (balance > 1 && key < node->left->key)
return rightRotate(node);
// Right Right Case
if (balance < -1 && key > node->right->key)
return leftRotate(node);
// Left Right Case
if (balance > 1 && key > node->left->key)
{
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Left Case
if (balance < -1 && key < node->right->key)
{
node->right = rightRotate(node->right);
return leftRotate(node);
}
/* return the (unchanged) node pointer */
return node;
}
// A utility function to print preorder
// traversal of the tree.
// The function also prints height
// of every node
void preOrder(Node *root)
{
if(root != NULL)
{
cout << root->key << " ";
preOrder(root->left);
preOrder(root->right);
}
}
// Driver Code
int main()
{
Node *root = NULL;
/* Constructing tree given in
the above figure */
root = insert(root, 10);
root = insert(root, 20);
root = insert(root, 30);
root = insert(root, 40);
root = insert(root, 50);
root = insert(root, 25);
/* The constructed AVL Tree would be
30
/ \
20 40
/ \ \
10 25 50
*/
cout << "Preorder traversal of the "
"constructed AVL tree is \n";
preOrder(root);
return 0;
}
// This code is contributed by
// rathbhupendra | constant | nlogn |
// C++ program to find N'th element in a set formed
// by sum of two arrays
#include<bits/stdc++.h>
using namespace std;
//Function to calculate the set of sums
int calculateSetOfSum(int arr1[], int size1, int arr2[],
int size2, int N)
{
// Insert each pair sum into set. Note that a set
// stores elements in sorted order and unique elements
set<int> s;
for (int i=0 ; i < size1; i++)
for (int j=0; j < size2; j++)
s.insert(arr1[i]+arr2[j]);
// If set has less than N elements
if (s.size() < N)
return -1;
// Find N'tb item in set and return it
set<int>::iterator it = s.begin();
for (int count=1; count<N; count++)
it++;
return *it;
}
// Driver code
int main()
{
int arr1[] = {1, 2};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int arr2[] = {3, 4};
int size2 = sizeof(arr2) / sizeof(arr2[0]);
int N = 3;
int res = calculateSetOfSum(arr1, size1, arr2, size2, N);
if (res == -1)
cout << "N'th term doesn't exists in set";
else
cout << "N'th element in the set of sums is "
<< res;
return 0;
} | linear | quadratic |
#include <iostream>
using namespace std;
void constructLowerArray(int arr[], int* countSmaller,
int n)
{
int i, j;
// Initialize all the counts in
// countSmaller array as 0
for (i = 0; i < n; i++)
countSmaller[i] = 0;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[i])
countSmaller[i]++;
}
}
}
// Utility function that prints
// out an array on a line
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << "\n";
}
// Driver code
int main()
{
int arr[] = { 12, 1, 2, 3, 0, 11, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
int* low = (int*)malloc(sizeof(int) * n);
constructLowerArray(arr, low, n);
printArray(low, n);
return 0;
}
// This code is contributed by Hemant Jain | constant | quadratic |
#include <bits/stdc++.h>
using namespace std;
void merge(vector<pair<int, int> >& v, vector<int>& ans,
int l, int mid, int h)
{
vector<pair<int, int> >
t; // temporary array for merging both halves
int i = l;
int j = mid + 1;
while (i < mid + 1 && j <= h) {
// v[i].first is greater than all
// the elements from j till h.
if (v[i].first > v[j].first) {
ans[v[i].second] += (h - j + 1);
t.push_back(v[i]);
i++;
}
else {
t.push_back(v[j]);
j++;
}
}
// if any elements left in left array
while (i <= mid)
t.push_back(v[i++]);
// if any elements left in right array
while (j <= h)
t.push_back(v[j++]);
// putting elements back in main array in
// descending order
for (int k = 0, i = l; i <= h; i++, k++)
v[i] = t[k];
}
void mergesort(vector<pair<int, int> >& v, vector<int>& ans,
int i, int j)
{
if (i < j) {
int mid = (i + j) / 2;
// calling mergesort for left half
mergesort(v, ans, i, mid);
// calling mergesort for right half
mergesort(v, ans, mid + 1, j);
// merging both halves and generating answer
merge(v, ans, i, mid, j);
}
}
vector<int> constructLowerArray(int* arr, int n)
{
vector<pair<int, int> > v;
// inserting elements and corresponding index
// as pair
for (int i = 0; i < n; i++)
v.push_back({ arr[i], i });
// answer array for keeping count
// initialized by 0,
vector<int> ans(n, 0);
// calling mergesort
mergesort(v, ans, 0, n - 1);
return ans;
}
// Driver Code Starts.
int main()
{
int arr[] = { 12, 1, 2, 3, 0, 11, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
auto ans = constructLowerArray(arr, n);
for (auto x : ans) {
cout << x << " ";
}
cout << "\n";
return 0;
}
// Driver code ends.
// This code is contributed by Manjeet Singh | linear | nlogn |
#include <iostream>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
// An AVL tree node
struct node {
int key;
struct node* left;
struct node* right;
int height;
// size of the tree rooted
// with this node
int size;
};
// A utility function to get
// maximum of two integers
int max(int a, int b);
// A utility function to get
// height of the tree rooted with N
int height(struct node* N)
{
if (N == NULL)
return 0;
return N->height;
}
// A utility function to size
// of the tree of rooted with N
int size(struct node* N)
{
if (N == NULL)
return 0;
return N->size;
}
// A utility function to
// get maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }
// Helper function that allocates a
// new node with the given key and
// NULL left and right pointers.
struct node* newNode(int key)
{
struct node* node
= (struct node*)malloc(sizeof(struct node));
node->key = key;
node->left = NULL;
node->right = NULL;
// New node is initially added at leaf
node->height = 1;
node->size = 1;
return (node);
}
// A utility function to right rotate
// subtree rooted with y
struct node* rightRotate(struct node* y)
{
struct node* x = y->left;
struct node* T2 = x->right;
// Perform rotation
x->right = y;
y->left = T2;
// Update heights
y->height = max(height(y->left), height(y->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
// Update sizes
y->size = size(y->left) + size(y->right) + 1;
x->size = size(x->left) + size(x->right) + 1;
// Return new root
return x;
}
// A utility function to left rotate
// subtree rooted with x
struct node* leftRotate(struct node* x)
{
struct node* y = x->right;
struct node* T2 = y->left;
// Perform rotation
y->left = x;
x->right = T2;
// Update heights
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;
// Update sizes
x->size = size(x->left) + size(x->right) + 1;
y->size = size(y->left) + size(y->right) + 1;
// Return new root
return y;
}
// Get Balance factor of node N
int getBalance(struct node* N)
{
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
// Inserts a new key to the tree rotted with
// node. Also, updates *count to contain count
// of smaller elements for the new key
struct node* insert(struct node* node, int key, int* count)
{
// 1. Perform the normal BST rotation
if (node == NULL)
return (newNode(key));
if (key < node->key)
node->left = insert(node->left, key, count);
else {
node->right = insert(node->right, key, count);
// UPDATE COUNT OF SMALLER ELEMENTS FOR KEY
*count = *count + size(node->left) + 1;
}
// 2.Update height and size of this ancestor node
node->height
= max(height(node->left), height(node->right)) + 1;
node->size = size(node->left) + size(node->right) + 1;
// 3. Get the balance factor of this
// ancestor node to check whether this
// node became unbalanced
int balance = getBalance(node);
// If this node becomes unbalanced,
// then there are 4 cases
// Left Left Case
if (balance > 1 && key < node->left->key)
return rightRotate(node);
// Right Right Case
if (balance < -1 && key > node->right->key)
return leftRotate(node);
// Left Right Case
if (balance > 1 && key > node->left->key) {
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Left Case
if (balance < -1 && key < node->right->key) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
// Return the (unchanged) node pointer
return node;
}
// The following function updates the
// countSmaller array to contain count of
// smaller elements on right side.
void constructLowerArray(int arr[], int countSmaller[],
int n)
{
int i, j;
struct node* root = NULL;
// Initialize all the counts in
// countSmaller array as 0
for (i = 0; i < n; i++)
countSmaller[i] = 0;
// Starting from rightmost element,
// insert all elements one by one in
// an AVL tree and get the count of
// smaller elements
for (i = n - 1; i >= 0; i--) {
root = insert(root, arr[i], &countSmaller[i]);
}
}
// Utility function that prints out an
// array on a line
void printArray(int arr[], int size)
{
int i;
cout << "\n";
for (i = 0; i < size; i++)
cout << arr[i] << " ";
}
// Driver code
int main()
{
int arr[] = { 12, 1, 2, 3, 0, 11, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
int* low = (int*)malloc(sizeof(int) * n);
constructLowerArray(arr, low, n);
printArray(low, n);
return 0;
}
// This code is contributed by Hemant Jain | linear | nlogn |
#include <bits/stdc++.h>
using namespace std;
// BST node structure
class Node {
public:
int val;
int count;
Node* left;
Node* right;
// Constructor
Node(int num1, int num2)
{
this->val = num1;
this->count = num2;
this->left = this->right = NULL;
}
};
// Function to addNode and find the smaller
// elements on the right side
int addNode(Node*& root, int value, int countSmaller)
{
// Base case
if (root == NULL) {
root = new Node(value, 0);
return countSmaller;
}
if (root->val < value) {
return root->count
+ addNode(root->right, value,
countSmaller + 1);
}
else {
root->count++;
return addNode(root->left, value, countSmaller);
}
}
// Driver code
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int data[] = { 12, 1, 2, 3, 0, 11, 4 };
int size = sizeof(data) / sizeof(data[0]);
int ans[size] = { 0 };
Node* root = NULL;
for (int i = size - 1; i >= 0; i--) {
ans[i] = addNode(root, data[i], 0);
}
for (int i = 0; i < size; i++)
cout << ans[i] << " ";
return 0;
}
// This code is contributed by divyanshu gupta | linear | quadratic |
// C++ program to sort an array according absolute
// difference with x.
#include <bits/stdc++.h>
using namespace std;
// Function to sort an array according absolute
// difference with x.
void rearrange(int arr[], int n, int x)
{
multimap<int, int> m;
multimap<int, int>::iterator it;
// Store values in a map with the difference
// with X as key
for (int i = 0; i < n; i++)
m.insert(make_pair(abs(x - arr[i]), arr[i]));
// Update the values of array
int i = 0;
for (it = m.begin(); it != m.end(); it++)
arr[i++] = (*it).second;
}
// Function to print the array
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
// Driver code
int main()
{
int arr[] = { 10, 5, 3, 9, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 7;
// Function call
rearrange(arr, n, x);
printArray(arr, n);
return 0;
} | linear | nlogn |
// CPP program for the above approach
#include <bits/stdc++.h>
using namespace std;
void rearrange(int arr[], int n, int x)
{
/*
We can send the value x into
lambda expression as
follows: [capture]()
{
//statements
//capture value can be used inside
}
*/
stable_sort(arr, arr + n, [x](int a, int b) {
if (abs(a - x) < abs(b - x))
return true;
else
return false;
});
}
// Driver code
int main()
{
int arr[] = { 10, 5, 3, 9, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 7;
// Function call
rearrange(arr, n, x);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
} | constant | nlogn |
// C++ program to find maximum product of an increasing
// subsequence of size 3
#include <bits/stdc++.h>
using namespace std;
// Returns maximum product of an increasing subsequence of
// size 3 in arr[0..n-1]. If no such subsequence exists,
// then it returns INT_MIN
long long int maxProduct(int arr[], int n)
{
int result = INT_MIN;
// T.C : O(n^3)
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
result
= max(result, arr[i] * arr[j] * arr[k]);
}
}
}
return result;
}
// Driver Program
int main()
{
int arr[] = { 10, 11, 9, 5, 6, 1, 20 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << maxProduct(arr, n) << endl;
return 0;
} | constant | cubic |
// C++ program to find maximum product of an increasing
// subsequence of size 3
#include <bits/stdc++.h>
using namespace std;
// Returns maximum product of an increasing subsequence of
// size 3 in arr[0..n-1]. If no such subsequence exists,
// then it returns INT_MIN
long long int maxProduct(int arr[], int n)
{
// An array ti store closest smaller element on left
// side of every element. If there is no such element
// on left side, then smaller[i] be -1.
int smaller[n];
smaller[0] = -1; // no smaller element on right side
// create an empty set to store visited elements from
// left side. Set can also quickly find largest smaller
// of an element.
set<int> S;
for (int i = 0; i < n; i++) {
// insert arr[i] into the set S
auto j = S.insert(arr[i]);
auto itc
= j.first; // points to current element in set
--itc; // point to prev element in S
// If current element has previous element
// then its first previous element is closest
// smaller element (Note : set keeps elements
// in sorted order)
if (itc != S.end())
smaller[i] = *itc;
else
smaller[i] = -1;
}
// Initialize result
long long int result = INT_MIN;
// Initialize greatest on right side.
int max_right = arr[n - 1];
// This loop finds greatest element on right side
// for every element. It also updates result when
// required.
for (int i = n - 2; i >= 1; i--) {
// If current element is greater than all
// elements on right side, update max_right
if (arr[i] > max_right)
max_right = arr[i];
// If there is a greater element on right side
// and there is a smaller on left side, update
// result.
else if (smaller[i] != -1)
result = max((long long int)(smaller[i] * arr[i]
* max_right),
result);
}
return result;
}
// Driver Program
int main()
{
int arr[] = { 10, 11, 9, 5, 6, 1, 20 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << maxProduct(arr, n) << endl;
return 0;
} | linear | nlogn |
// C++ Code for the above approach
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data,
a pointer to left child
and a pointer to right child */
class Node {
public:
int data;
Node* left;
Node* right;
};
// Function to return a new Node
Node* newNode(int data)
{
Node* node = new Node();
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
// Function to convert bst to
// a doubly linked list
void bstTodll(Node* root, Node*& head)
{
// if root is NULL
if (!root)
return;
// Convert right subtree recursively
bstTodll(root->right, head);
// Update root
root->right = head;
// if head is not NULL
if (head) {
// Update left of the head
head->left = root;
}
// Update head
head = root;
// Convert left subtree recursively
bstTodll(root->left, head);
}
// Function to merge two sorted linked list
Node* mergeLinkedList(Node* head1, Node* head2)
{
/*Create head and tail for result list*/
Node* head = NULL;
Node* tail = NULL;
while (head1 && head2) {
if (head1->data < head2->data) {
if (!head)
head = head1;
else {
tail->right = head1;
head1->left = tail;
}
tail = head1;
head1 = head1->right;
}
else {
if (!head)
head = head2;
else {
tail->right = head2;
head2->left = tail;
}
tail = head2;
head2 = head2->right;
}
}
while (head1) {
tail->right = head1;
head1->left = tail;
tail = head1;
head1 = head1->right;
}
while (head2) {
tail->right = head2;
head2->left = tail;
tail = head2;
head2 = head2->right;
}
// Return the created DLL
return head;
}
// function to convert list to bst
Node* sortedListToBST(Node*& head, int n)
{
// if no element is left or head is null
if (n <= 0 || !head)
return NULL;
// Create left part from the list recursively
Node* left = sortedListToBST(head, n / 2);
Node* root = head;
root->left = left;
head = head->right;
// Create left part from the list recursively
root->right = sortedListToBST(head, n - (n / 2) - 1);
// Return the root of BST
return root;
}
// This function merges two balanced BSTs
Node* mergeTrees(Node* root1, Node* root2, int m, int n)
{
// Convert BSTs into sorted Doubly Linked Lists
Node* head1 = NULL;
bstTodll(root1, head1);
head1->left = NULL;
Node* head2 = NULL;
bstTodll(root2, head2);
head2->left = NULL;
// Merge the two sorted lists into one
Node* head = mergeLinkedList(head1, head2);
// Construct a tree from the merged lists
return sortedListToBST(head, m + n);
}
void printInorder(Node* node)
{
// if current node is NULL
if (!node) {
return;
}
printInorder(node->left);
// Print node of current data
cout << node->data << " ";
printInorder(node->right);
}
/* Driver code*/
int main()
{
/* Create following tree as first balanced BST
100
/ \
50 300
/ \
20 70 */
Node* root1 = newNode(100);
root1->left = newNode(50);
root1->right = newNode(300);
root1->left->left = newNode(20);
root1->left->right = newNode(70);
/* Create following tree as second balanced BST
80
/ \
40 120
*/
Node* root2 = newNode(80);
root2->left = newNode(40);
root2->right = newNode(120);
// Function Call
Node* mergedTree = mergeTrees(root1, root2, 5, 3);
cout << "Following is Inorder traversal of the merged "
"tree \n";
printInorder(mergedTree);
return 0;
}
// This code is contributed by Tapesh(tapeshdua420) | constant | linear |
/* CPP program to check if
a tree is height-balanced or not */
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data,
pointer to left child and
a pointer to right child */
class Node {
public:
int data;
Node* left;
Node* right;
Node(int d)
{
int data = d;
left = right = NULL;
}
};
// Function to calculate the height of a tree
int height(Node* node)
{
// base case tree is empty
if (node == NULL)
return 0;
// If tree is not empty then
// height = 1 + max of left height
// and right heights
return 1 + max(height(node->left), height(node->right));
}
// Returns true if binary tree
// with root as root is height-balanced
bool isBalanced(Node* root)
{
// for height of left subtree
int lh;
// for height of right subtree
int rh;
// If tree is empty then return true
if (root == NULL)
return 1;
// Get the height of left and right sub trees
lh = height(root->left);
rh = height(root->right);
if (abs(lh - rh) <= 1 && isBalanced(root->left)
&& isBalanced(root->right))
return 1;
// If we reach here then tree is not height-balanced
return 0;
}
// Driver code
int main()
{
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->left->left->left = new Node(8);
if (isBalanced(root))
cout << "Tree is balanced";
else
cout << "Tree is not balanced";
return 0;
}
// This code is contributed by rathbhupendra | linear | quadratic |
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Structure of a tree node
struct Node {
int key;
struct Node* left;
struct Node* right;
Node(int k)
{
key = k;
left = right = NULL;
}
};
// Function to check if tree is height balanced
int isBalanced(Node* root)
{
if (root == NULL)
return 0;
int lh = isBalanced(root->left);
if (lh == -1)
return -1;
int rh = isBalanced(root->right);
if (rh == -1)
return -1;
if (abs(lh - rh) > 1)
return -1;
else
return max(lh, rh) + 1;
}
// Driver code
int main()
{
Node* root = new Node(10);
root->left = new Node(5);
root->right = new Node(30);
root->right->left = new Node(15);
root->right->right = new Node(20);
if (isBalanced(root) > 0)
cout << "Balanced";
else
cout << "Not Balanced";
return 0;
} | linear | linear |
// C++ program to find number of islands
// using Disjoint Set data structure.
#include <bits/stdc++.h>
using namespace std;
// Class to represent
// Disjoint Set Data structure
class DisjointUnionSets
{
vector<int> rank, parent;
int n;
public:
DisjointUnionSets(int n)
{
rank.resize(n);
parent.resize(n);
this->n = n;
makeSet();
}
void makeSet()
{
// Initially, all elements
// are in their own set.
for (int i = 0; i < n; i++)
parent[i] = i;
}
// Finds the representative of the set
// that x is an element of
int find(int x)
{
if (parent[x] != x)
{
// if x is not the parent of itself,
// then x is not the representative of
// its set.
// so we recursively call Find on its parent
// and move i's node directly under the
// representative of this set
parent[x]=find(parent[x]);
}
return parent[x];
}
// Unites the set that includes x and the set
// that includes y
void Union(int x, int y)
{
// Find the representatives(or the root nodes)
// for x an y
int xRoot = find(x);
int yRoot = find(y);
// Elements are in the same set,
// no need to unite anything.
if (xRoot == yRoot)
return;
// If x's rank is less than y's rank
// Then move x under y so that
// depth of tree remains less
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
// Else if y's rank is less than x's rank
// Then move y under x so that depth of tree
// remains less
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else // Else if their ranks are the same
{
// Then move y under x (doesn't matter
// which one goes where)
parent[yRoot] = xRoot;
// And increment the result tree's
// rank by 1
rank[xRoot] = rank[xRoot] + 1;
}
}
};
// Returns number of islands in a[][]
int countIslands(vector<vector<int>>a)
{
int n = a.size();
int m = a[0].size();
DisjointUnionSets *dus = new DisjointUnionSets(n * m);
/* The following loop checks for its neighbours
and unites the indexes if both are 1. */
for (int j = 0; j < n; j++)
{
for (int k = 0; k < m; k++)
{
// If cell is 0, nothing to do
if (a[j][k] == 0)
continue;
// Check all 8 neighbours and do a Union
// with neighbour's set if neighbour is
// also 1
if (j + 1 < n && a[j + 1][k] == 1)
dus->Union(j * (m) + k,
(j + 1) * (m) + k);
if (j - 1 >= 0 && a[j - 1][k] == 1)
dus->Union(j * (m) + k,
(j - 1) * (m) + k);
if (k + 1 < m && a[j][k + 1] == 1)
dus->Union(j * (m) + k,
(j) * (m) + k + 1);
if (k - 1 >= 0 && a[j][k - 1] == 1)
dus->Union(j * (m) + k,
(j) * (m) + k - 1);
if (j + 1 < n && k + 1 < m &&
a[j + 1][k + 1] == 1)
dus->Union(j * (m) + k,
(j + 1) * (m) + k + 1);
if (j + 1 < n && k - 1 >= 0 &&
a[j + 1][k - 1] == 1)
dus->Union(j * m + k,
(j + 1) * (m) + k - 1);
if (j - 1 >= 0 && k + 1 < m &&
a[j - 1][k + 1] == 1)
dus->Union(j * m + k,
(j - 1) * m + k + 1);
if (j - 1 >= 0 && k - 1 >= 0 &&
a[j - 1][k - 1] == 1)
dus->Union(j * m + k,
(j - 1) * m + k - 1);
}
}
// Array to note down frequency of each set
int *c = new int[n * m];
int numberOfIslands = 0;
for (int j = 0; j < n; j++)
{
for (int k = 0; k < m; k++)
{
if (a[j][k] == 1)
{
int x = dus->find(j * m + k);
// If frequency of set is 0,
// increment numberOfIslands
if (c[x] == 0)
{
numberOfIslands++;
c[x]++;
}
else
c[x]++;
}
}
}
return numberOfIslands;
}
// Driver Code
int main(void)
{
vector<vector<int>>a = {{1, 1, 0, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 0, 1, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1}};
cout << "Number of Islands is: "
<< countIslands(a) << endl;
}
// This code is contributed by ankush_953 | quadratic | quadratic |
// C++ program to find the height of the generic
// tree(n-ary tree) if parent array is given
#include <bits/stdc++.h>
using namespace std;
// function to fill the height vector
int rec(int i, int parent[], vector<int> height)
{
// if we have reached root node the
// return 1 as height of root node
if (parent[i] == -1) {
return 1;
}
// if we have calculated height of a
// node then return if
if (height[i] != -1) {
return height[i];
}
// height from root to a node = height
// from root to nodes parent + 1
height[i] = rec(parent[i], parent, height) + 1;
// return nodes height
return height[i];
}
// function to find the height of tree
int findHeight(int* parent, int n)
{
int res = 0;
// vector to store heights of all nodes
vector<int> height(n, -1);
for (int i = 0; i < n; i++) {
res = max(res, rec(i, parent, height));
}
return res;
}
// Driver program
int main()
{
int parent[] = { -1, 0, 1, 6, 6, 0, 0, 2, 7 };
int n = sizeof(parent) / sizeof(parent[0]);
int height = findHeight(parent, n);
cout << "Height of the given tree is: "
<< height << endl;
return 0;
} | linear | linear |
// C++ program to find number
// of children of given node
#include <bits/stdc++.h>
using namespace std;
// Represents a node of an n-ary tree
class Node {
public:
int key;
vector<Node*> child;
Node(int data)
{
key = data;
}
};
// Function to calculate number
// of children of given node
int numberOfChildren(Node* root, int x)
{
// initialize the numChildren as 0
int numChildren = 0;
if (root == NULL)
return 0;
// Creating a queue and pushing the root
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
// If this node has children
while (n > 0) {
// Dequeue an item from queue and
// check if it is equal to x
// If YES, then return number of children
Node* p = q.front();
q.pop();
if (p->key == x) {
numChildren = numChildren + p->child.size();
return numChildren;
}
// Enqueue all children of the dequeued item
for (int i = 0; i < p->child.size(); i++)
q.push(p->child[i]);
n--;
}
}
return numChildren;
}
// Driver program
int main()
{
// Creating a generic tree
Node* root = new Node(20);
(root->child).push_back(new Node(2));
(root->child).push_back(new Node(34));
(root->child).push_back(new Node(50));
(root->child).push_back(new Node(60));
(root->child).push_back(new Node(70));
(root->child[0]->child).push_back(new Node(15));
(root->child[0]->child).push_back(new Node(20));
(root->child[1]->child).push_back(new Node(30));
(root->child[2]->child).push_back(new Node(40));
(root->child[2]->child).push_back(new Node(100));
(root->child[2]->child).push_back(new Node(20));
(root->child[0]->child[1]->child).push_back(new Node(25));
(root->child[0]->child[1]->child).push_back(new Node(50));
// Node whose number of
// children is to be calculated
int x = 50;
// Function calling
cout << numberOfChildren(root, x) << endl;
return 0;
} | linear | linear |
// C++ program to find sum of all
// elements in generic tree
#include <bits/stdc++.h>
using namespace std;
// Represents a node of an n-ary tree
struct Node {
int key;
vector<Node*> child;
};
// Utility function to create a new tree node
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
return temp;
}
// Function to compute the sum
// of all elements in generic tree
int sumNodes(Node* root)
{
// initialize the sum variable
int sum = 0;
if (root == NULL)
return 0;
// Creating a queue and pushing the root
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
// If this node has children
while (n > 0) {
// Dequeue an item from queue and
// add it to variable "sum"
Node* p = q.front();
q.pop();
sum += p->key;
// Enqueue all children of the dequeued item
for (int i = 0; i < p->child.size(); i++)
q.push(p->child[i]);
n--;
}
}
return sum;
}
// Driver program
int main()
{
// Creating a generic tree
Node* root = newNode(20);
(root->child).push_back(newNode(2));
(root->child).push_back(newNode(34));
(root->child).push_back(newNode(50));
(root->child).push_back(newNode(60));
(root->child).push_back(newNode(70));
(root->child[0]->child).push_back(newNode(15));
(root->child[0]->child).push_back(newNode(20));
(root->child[1]->child).push_back(newNode(30));
(root->child[2]->child).push_back(newNode(40));
(root->child[2]->child).push_back(newNode(100));
(root->child[2]->child).push_back(newNode(20));
(root->child[0]->child[1]->child).push_back(newNode(25));
(root->child[0]->child[1]->child).push_back(newNode(50));
cout << sumNodes(root) << endl;
return 0;
} | linear | linear |
// C++ program to create a tree with left child
// right sibling representation.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
struct Node* child;
};
// Creating new Node
Node* newNode(int data)
{
Node* newNode = new Node;
newNode->next = newNode->child = NULL;
newNode->data = data;
return newNode;
}
// Adds a sibling to a list with starting with n
Node* addSibling(Node* n, int data)
{
if (n == NULL)
return NULL;
while (n->next)
n = n->next;
return (n->next = newNode(data));
}
// Add child Node to a Node
Node* addChild(Node* n, int data)
{
if (n == NULL)
return NULL;
// Check if child list is not empty.
if (n->child)
return addSibling(n->child, data);
else
return (n->child = newNode(data));
}
// Traverses tree in level order
void traverseTree(Node* root)
{
// Corner cases
if (root == NULL)
return;
cout << root->data << " ";
if (root->child == NULL)
return;
// Create a queue and enqueue root
queue<Node*> q;
Node* curr = root->child;
q.push(curr);
while (!q.empty()) {
// Take out an item from the queue
curr = q.front();
q.pop();
// Print next level of taken out item and enqueue
// next level's children
while (curr != NULL) {
cout << curr->data << " ";
if (curr->child != NULL) {
q.push(curr->child);
}
curr = curr->next;
}
}
}
// Driver code
int main()
{
Node* root = newNode(10);
Node* n1 = addChild(root, 2);
Node* n2 = addChild(root, 3);
Node* n3 = addChild(root, 4);
Node* n4 = addChild(n3, 6);
Node* n5 = addChild(root, 5);
Node* n6 = addChild(n5, 7);
Node* n7 = addChild(n5, 8);
Node* n8 = addChild(n5, 9);
traverseTree(root);
return 0;
} | linear | linear |
// C++ program to count number of nodes
// which has more children than its parent
#include<bits/stdc++.h>
using namespace std;
// function to count number of nodes
// which has more children than its parent
int countNodes(vector<int> adj[], int root)
{
int count = 0;
// queue for applying BFS
queue<int> q;
// BFS algorithm
q.push(root);
while (!q.empty())
{
int node = q.front();
q.pop();
// traverse children of node
for( int i=0;i<adj[node].size();i++)
{
// children of node
int children = adj[node][i];
// if number of childs of children
// is greater than number of childs
// of node, then increment count
if (adj[children].size() > adj[node].size())
count++;
q.push(children);
}
}
return count;
}
// Driver program to test above functions
int main()
{
// adjacency list for n-ary tree
vector<int> adj[10];
// construct n ary tree as shown
// in above diagram
adj[1].push_back(2);
adj[1].push_back(3);
adj[2].push_back(4);
adj[2].push_back(5);
adj[2].push_back(6);
adj[3].push_back(9);
adj[5].push_back(7);
adj[5].push_back(8);
int root = 1;
cout << countNodes(adj, root);
return 0;
} | linear | linear |
// C++ program to generate short url from integer id and
// integer id back from short url.
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
// Function to generate a short url from integer ID
string idToShortURL(long int n)
{
// Map to store 62 possible characters
char map[] = "abcdefghijklmnopqrstuvwxyzABCDEF"
"GHIJKLMNOPQRSTUVWXYZ0123456789";
string shorturl;
// Convert given integer id to a base 62 number
while (n)
{
// use above map to store actual character
// in short url
shorturl.push_back(map[n%62]);
n = n/62;
}
// Reverse shortURL to complete base conversion
reverse(shorturl.begin(), shorturl.end());
return shorturl;
}
// Function to get integer ID back from a short url
long int shortURLtoID(string shortURL)
{
long int id = 0; // initialize result
// A simple base conversion logic
for (int i=0; i < shortURL.length(); i++)
{
if ('a' <= shortURL[i] && shortURL[i] <= 'z')
id = id*62 + shortURL[i] - 'a';
if ('A' <= shortURL[i] && shortURL[i] <= 'Z')
id = id*62 + shortURL[i] - 'A' + 26;
if ('0' <= shortURL[i] && shortURL[i] <= '9')
id = id*62 + shortURL[i] - '0' + 52;
}
return id;
}
// Driver program to test above function
int main()
{
int n = 12345;
string shorturl = idToShortURL(n);
cout << "Generated short url is " << shorturl << endl;
cout << "Id from url is " << shortURLtoID(shorturl);
return 0;
} | constant | linear |
// A C++ program to implement Cartesian Tree sort
// Note that in this program we will build a min-heap
// Cartesian Tree and not max-heap.
#include<bits/stdc++.h>
using namespace std;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node
{
int data;
Node *left, *right;
};
// Creating a shortcut for int, Node* pair type
typedef pair<int, Node*> iNPair;
// This function sorts by pushing and popping the
// Cartesian Tree nodes in a pre-order like fashion
void pQBasedTraversal(Node* root)
{
// We will use a priority queue to sort the
// partially-sorted data efficiently.
// Unlike Heap, Cartesian tree makes use of
// the fact that the data is partially sorted
priority_queue <iNPair, vector<iNPair>, greater<iNPair>> pQueue;
pQueue.push (make_pair (root->data, root));
// Resembles a pre-order traverse as first data
// is printed then the left and then right child.
while (! pQueue.empty())
{
iNPair popped_pair = pQueue.top();
printf("%d ", popped_pair.first);
pQueue.pop();
if (popped_pair.second->left != NULL)
pQueue.push (make_pair(popped_pair.second->left->data,
popped_pair.second->left));
if (popped_pair.second->right != NULL)
pQueue.push (make_pair(popped_pair.second->right->data,
popped_pair.second->right));
}
return;
}
Node *buildCartesianTreeUtil(int root, int arr[],
int parent[], int leftchild[], int rightchild[])
{
if (root == -1)
return NULL;
Node *temp = new Node;
temp->data = arr[root];
temp->left = buildCartesianTreeUtil(leftchild[root],
arr, parent, leftchild, rightchild);
temp->right = buildCartesianTreeUtil(rightchild[root],
arr, parent, leftchild, rightchild);
return temp ;
}
// A function to create the Cartesian Tree in O(N) time
Node *buildCartesianTree(int arr[], int n)
{
// Arrays to hold the index of parent, left-child,
// right-child of each number in the input array
int parent[n], leftchild[n], rightchild[n];
// Initialize all array values as -1
memset(parent, -1, sizeof(parent));
memset(leftchild, -1, sizeof(leftchild));
memset(rightchild, -1, sizeof(rightchild));
// 'root' and 'last' stores the index of the root and the
// last processed of the Cartesian Tree.
// Initially we take root of the Cartesian Tree as the
// first element of the input array. This can change
// according to the algorithm
int root = 0, last;
// Starting from the second element of the input array
// to the last on scan across the elements, adding them
// one at a time.
for (int i = 1; i <= n - 1; i++)
{
last = i-1;
rightchild[i] = -1;
// Scan upward from the node's parent up to
// the root of the tree until a node is found
// whose value is smaller than the current one
// This is the same as Step 2 mentioned in the
// algorithm
while (arr[last] >= arr[i] && last != root)
last = parent[last];
// arr[i] is the smallest element yet; make it
// new root
if (arr[last] >= arr[i])
{
parent[root] = i;
leftchild[i] = root;
root = i;
}
// Just insert it
else if (rightchild[last] == -1)
{
rightchild[last] = i;
parent[i] = last;
leftchild[i] = -1;
}
// Reconfigure links
else
{
parent[rightchild[last]] = i;
leftchild[i] = rightchild[last];
rightchild[last]= i;
parent[i] = last;
}
}
// Since the root of the Cartesian Tree has no
// parent, so we assign it -1
parent[root] = -1;
return (buildCartesianTreeUtil (root, arr, parent,
leftchild, rightchild));
}
// Sorts an input array
int printSortedArr(int arr[], int n)
{
// Build a cartesian tree
Node *root = buildCartesianTree(arr, n);
printf("The sorted array is-\n");
// Do pr-order traversal and insert
// in priority queue
pQBasedTraversal(root);
}
/* Driver program to test above functions */
int main()
{
/* Given input array- {5,10,40,30,28},
it's corresponding unique Cartesian Tree
is-
5
\
10
\
28
/
30
/
40
*/
int arr[] = {5, 10, 40, 30, 28};
int n = sizeof(arr)/sizeof(arr[0]);
printSortedArr(arr, n);
return(0);
} | linear | nlogn |
// C++ Program to search an element
// in a sorted and pivoted array
#include <bits/stdc++.h>
using namespace std;
// Standard Binary Search function
int binarySearch(int arr[], int low, int high, int key)
{
if (high < low)
return -1;
int mid = (low + high) / 2;
if (key == arr[mid])
return mid;
if (key > arr[mid])
return binarySearch(arr, (mid + 1), high, key);
return binarySearch(arr, low, (mid - 1), key);
}
// Function to get pivot. For array 3, 4, 5, 6, 1, 2
// it returns 3 (index of 6)
int findPivot(int arr[], int low, int high)
{
// Base cases
if (high < low)
return -1;
if (high == low)
return low;
// low + (high - low)/2;
int mid = (low + high) / 2;
if (mid < high && arr[mid] > arr[mid + 1])
return mid;
if (mid > low && arr[mid] < arr[mid - 1])
return (mid - 1);
if (arr[low] >= arr[mid])
return findPivot(arr, low, mid - 1);
return findPivot(arr, mid + 1, high);
}
// Searches an element key in a pivoted
// sorted array arr[] of size n
int pivotedBinarySearch(int arr[], int n, int key)
{
int pivot = findPivot(arr, 0, n - 1);
// If we didn't find a pivot,
// then array is not rotated at all
if (pivot == -1)
return binarySearch(arr, 0, n - 1, key);
// If we found a pivot, then first compare with pivot
// and then search in two subarrays around pivot
if (arr[pivot] == key)
return pivot;
if (arr[0] <= key)
return binarySearch(arr, 0, pivot - 1, key);
return binarySearch(arr, pivot + 1, n - 1, key);
}
// Driver program to check above functions
int main()
{
// Let us search 3 in below array
int arr1[] = { 5, 6, 7, 8, 9, 10, 1, 2, 3 };
int n = sizeof(arr1) / sizeof(arr1[0]);
int key = 3;
// Function calling
cout << "Index of the element is : "
<< pivotedBinarySearch(arr1, n, key);
return 0;
} | constant | logn |
// Search an element in sorted and rotated
// array using single pass of Binary Search
#include <bits/stdc++.h>
using namespace std;
// Returns index of key in arr[l..h] if
// key is present, otherwise returns -1
int search(int arr[], int l, int h, int key)
{
if (l > h)
return -1;
int mid = (l + h) / 2;
if (arr[mid] == key)
return mid;
/* If arr[l...mid] is sorted */
if (arr[l] <= arr[mid]) {
/* As this subarray is sorted, we can quickly
check if key lies in half or other half */
if (key >= arr[l] && key <= arr[mid])
return search(arr, l, mid - 1, key);
/*If key not lies in first half subarray,
Divide other half into two subarrays,
such that we can quickly check if key lies
in other half */
return search(arr, mid + 1, h, key);
}
/* If arr[l..mid] first subarray is not sorted, then
arr[mid... h] must be sorted subarray */
if (key >= arr[mid] && key <= arr[h])
return search(arr, mid + 1, h, key);
return search(arr, l, mid - 1, key);
}
// Driver program
int main()
{
int arr[] = { 4, 5, 6, 7, 8, 9, 1, 2, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
int key = 3;
int i = search(arr, 0, n - 1, key);
if (i != -1)
cout << "Index: " << i << endl;
else
cout << "Key not found";
}
// This code is contributed by Aditya Kumar (adityakumar129) | constant | logn |
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// This function returns true if arr[0..n-1]
// has a pair with sum equals to x.
bool pairInSortedRotated(int arr[], int n, int x)
{
// Find the pivot element
int i;
for (i = 0; i < n - 1; i++)
if (arr[i] > arr[i + 1])
break;
// l is now index of smallest element
int l = (i + 1) % n;
// r is now index of largest element
int r = i;
// Keep moving either l or r till they meet
while (l != r) {
// If we find a pair with sum x,
// we return true
if (arr[l] + arr[r] == x)
return true;
// If current pair sum is less,
// move to the higher sum
if (arr[l] + arr[r] < x)
l = (l + 1) % n;
// Move to the lower sum side
else
r = (n + r - 1) % n;
}
return false;
}
// Driver code
int main()
{
int arr[] = { 11, 15, 6, 8, 9, 10 };
int X = 16;
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
if (pairInSortedRotated(arr, N, X))
cout << "true";
else
cout << "false";
return 0;
} | constant | linear |
// C++ program to find max value of i*arr[i]
#include <iostream>
using namespace std;
// Returns max possible value of i*arr[i]
int maxSum(int arr[], int n)
{
// Find array sum and i*arr[i] with no rotation
int arrSum = 0; // Stores sum of arr[i]
int currVal = 0; // Stores sum of i*arr[i]
for (int i = 0; i < n; i++) {
arrSum = arrSum + arr[i];
currVal = currVal + (i * arr[i]);
}
// Initialize result as 0 rotation sum
int maxVal = currVal;
// Try all rotations one by one and find
// the maximum rotation sum.
for (int j = 1; j < n; j++) {
currVal = currVal + arrSum - n * arr[n - j];
if (currVal > maxVal)
maxVal = currVal;
}
// Return result
return maxVal;
}
// Driver program
int main(void)
{
int arr[] = { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "\nMax sum is " << maxSum(arr, n);
return 0;
} | constant | linear |
// A Naive C++ program to find maximum sum rotation
#include<bits/stdc++.h>
using namespace std;
// Returns maximum value of i*arr[i]
int maxSum(int arr[], int n)
{
// Initialize result
int res = INT_MIN;
// Consider rotation beginning with i
// for all possible values of i.
for (int i=0; i<n; i++)
{
// Initialize sum of current rotation
int curr_sum = 0;
// Compute sum of all values. We don't
// actually rotate the array, instead of that we compute the
// sum by finding indexes when arr[i] is
// first element
for (int j=0; j<n; j++)
{
int index = (i+j)%n;
curr_sum += j*arr[index];
}
// Update result if required
res = max(res, curr_sum);
}
return res;
}
// Driver code
int main()
{
int arr[] = {8, 3, 1, 2};
int n = sizeof(arr)/sizeof(arr[0]);
cout << maxSum(arr, n) << endl;
return 0;
} | constant | quadratic |
// An efficient C++ program to compute
// maximum sum of i*arr[i]
#include<bits/stdc++.h>
using namespace std;
int maxSum(int arr[], int n)
{
// Compute sum of all array elements
int cum_sum = 0;
for (int i=0; i<n; i++)
cum_sum += arr[i];
// Compute sum of i*arr[i] for initial
// configuration.
int curr_val = 0;
for (int i=0; i<n; i++)
curr_val += i*arr[i];
// Initialize result
int res = curr_val;
// Compute values for other iterations
for (int i=1; i<n; i++)
{
// Compute next value using previous
// value in O(1) time
int next_val = curr_val - (cum_sum - arr[i-1])
+ arr[i-1] * (n-1);
// Update current value
curr_val = next_val;
// Update result if required
res = max(res, next_val);
}
return res;
}
// Driver code
int main()
{
int arr[] = {8, 3, 1, 2};
int n = sizeof(arr)/sizeof(arr[0]);
cout << maxSum(arr, n) << endl;
return 0;
} | constant | linear |
// C++ program to find maximum sum of all
// rotation of i*arr[i] using pivot.
#include <iostream>
using namespace std;
// fun declaration
int maxSum(int arr[], int n);
int findPivot(int arr[], int n);
// function definition
int maxSum(int arr[], int n)
{
int sum = 0;
int i;
int pivot = findPivot(arr, n);
// difference in pivot and index of
// last element of array
int diff = n - 1 - pivot;
for(i = 0; i < n; i++)
{
sum = sum + ((i + diff) % n) * arr[i];
}
return sum;
}
// function to find pivot
int findPivot(int arr[], int n)
{
int i;
for(i = 0; i < n; i++)
{
if(arr[i] > arr[(i + 1) % n])
return i;
}
}
// Driver code
int main(void)
{
// rotated input array
int arr[] = {8, 13, 1, 2};
int n = sizeof(arr) / sizeof(int);
int max = maxSum(arr, n);
cout << max;
return 0;
}
// This code is contributed by Shubhamsingh10 | constant | linear |
// C++ program for the above approach
#include <iostream>
using namespace std;
int* rotateArray(int A[], int start, int end)
{
while (start < end) {
int temp = A[start];
A[start] = A[end];
A[end] = temp;
start++;
end--;
}
return A;
}
void leftRotate(int A[], int a, int k)
{
// if the value of k ever exceeds the length of the
// array
int c = k % a;
// initializing array D so that we always
// have a clone of the original array to rotate
int D[a];
for (int i = 0; i < a; i++)
D[i] = A[i];
rotateArray(D, 0, c - 1);
rotateArray(D, c, a - 1);
rotateArray(D, 0, a - 1);
// printing the rotated array
for (int i = 0; i < a; i++)
cout << D[i] << " ";
cout << "\n";
}
int main()
{
int A[] = { 1, 3, 5, 7, 9 };
int n = sizeof(A) / sizeof(A[0]);
int k = 2;
leftRotate(A, n, k);
k = 3;
leftRotate(A, n, k);
k = 4;
leftRotate(A, n, k);
return 0;
}
// this code is contributed by aditya942003patil | linear | linear |
// CPP implementation of left rotation of
// an array K number of times
#include <bits/stdc++.h>
using namespace std;
// Fills temp[] with two copies of arr[]
void preprocess(int arr[], int n, int temp[])
{
// Store arr[] elements at i and i + n
for (int i = 0; i < n; i++)
temp[i] = temp[i + n] = arr[i];
}
// Function to left rotate an array k times
void leftRotate(int arr[], int n, int k, int temp[])
{
// Starting position of array after k
// rotations in temp[] will be k % n
int start = k % n;
// Print array after k rotations
for (int i = start; i < start + n; i++)
cout << temp[i] << " ";
cout << endl;
}
// Driver program
int main()
{
int arr[] = { 1, 3, 5, 7, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
int temp[2 * n];
preprocess(arr, n, temp);
int k = 2;
leftRotate(arr, n, k, temp);
k = 3;
leftRotate(arr, n, k, temp);
k = 4;
leftRotate(arr, n, k, temp);
return 0;
} | linear | linear |
// CPP implementation of left rotation of
// an array K number of times
#include <bits/stdc++.h>
using namespace std;
// Function to left rotate an array k times
void leftRotate(int arr[], int n, int k)
{
// Print array after k rotations
for (int i = k; i < k + n; i++)
cout << arr[i % n] << " ";
}
// Driver program
int main()
{
int arr[] = { 1, 3, 5, 7, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;
leftRotate(arr, n, k);
cout << endl;
k = 3;
leftRotate(arr, n, k);
cout << endl;
k = 4;
leftRotate(arr, n, k);
cout << endl;
return 0;
} | constant | linear |
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the minimum value
int findMin(int arr[], int n)
{
int min_ele = arr[0];
// Traversing over array to
// find minimum element
for (int i = 0; i < n; i++) {
if (arr[i] < min_ele) {
min_ele = arr[i];
}
}
return min_ele;
}
// Driver code
int main()
{
int arr[] = { 5, 6, 1, 2, 3, 4 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
cout << findMin(arr, N) << endl;
return 0;
} | constant | linear |
// C++ program to find minimum
// element in a sorted and rotated array
#include <bits/stdc++.h>
using namespace std;
int findMin(int arr[], int low, int high)
{
// This condition is needed to
// handle the case when array is not
// rotated at all
if (high < low)
return arr[0];
// If there is only one element left
if (high == low)
return arr[low];
// Find mid
int mid = low + (high - low) / 2; /*(low + high)/2;*/
// Check if element (mid+1) is minimum element. Consider
// the cases like {3, 4, 5, 1, 2}
if (mid < high && arr[mid + 1] < arr[mid])
return arr[mid + 1];
// Check if mid itself is minimum element
if (mid > low && arr[mid] < arr[mid - 1])
return arr[mid];
// Decide whether we need to go to left half or right
// half
if (arr[high] > arr[mid])
return findMin(arr, low, mid - 1);
return findMin(arr, mid + 1, high);
}
// Driver program to test above functions
int main()
{
int arr[] = { 5, 6, 1, 2, 3, 4 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
cout << "The minimum element is "
<< findMin(arr, 0, N - 1) << endl;
return 0;
}
// This is code is contributed by rathbhupendra | constant | logn |
// C++ program for right rotation of
// an array (Reversal Algorithm)
#include <bits/stdc++.h>
/*Function to reverse arr[]
from index start to end*/
void reverseArray(int arr[], int start,
int end)
{
while (start < end)
{
std::swap(arr[start], arr[end]);
start++;
end--;
}
}
/* Function to right rotate arr[]
of size n by d */
void rightRotate(int arr[], int d, int n)
{
// if in case d>n,this will give segmentation fault.
d=d%n;
reverseArray(arr, 0, n-1);
reverseArray(arr, 0, d-1);
reverseArray(arr, d, n-1);
}
/* function to print an array */
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
std::cout << arr[i] << " ";
}
// driver code
int main()
{
int arr[] = {1, 2, 3, 4, 5,
6, 7, 8, 9, 10};
int n = sizeof(arr)/sizeof(arr[0]);
int k = 3;
rightRotate(arr, k, n);
printArray(arr, n);
return 0;
} | constant | linear |
// C++ Program to solve queries on Left and Right
// Circular shift on array
#include <bits/stdc++.h>
using namespace std;
// Function to solve query of type 1 x.
void querytype1(int* toRotate, int times, int n)
{
// Decreasing the absolute rotation
(*toRotate) = ((*toRotate) - times) % n;
}
// Function to solve query of type 2 y.
void querytype2(int* toRotate, int times, int n)
{
// Increasing the absolute rotation.
(*toRotate) = ((*toRotate) + times) % n;
}
// Function to solve queries of type 3 l r.
void querytype3(int toRotate, int l, int r, int preSum[],
int n)
{
// Finding absolute l and r.
l = (l + toRotate + n) % n;
r = (r + toRotate + n) % n;
// if l is before r.
if (l <= r)
cout << (preSum[r + 1] - preSum[l]) << endl;
// If r is before l.
else
cout << (preSum[n] + preSum[r + 1] - preSum[l])
<< endl;
}
// Wrapper Function solve all queries.
void wrapper(int a[], int n)
{
int preSum[n + 1];
preSum[0] = 0;
// Finding Prefix sum
for (int i = 1; i <= n; i++)
preSum[i] = preSum[i - 1] + a[i - 1];
int toRotate = 0;
// Solving each query
querytype1(&toRotate, 3, n);
querytype3(toRotate, 0, 2, preSum, n);
querytype2(&toRotate, 1, n);
querytype3(toRotate, 1, 4, preSum, n);
}
// Driver Program
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int N = sizeof(arr) / sizeof(arr[0]);
wrapper(arr, N);
return 0;
} | linear | linear |
// C++ implementation of left rotation of
// an array K number of times
#include <bits/stdc++.h>
using namespace std;
// Function to leftRotate array multiple times
void leftRotate(int arr[], int n, int k)
{
/* To get the starting point of rotated array */
int mod = k % n;
// Prints the rotated array from start position
for (int i = 0; i < n; i++)
cout << (arr[(mod + i) % n]) << " ";
cout << "\n";
}
// Driver Code
int main()
{
int arr[] = { 1, 3, 5, 7, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;
// Function Call
leftRotate(arr, n, k);
k = 3;
// Function Call
leftRotate(arr, n, k);
k = 4;
// Function Call
leftRotate(arr, n, k);
return 0;
} | constant | linear |
#include <bits/stdc++.h>
using namespace std;
int findElement(vector<int> arr, int ranges[][2],
int rotations, int index)
{
// Track of the rotation number
int n1 = 1;
// Track of the row index for the ranges[][] array
int i = 0;
// Initialize the left side of the ranges[][] array
int leftRange = 0;
// Initialize the right side of the ranges[][] array
int rightRange = 0;
// Initialize the key variable
int key = 0;
while (n1 <= rotations) {
leftRange = ranges[i][0];
rightRange = ranges[i][1];
key = arr[rightRange];
for (int j = rightRange; j >= leftRange + 1; j--) {
arr[j] = arr[j - 1];
}
arr[leftRange] = key;
n1++;
i++;
}
// Return the element after all the rotations
return arr[index];
}
int main()
{
vector<int> arr{ 1, 2, 3, 4, 5 };
// No. of rotations
int rotations = 2;
// Ranges according to 0-based indexing
int ranges[][2] = { { 0, 2 }, { 0, 3 } };
int index = 1;
cout << (findElement(arr, ranges, rotations, index));
}
// This code is contributed by garg28harsh. | constant | quadratic |
// CPP code to rotate an array
// and answer the index query
#include <bits/stdc++.h>
using namespace std;
// Function to compute the element at
// given index
int findElement(int arr[], int ranges[][2], int rotations,
int index)
{
for (int i = rotations - 1; i >= 0; i--) {
// Range[left...right]
int left = ranges[i][0];
int right = ranges[i][1];
// Rotation will not have any effect
if (left <= index && right >= index) {
if (index == left)
index = right;
else
index--;
}
}
// Returning new element
return arr[index];
}
// Driver
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
// No. of rotations
int rotations = 2;
// Ranges according to 0-based indexing
int ranges[rotations][2] = { { 0, 2 }, { 0, 3 } };
int index = 1;
cout << findElement(arr, ranges, rotations, index);
return 0;
} | constant | constant |
// CPP program to split array and move first
// part to end.
#include <iostream>
using namespace std;
void splitArr(int arr[], int n, int k)
{
for (int i = 0; i < k; i++) {
// Rotate array by 1.
int x = arr[0];
for (int j = 0; j < n - 1; ++j)
arr[j] = arr[j + 1];
arr[n - 1] = x;
}
}
// Driver code
int main()
{
int arr[] = { 12, 10, 5, 6, 52, 36 };
int n = sizeof(arr) / sizeof(arr[0]);
int position = 2;
splitArr(arr, n, position);
for (int i = 0; i < n; ++i)
cout <<" "<< arr[i];
return 0;
}
// This code is contributed by shivanisinghss2110 | constant | quadratic |
// CPP program to split array and move first
// part to end.
#include <bits/stdc++.h>
using namespace std;
// Function to split array and
// move first part to end
void splitArr(int arr[], int length, int rotation)
{
int tmp[length * 2] = {0};
for(int i = 0; i < length; i++)
{
tmp[i] = arr[i];
tmp[i + length] = arr[i];
}
for(int i = rotation; i < rotation + length; i++)
{
arr[i - rotation] = tmp[i];
}
}
// Driver code
int main()
{
int arr[] = { 12, 10, 5, 6, 52, 36 };
int n = sizeof(arr) / sizeof(arr[0]);
int position = 2;
splitArr(arr, n, position);
for (int i = 0; i < n; ++i)
printf("%d ", arr[i]);
return 0;
}
// This code is contributed by YashKhandelwal8 | linear | linear |
// C++ program for above approach
#include <iostream>
using namespace std;
// Function to transform the array
void fixArray(int ar[], int n)
{
int i, j, temp;
// Iterate over the array
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
// Check is any ar[j]
// exists such that
// ar[j] is equal to i
if (ar[j] == i) {
temp = ar[j];
ar[j] = ar[i];
ar[i] = temp;
break;
}
}
}
// Iterate over array
for (i = 0; i < n; i++)
{
// If not present
if (ar[i] != i)
{
ar[i] = -1;
}
}
// Print the output
cout << "Array after Rearranging" << endl;
for (i = 0; i < n; i++) {
cout << ar[i] << " ";
}
}
// Driver Code
int main()
{
int n, ar[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
n = sizeof(ar) / sizeof(ar[0]);
// Function Call
fixArray(ar, n);
}
// Code BY Tanmay Anand | constant | quadratic |
// C++ program for rearrange an
// array such that arr[i] = i.
#include <bits/stdc++.h>
using namespace std;
// Function to rearrange an array
// such that arr[i] = i.
void fixArray(int A[], int len)
{
for (int i = 0; i < len; i++)
{
if (A[i] != -1 && A[i] != i)
{
int x = A[i];
// check if desired place
// is not vacate
while (A[x] != -1 && A[x] != x)
{
// store the value from
// desired place
int y = A[x];
// place the x to its correct
// position
A[x] = x;
// now y will become x, now
// search the place for x
x = y;
}
// place the x to its correct
// position
A[x] = x;
// check if while loop hasn't
// set the correct value at A[i]
if (A[i] != i)
{
// if not then put -1 at
// the vacated place
A[i] = -1;
}
}
}
}
// Driver code
int main()
{
int A[] = { -1, -1, 6, 1, 9,
3, 2, -1, 4, -1 };
int len = sizeof(A) / sizeof(A[0]);
// Function Call
fixArray(A, len);
// Print the output
for (int i = 0; i < len; i++)
cout << A[i] << " ";
}
// This code is contributed by Smitha Dinesh Semwal | constant | linear |
#include <iostream>
#include <unordered_set>
using namespace std;
void fixArray(int arr[], int n)
{
// a set
unordered_set<int> s;
// Enter each element which is not -1 in set
for(int i=0; i<n; i++)
{
if(arr[i] != -1)
s.insert(arr[i]);
}
// Navigate through array,
// and put A[i] = i,
// if i is present in set
for(int i=0; i<n; i++)
{
// if i(index) is found in hmap
if(s.find(i) != s.end())
{
arr[i] = i;
}
// if i not found
else
{
arr[i] = -1;
}
}
}
// Driver Code
int main() {
// Array initialization
int arr[] {-1, -1, 6, 1, 9,
3, 2, -1, 4,-1};
int n = sizeof(arr) / sizeof(arr[0]);
// Function Call
fixArray(arr, n);
// Print output
for(int i=0; i<n; i++)
cout << arr[i] << ' ';
return 0;
}
// this code is contributed by dev chaudhary | linear | linear |
// C++ program for rearrange an
// array such that arr[i] = i.
#include <iostream>
using namespace std;
void fixArray(int arr[], int n)
{
int i = 0;
while (i < n) {
int correct = arr[i];
if (arr[i] != -1 && arr[i] != arr[correct]) {
// if array element should be lesser than
// size and array element should not be at
// its correct position then only swap with
// its correct position or index value
swap(arr[i], arr[correct]);
}
else {
// if element is at its correct position
// just increment i and check for remaining
// array elements
i++;
}
}
return arr;
}
// Driver Code
int main()
{
int arr[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function Call
fixArray(arr, n);
// Print output
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
// This Code is Contributed by kothavvsaakash | constant | linear |
// C++ program to rearrange the array as per the given
// condition
#include <bits/stdc++.h>
using namespace std;
// function to rearrange the array
void rearrangeArr(int arr[], int n)
{
// total even positions
int evenPos = n / 2;
// total odd positions
int oddPos = n - evenPos;
int tempArr[n];
// copy original array in an auxiliary array
for (int i = 0; i < n; i++)
tempArr[i] = arr[i];
// sort the auxiliary array
sort(tempArr, tempArr + n);
int j = oddPos - 1;
// fill up odd position in original array
for (int i = 0; i < n; i += 2)
arr[i] = tempArr[j--];
j = oddPos;
// fill up even positions in original array
for (int i = 1; i < n; i += 2)
arr[i] = tempArr[j++];
// display array
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
int size = sizeof(arr) / sizeof(arr[0]);
rearrangeArr(arr, size);
return 0;
} | linear | nlogn |
#include <bits/stdc++.h>
using namespace std;
int main(){
int n,i,p,q;
int a[]= {1, 2, 1, 4, 5, 6, 8, 8};
n=sizeof(a)/sizeof(a[0]);
int b[n];
for(i=0;i<n;i++)
b[i]=a[i];
sort(b,b+n);
p=0;q=n-1;
for(i=n-1;i>=0;i--){
if(i%2!=0){
a[i]=b[q];
q--;
}
else{
a[i]=b[p];
p++;
}
}
for(i=0;i<n;i++){
cout<<a[i]<<" ";
}
return 0;
} | linear | nlogn |
/* C++ program to rearrange
positive and negative integers
in alternate fashion while keeping
the order of positive and negative numbers. */
#include <assert.h>
#include <iostream>
using namespace std;
// Utility function to right rotate all elements between
// [outofplace, cur]
void rightrotate(int arr[], int n, int outofplace, int cur)
{
char tmp = arr[cur];
for (int i = cur; i > outofplace; i--)
arr[i] = arr[i - 1];
arr[outofplace] = tmp;
}
void rearrange(int arr[], int n)
{
int outofplace = -1;
for (int index = 0; index < n; index++) {
if (outofplace >= 0) {
// find the item which must be moved into the
// out-of-place entry if out-of-place entry is
// positive and current entry is negative OR if
// out-of-place entry is negative and current
// entry is negative then right rotate
//
// [...-3, -4, -5, 6...] --> [...6, -3, -4,
// -5...]
// ^ ^
// | |
// outofplace --> outofplace
//
if (((arr[index] >= 0) && (arr[outofplace] < 0))
|| ((arr[index] < 0)
&& (arr[outofplace] >= 0))) {
rightrotate(arr, n, outofplace, index);
// the new out-of-place entry is now 2 steps
// ahead
if (index - outofplace >= 2)
outofplace = outofplace + 2;
else
outofplace = -1;
}
}
// if no entry has been flagged out-of-place
if (outofplace == -1) {
// check if current entry is out-of-place
if (((arr[index] >= 0) && (!(index & 0x01)))
|| ((arr[index] < 0) && (index & 0x01))) {
outofplace = index;
}
}
}
}
// A utility function to print an array 'arr[]' of size 'n'
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver code
int main()
{
int arr[] = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Given array is \n";
printArray(arr, n);
rearrange(arr, n);
cout << "Rearranged array is \n";
printArray(arr, n);
return 0;
} | constant | quadratic |
// C++ Program to move all zeros to the end
#include <bits/stdc++.h>
using namespace std;
int main()
{
int A[] = { 5, 6, 0, 4, 6, 0, 9, 0, 8 };
int n = sizeof(A) / sizeof(A[0]);
int j = 0;
for (int i = 0; i < n; i++) {
if (A[i] != 0) {
swap(A[j], A[i]); // Partitioning the array
j++;
}
}
for (int i = 0; i < n; i++) {
cout << A[i] << " "; // Print the array
}
return 0;
} | constant | linear |
# C++ program to shift all zeros
# to right most side of array
# without affecting order of non-zero
# elements
# Given list
arr = [5, 6, 0, 4, 6, 0, 9, 0, 8]
# Storing all non zero values
nonZeroValues = [x for x in arr if x != 0]
# Storing all zeroes
zeroes = [j for j in arr if j == 0]
# Updating the answer
arr = nonZeroValues + zeroes
# Printing the answer
print( "array after shifting zeros to right side: " + arr) | constant | linear |
// C++ implementation to move all zeroes at the end of array
#include <iostream>
using namespace std;
// function to move all zeroes at the end of array
void moveZerosToEnd(int arr[], int n)
{
// Count of non-zero elements
int count = 0;
// Traverse the array. If arr[i] is non-zero, then
// update the value of arr at index count to arr[i]
for (int i = 0; i < n; i++)
if (arr[i] != 0)
arr[count++] = arr[i];
// Update all elements at index >=count with value 0
for (int i = count; i < n; i++)
arr[i] = 0;
}
// function to print the array elements
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
// Driver program to test above
int main()
{
int arr[] = { 0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
printArray(arr, n);
moveZerosToEnd(arr, n);
cout << "\nModified array: ";
printArray(arr, n);
return 0;
} | constant | linear |
// C++ program to find minimum swaps required
// to club all elements less than or equals
// to k together
#include <iostream>
using namespace std;
// Utility function to find minimum swaps
// required to club all elements less than
// or equals to k together
int minSwap(int *arr, int n, int k) {
// Find count of elements which are
// less than equals to k
int count = 0;
for (int i = 0; i < n; ++i)
if (arr[i] <= k)
++count;
// Find unwanted elements in current
// window of size 'count'
int bad = 0;
for (int i = 0; i < count; ++i)
if (arr[i] > k)
++bad;
// Initialize answer with 'bad' value of
// current window
int ans = bad;
for (int i = 0, j = count; j < n; ++i, ++j) {
// Decrement count of previous window
if (arr[i] > k)
--bad;
// Increment count of current window
if (arr[j] > k)
++bad;
// Update ans if count of 'bad'
// is less in current window
ans = min(ans, bad);
}
return ans;
}
// Driver code
int main() {
int arr[] = {2, 1, 5, 6, 3};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
cout << minSwap(arr, n, k) << "\n";
int arr1[] = {2, 7, 9, 5, 8, 7, 4};
n = sizeof(arr1) / sizeof(arr1[0]);
k = 5;
cout << minSwap(arr1, n, k);
return 0;
} | constant | linear |
#include <bits/stdc++.h>
using namespace std;
// Function for finding the minimum number of swaps
// required to bring all the numbers less
// than or equal to k together.
int minSwap(int arr[], int n, int k)
{
// Initially snowBallsize is 0
int snowBallSize = 0;
for (int i = 0; i < n; i++) {
// Calculating the size of window required
if (arr[i] <= k) {
snowBallSize++;
}
}
int swap = 0, ans_swaps = INT_MAX;
for (int i = 0; i < snowBallSize; i++) {
if (arr[i] > k)
swap++;
}
ans_swaps = min(ans_swaps, swap);
for (int i = snowBallSize; i < n; i++) {
// Checking in every window no. of swaps required
// and storing its minimum
if (arr[i - snowBallSize] <= k && arr[i] > k)
swap++;
else if (arr[i - snowBallSize] > k && arr[i] <= k)
swap--;
ans_swaps = min(ans_swaps, swap);
}
return ans_swaps;
}
// Driver's code
int main()
{
int arr1[] = { 2, 7, 9, 5, 8, 7, 4 };
int n = sizeof(arr1) / sizeof(arr1[0]);
int k = 5;
cout << minSwap(arr1, n, k) << "\n";
return 0;
}
// This code is contributed by aditya942003patil | constant | linear |
// C++ implementation of
// the above approach
#include <iostream>
void printArray(int array[], int length)
{
std::cout << "[";
for(int i = 0; i < length; i++)
{
std::cout << array[i];
if(i < (length - 1))
std::cout << ", ";
else
std::cout << "]" << std::endl;
}
}
void reverse(int array[], int start, int end)
{
while(start < end)
{
int temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
// Rearrange the array with all negative integers
// on left and positive integers on right
// use recursion to split the array with first element
// as one half and the rest array as another and then
// merge it with head of the array in each step
void rearrange(int array[], int start, int end)
{
// exit condition
if(start == end)
return;
// rearrange the array except the first
// element in each recursive call
rearrange(array, (start + 1), end);
// If the first element of the array is positive,
// then right-rotate the array by one place first
// and then reverse the merged array.
if(array[start] >= 0)
{
reverse(array, (start + 1), end);
reverse(array, start, end);
}
}
// Driver code
int main()
{
int array[] = {-12, -11, -13, -5, -6, 7, 5, 3, 6};
int length = (sizeof(array) / sizeof(array[0]));
int countNegative = 0;
for(int i = 0; i < length; i++)
{
if(array[i] < 0)
countNegative++;
}
std::cout << "array: ";
printArray(array, length);
rearrange(array, 0, (length - 1));
reverse(array, countNegative, (length - 1));
std::cout << "rearranged array: ";
printArray(array, length);
return 0;
} | quadratic | quadratic |
// C++ program to print the array in given order
#include <bits/stdc++.h>
using namespace std;
// Function which arrange the array.
void rearrangeArray(int arr[], int n)
{
// Sorting the array elements
sort(arr, arr + n);
int tempArr[n]; // To store modified array
// Adding numbers from sorted array to
// new array accordingly
int ArrIndex = 0;
// Traverse from begin and end simultaneously
for (int i = 0, j = n - 1; i <= n / 2 || j > n / 2;
i++, j--) {
tempArr[ArrIndex] = arr[i];
ArrIndex++;
tempArr[ArrIndex] = arr[j];
ArrIndex++;
}
// Modifying original array
for (int i = 0; i < n; i++)
arr[i] = tempArr[i];
}
// Driver Code
int main()
{
int arr[] = { 5, 8, 1, 4, 2, 9, 3, 7, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
rearrangeArray(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
} | linear | nlogn |
// C++ implementation to rearrange the array elements after
// modification
#include <bits/stdc++.h>
using namespace std;
// function which pushes all zeros to end of an array.
void pushZerosToEnd(int arr[], int n)
{
// Count of non-zero elements
int count = 0;
// Traverse the array. If element encountered is
// non-zero, then replace the element at index 'count'
// with this element
for (int i = 0; i < n; i++)
if (arr[i] != 0)
// here count is incremented
arr[count++] = arr[i];
// Now all non-zero elements have been shifted to front
// and 'count' is set as index of first 0. Make all
// elements 0 from count to end.
while (count < n)
arr[count++] = 0;
}
// function to rearrange the array elements after
// modification
void modifyAndRearrangeArr(int arr[], int n)
{
// if 'arr[]' contains a single element only
if (n == 1)
return;
// traverse the array
for (int i = 0; i < n - 1; i++) {
// if true, perform the required modification
if ((arr[i] != 0) && (arr[i] == arr[i + 1])) {
// double current index value
arr[i] = 2 * arr[i];
// put 0 in the next index
arr[i + 1] = 0;
// increment by 1 so as to move two indexes
// ahead during loop iteration
i++;
}
}
// push all the zeros at the end of 'arr[]'
pushZerosToEnd(arr, n);
}
// function to print the array elements
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
// Driver program to test above
int main()
{
int arr[] = { 0, 2, 2, 2, 0, 6, 6, 0, 0, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
printArray(arr, n);
modifyAndRearrangeArr(arr, n);
cout << "\nModified array: ";
printArray(arr, n);
return 0;
} | constant | linear |
// C++ program to Rearrange positive and negative
// numbers in a array
#include <bits/stdc++.h>
using namespace std;
// A utility function to print an array of size n
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout<<arr[i]<<" ";
}
void rotateSubArray(int arr[], int l, int r) {
int temp = arr[r];
for (int j = r; j > l - 1; j--) {
arr[j] = arr[j - 1];
}
arr[l] = temp;
}
void moveNegative(int arr[], int n)
{
int last_negative_index = -1;
for (int i = 0; i < n; i++) {
if (arr[i] < 0) {
last_negative_index += 1;
int temp = arr[i];
arr[i] = arr[last_negative_index];
arr[last_negative_index] = temp;
// Done to manage order too
if (i - last_negative_index >= 2)
rotateSubArray(arr, last_negative_index + 1, i);
}
}
}
// Driver Code
int main()
{
int arr[] = { 5, 5, -3, 4, -8, 0, -7, 3, -9, -3, 9, -2, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
moveNegative(arr, n);
printArray(arr, n);
return 0;
}
// This code is contributed by Aarti_Rathi | constant | quadratic |
// C++ program to Rearrange positive and negative
// numbers in a array
#include <stdio.h>
// A utility function to print an array of size n
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Function to Rearrange positive and negative
// numbers in a array
void RearrangePosNeg(int arr[], int n)
{
int key, j;
for (int i = 1; i < n; i++) {
key = arr[i];
// if current element is positive
// do nothing
if (key > 0)
continue;
/* if current element is negative,
shift positive elements of arr[0..i-1],
to one position to their right */
j = i - 1;
while (j >= 0 && arr[j] > 0) {
arr[j + 1] = arr[j];
j = j - 1;
}
// Put negative element at its right position
arr[j + 1] = key;
}
}
/* Driver program to test above functions */
int main()
{
int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };
int n = sizeof(arr) / sizeof(arr[0]);
RearrangePosNeg(arr, n);
printArray(arr, n);
return 0;
} | constant | quadratic |
// C++ program to Rearrange positive and negative
// numbers in a array
#include <iostream>
using namespace std;
/* Function to print an array */
void printArray(int A[], int size)
{
for (int i = 0; i < size; i++)
cout << A[i] << " ";
cout << endl;
}
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
// Note the order of appearance of elements should
// be maintained - we copy elements of left subarray
// first followed by that of right subarray
// copy negative elements of left subarray
while (i < n1 && L[i] < 0)
arr[k++] = L[i++];
// copy negative elements of right subarray
while (j < n2 && R[j] < 0)
arr[k++] = R[j++];
// copy positive elements of left subarray
while (i < n1)
arr[k++] = L[i++];
// copy positive elements of right subarray
while (j < n2)
arr[k++] = R[j++];
}
// Function to Rearrange positive and negative
// numbers in a array
void RearrangePosNeg(int arr[], int l, int r)
{
if (l < r) {
// Same as (l + r)/2, but avoids overflow for
// large l and h
int m = l + (r - l) / 2;
// Sort first and second halves
RearrangePosNeg(arr, l, m);
RearrangePosNeg(arr, m + 1, r);
merge(arr, l, m, r);
}
}
/* Driver program to test above functions */
int main()
{
int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
RearrangePosNeg(arr, 0, arr_size - 1);
printArray(arr, arr_size);
return 0;
} | linear | nlogn |
// C++ program to Rearrange positive and negative
// numbers in a array
#include <bits/stdc++.h>
using namespace std;
/* Function to print an array */
void printArray(int A[], int size)
{
for (int i = 0; i < size; i++)
cout << A[i] << " ";
cout << endl;
}
/* Function to reverse an array. An array can be
reversed in O(n) time and O(1) space. */
void reverse(int arr[], int l, int r)
{
if (l < r) {
swap(arr[l], arr[r]);
reverse(arr, ++l, --r);
}
}
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i = l; // Initial index of 1st subarray
int j = m + 1; // Initial index of IInd
while (i <= m && arr[i] < 0)
i++;
// arr[i..m] is positive
while (j <= r && arr[j] < 0)
j++;
// arr[j..r] is positive
// reverse positive part of
// left sub-array (arr[i..m])
reverse(arr, i, m);
// reverse negative part of
// right sub-array (arr[m+1..j-1])
reverse(arr, m + 1, j - 1);
// reverse arr[i..j-1]
reverse(arr, i, j - 1);
}
// Function to Rearrange positive and negative
// numbers in a array
void RearrangePosNeg(int arr[], int l, int r)
{
if (l < r) {
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l + (r - l) / 2;
// Sort first and second halves
RearrangePosNeg(arr, l, m);
RearrangePosNeg(arr, m + 1, r);
merge(arr, l, m, r);
}
}
/* Driver code */
int main()
{
int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
RearrangePosNeg(arr, 0, arr_size - 1);
printArray(arr, arr_size);
return 0;
} | logn | nlogn |
#include <bits/stdc++.h>
using namespace std;
void Rearrange(int arr[], int n)
{
stable_partition(arr,arr+n,[](int x){return x<0;});
}
int main()
{
int n=4;
int arr[n]={-3, 3, -2, 2};
Rearrange( arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
} | linear | quadratic |
#include <iostream>
using namespace std;
void rearrangePosNegWithOrder(int *arr, int size)
{
int i = 0, j = 0;
while (j < size) {
if (arr[j] >= 0) {
j++;
}
else {
for (int k = j; k > i; k--) {
int temp = arr[k];
arr[k] = arr[k - 1];
arr[k - 1] = temp;
}
i++;
j++;
}
}
}
int main()
{
int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };
int size = *(&arr + 1) - arr;
rearrangePosNegWithOrder(arr, size);
for (int i : arr) {
cout << i;
cout << " ";
}
return 0;
} | constant | linear |
// C++ program to rearrange an array in minimum
// maximum form
#include <bits/stdc++.h>
using namespace std;
// Prints max at first position, min at second position
// second max at third position, second min at fourth
// position and so on.
void rearrange(int arr[], int n)
{
// Auxiliary array to hold modified array
int temp[n];
// Indexes of smallest and largest elements
// from remaining array.
int small = 0, large = n - 1;
// To indicate whether we need to copy remaining
// largest or remaining smallest at next position
int flag = true;
// Store result in temp[]
for (int i = 0; i < n; i++) {
if (flag)
temp[i] = arr[large--];
else
temp[i] = arr[small++];
flag = !flag;
}
// Copy temp[] to arr[]
for (int i = 0; i < n; i++)
arr[i] = temp[i];
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original Array\n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
rearrange(arr, n);
cout << "\nModified Array\n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
} | linear | linear |
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
void move(vector<int>& arr){
sort(arr.begin(),arr.end());
}
int main() {
vector<int> arr = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };
move(arr);
for (int e : arr)
cout<<e << " ";
return 0;
}
// This code is contributed by repakaeshwaripriya | linear | nlogn |
// A C++ program to put all negative
// numbers before positive numbers
#include <bits/stdc++.h>
using namespace std;
void rearrange(int arr[], int n)
{
int j = 0;
for (int i = 0; i < n; i++) {
if (arr[i] < 0) {
if (i != j)
swap(arr[i], arr[j]);
j++;
}
}
}
// A utility function to print an array
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
}
// Driver code
int main()
{
int arr[] = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
rearrange(arr, n);
printArray(arr, n);
return 0;
} | constant | linear |
// C++ program of the above
// approach
#include <iostream>
using namespace std;
// Function to shift all the
// negative elements on left side
void shiftall(int arr[], int left,
int right)
{
// Loop to iterate over the
// array from left to the right
while (left<=right)
{
// Condition to check if the left
// and the right elements are
// negative
if (arr[left] < 0 && arr[right] < 0)
left+=1;
// Condition to check if the left
// pointer element is positive and
// the right pointer element is negative
else if (arr[left]>0 && arr[right]<0)
{
int temp=arr[left];
arr[left]=arr[right];
arr[right]=temp;
left+=1;
right-=1;
}
// Condition to check if both the
// elements are positive
else if (arr[left]>0 && arr[right] >0)
right-=1;
else{
left += 1;
right -= 1;
}
}
}
// Function to print the array
void display(int arr[], int right){
// Loop to iterate over the element
// of the given array
for (int i=0;i<=right;++i){
cout<<arr[i]<<" ";
}
cout<<endl;
}
// Driver Code
int main()
{
int arr[] = {-12, 11, -13, -5,
6, -7, 5, -3, 11};
int arr_size = sizeof(arr) /
sizeof(arr[0]);
// Function Call
shiftall(arr,0,arr_size-1);
display(arr,arr_size-1);
return 0;
}
//added by Dhruv Goyal | constant | linear |
#include <iostream>
using namespace std;
// Swap Function.
void swap(int &a,int &b){
int temp =a;
a=b;
b=temp;
}
// Using Dutch National Flag Algorithm.
void reArrange(int arr[],int n){
int low =0,high = n-1;
while(low<high){
if(arr[low]<0){
low++;
}else if(arr[high]>0){
high--;
}else{
swap(arr[low],arr[high]);
}
}
}
void displayArray(int arr[],int n){
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main() {
// Data
int arr[] = {1, 2, -4, -5, 2, -7, 3, 2, -6, -8, -9, 3, 2, 1};
int n = sizeof(arr)/sizeof(arr[0]);
reArrange(arr,n);
displayArray(arr,n);
return 0;
} | constant | linear |
// C++ program to Move All -ve Element At End
// Without changing order Of Array Element
#include<bits/stdc++.h>
using namespace std;
// Moves all -ve element to end of array in
// same order.
void segregateElements(int arr[], int n)
{
// Create an empty array to store result
int temp[n];
// Traversal array and store +ve element in
// temp array
int j = 0; // index of temp
for (int i = 0; i < n ; i++)
if (arr[i] >= 0 )
temp[j++] = arr[i];
// If array contains all positive or all negative.
if (j == n || j == 0)
return;
// Store -ve element in temp array
for (int i = 0 ; i < n ; i++)
if (arr[i] < 0)
temp[j++] = arr[i];
// Copy contents of temp[] to arr[]
memcpy(arr, temp, sizeof(temp));
}
// Driver program
int main()
{
int arr[] = {1 ,-1 ,-3 , -2, 7, 5, 11, 6 };
int n = sizeof(arr)/sizeof(arr[0]);
segregateElements(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
} | linear | linear |
// CPP code to rearrange an array such that
// even index elements are smaller and odd
// index elements are greater than their
// next.
#include <iostream>
using namespace std;
void rearrange(int* arr, int n)
{
for (int i = 0; i < n - 1; i++) {
if (i % 2 == 0 && arr[i] > arr[i + 1])
swap(arr[i], arr[i + 1]);
if (i % 2 != 0 && arr[i] < arr[i + 1])
swap(arr[i], arr[i + 1]);
}
}
/* Utility that prints out an array in
a line */
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
/* Driver function to test above functions */
int main()
{
int arr[] = { 6, 4, 2, 1, 8, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Before rearranging: \n";
printArray(arr, n);
rearrange(arr, n);
cout << "After rearranging: \n";
printArray(arr, n);
return 0;
} | constant | linear |
// C++ program to rearrange positive and negative
// numbers
#include <bits/stdc++.h>
using namespace std;
void rearrange(int a[], int size)
{
int positive = 0, negative = 1;
while (true) {
/* Move forward the positive pointer till
negative number number not encountered */
while (positive < size && a[positive] >= 0)
positive += 2;
/* Move forward the negative pointer till
positive number number not encountered */
while (negative < size && a[negative] <= 0)
negative += 2;
// Swap array elements to fix their position.
if (positive < size && negative < size)
swap(a[positive], a[negative]);
/* Break from the while loop when any index
exceeds the size of the array */
else
break;
}
}
// Driver code
int main()
{
int arr[] = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 };
int n = (sizeof(arr) / sizeof(arr[0]));
rearrange(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
} | constant | quadratic |
// C++ program to rearrange positive
// and negative numbers
#include<iostream>
using namespace std;
// Swap function
void swap(int* a, int i , int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
return ;
}
// Print array function
void printArray(int* a, int n)
{
for(int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
return ;
}
// Driver code
int main()
{
int arr[] = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 };
int n = sizeof(arr)/sizeof(arr[0]);
//before modification
printArray(arr, n);
for(int i = 0; i < n; i++)
{
if(arr[i] >= 0 && i % 2 == 1)
{
// out of order positive element
for(int j = i + 1; j < n; j++)
{
if(arr[j] < 0 && j % 2 == 0)
{
// find out of order negative
// element in remaining array
swap(arr, i, j);
break ;
}
}
}
else if(arr[i] < 0 && i % 2 == 0)
{
// out of order negative element
for(int j = i + 1; j < n; j++)
{
if(arr[j] >= 0 && j % 2 == 1)
{
// find out of order positive
// element in remaining array
swap(arr, i, j);
break;
}
}
}
}
//after modification
printArray(arr, n);
return 0;
}
// This code is contributed by AnitAggarwal | constant | quadratic |
// C++ program to update every array element with
// multiplication of previous and next numbers in array
#include<iostream>
using namespace std;
void modify(int arr[], int n)
{
// Nothing to do when array size is 1
if (n <= 1)
return;
// store current value of arr[0] and update it
int prev = arr[0];
arr[0] = arr[0] * arr[1];
// Update rest of the array elements
for (int i=1; i<n-1; i++)
{
// Store current value of next interaction
int curr = arr[i];
// Update current value using previous value
arr[i] = prev * arr[i+1];
// Update previous value
prev = curr;
}
// Update last array element
arr[n-1] = prev * arr[n-1];
}
// Driver program
int main()
{
int arr[] = {2, 3, 4, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
modify(arr, n);
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
} | constant | linear |
// C++ Program to shuffle a given array
#include<bits/stdc++.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
// A utility function to swap to integers
void swap (int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// A utility function to print an array
void printArray (int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << "\n";
}
// A function to generate a random
// permutation of arr[]
void randomize (int arr[], int n)
{
// Use a different seed value so that
// we don't get same result each time
// we run this program
srand (time(NULL));
// Start from the last element and swap
// one by one. We don't need to run for
// the first element that's why i > 0
for (int i = n - 1; i > 0; i--)
{
// Pick a random index from 0 to i
int j = rand() % (i + 1);
// Swap arr[i] with the element
// at random index
swap(&arr[i], &arr[j]);
}
}
// Driver Code
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
int n = sizeof(arr) / sizeof(arr[0]);
randomize (arr, n);
printArray(arr, n);
return 0;
}
// This code is contributed by
// rathbhupendra | constant | linear |
// C++ Implementation of the above approach
#include <iostream>
using namespace std;
void arrayEvenAndOdd(int arr[], int n)
{
int a[n], index = 0;
for (int i = 0; i < n; i++)
{
if (arr[i] % 2 == 0)
{
a[index] = arr[i];
index++;
}
}
for (int i = 0; i < n; i++)
{
if (arr[i] % 2 != 0)
{
a[index] = arr[i];
index++;
}
}
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
// Driver code
int main()
{
int arr[] = { 1, 3, 2, 4, 7, 6, 9, 10 };
int n = sizeof(arr) / sizeof(int);
// Function call
arrayEvenAndOdd(arr, n);
return 0;
} | linear | linear |
// CPP code to segregate even odd
// numbers in an array
#include <bits/stdc++.h>
using namespace std;
// Function to segregate even odd numbers
void arrayEvenAndOdd(int arr[], int n)
{
int i = -1, j = 0;
int t;
while (j != n) {
if (arr[j] % 2 == 0) {
i++;
// Swapping even and odd numbers
swap(arr[i], arr[j]);
}
j++;
}
// Printing segregated array
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
// Driver code
int main()
{
int arr[] = { 1, 3, 2, 4, 7, 6, 9, 10 };
int n = sizeof(arr) / sizeof(int);
arrayEvenAndOdd(arr, n);
return 0;
} | constant | linear |
// C++ program of above implementation
#include <bits/stdc++.h>
using namespace std;
// Standard partition process of QuickSort().
// It considers the last element as pivot and
// oves all smaller element to left of it
// and greater elements to right
int partition(int* arr, int l, int r)
{
int x = arr[r], i = l;
for (int j = l; j <= r - 1; j++) {
if (arr[j] <= x) {
swap(arr[i], arr[j]);
i++;
}
}
swap(arr[i], arr[r]);
return i;
}
int randomPartition(int* arr, int l, int r)
{
int n = r - l + 1;
int pivot = (rand() % 100 + 1) % n;
swap(arr[l + pivot], arr[r]);
return partition(arr, l, r);
}
// This function returns k'th smallest
// element in arr[l..r] using
// QuickSort based method. ASSUMPTION:
// ALL ELEMENTS IN ARR[] ARE DISTINCT
int kthSmallest(int* arr, int l, int r, int k)
{
// If k is smaller than number
// of elements in array
if (k > 0 && k <= r - l + 1) {
// Partition the array around last
// element and get position of pivot
// element in sorted array
int pos = randomPartition(arr, l, r);
// If position is same as k
if (pos - l == k - 1) {
return arr[pos];
}
// If position is more, recur
// for left subarray
if (pos - l > k - 1) {
return kthSmallest(arr, l, pos - 1, k);
}
// Else recur for right subarray
return kthSmallest(arr, pos + 1, r,
k - pos + l - 1);
}
// If k is more than number of
// elements in array
return INT_MAX;
}
// Driver Code
int main()
{
int arr[] = { 12, 3, 5, 7, 4, 19, 26 };
int n = sizeof(arr) / sizeof(arr[0]), k = 3;
cout << "K'th smallest element is "
<< kthSmallest(arr, 0, n - 1, k);
} | constant | nlogn |
// STL based C++ program to find k-th smallest
// element.
#include <bits/stdc++.h>
using namespace std;
int kthSmallest(int arr[], int n, int k)
{
// Insert all elements into the set
set<int> s;
for (int i = 0; i < n; i++)
s.insert(arr[i]);
// Traverse set and print k-th element
auto it = s.begin();
for (int i = 0; i < k - 1; i++)
it++;
return *it;
}
int main()
{
int arr[] = { 12, 3, 5, 7, 3, 19 };
int n = sizeof(arr) / sizeof(arr[0]), k = 2;
cout << "K'th smallest element is "
<< kthSmallest(arr, n, k);
return 0;
} | linear | nlogn |
#include <iostream>
using namespace std;
// Swap function to interchange
// the value of variables x and y
int swap(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
// Min Heap Class
// arr holds reference to an integer
// array size indicate the number of
// elements in Min Heap
class MinHeap {
int size;
int* arr;
public:
// Constructor to initialize the size and arr
MinHeap(int size, int input[]);
// Min Heapify function, that assumes that
// 2*i+1 and 2*i+2 are min heap and fix the
// heap property for i.
void heapify(int i);
// Build the min heap, by calling heapify
// for all non-leaf nodes.
void buildHeap();
};
// Constructor to initialize data
// members and creating mean heap
MinHeap::MinHeap(int size, int input[])
{
// Initializing arr and size
this->size = size;
this->arr = input;
// Building the Min Heap
buildHeap();
}
// Min Heapify function, that assumes
// 2*i+1 and 2*i+2 are min heap and
// fix min heap property for i
void MinHeap::heapify(int i)
{
// If Leaf Node, Simply return
if (i >= size / 2)
return;
// variable to store the smallest element
// index out of i, 2*i+1 and 2*i+2
int smallest;
// Index of left node
int left = 2 * i + 1;
// Index of right node
int right = 2 * i + 2;
// Select minimum from left node and
// current node i, and store the minimum
// index in smallest variable
smallest = arr[left] < arr[i] ? left : i;
// If right child exist, compare and
// update the smallest variable
if (right < size)
smallest = arr[right] < arr[smallest]
? right : smallest;
// If Node i violates the min heap
// property, swap current node i with
// smallest to fix the min-heap property
// and recursively call heapify for node smallest.
if (smallest != i) {
swap(arr[i], arr[smallest]);
heapify(smallest);
}
}
// Build Min Heap
void MinHeap::buildHeap()
{
// Calling Heapify for all non leaf nodes
for (int i = size / 2 - 1; i >= 0; i--) {
heapify(i);
}
}
void FirstKelements(int arr[],int size,int k){
// Creating Min Heap for given
// array with only k elements
MinHeap* m = new MinHeap(k, arr);
// Loop For each element in array
// after the kth element
for (int i = k; i < size; i++) {
// if current element is smaller
// than minimum element, do nothing
// and continue to next element
if (arr[0] > arr[i])
continue;
// Otherwise Change minimum element to
// current element, and call heapify to
// restore the heap property
else {
arr[0] = arr[i];
m->heapify(0);
}
}
// Now min heap contains k maximum
// elements, Iterate and print
for (int i = 0; i < k; i++) {
cout << arr[i] << " ";
}
}
// Driver Program
int main()
{
int arr[] = { 11, 3, 2, 1, 15, 5, 4,
45, 88, 96, 50, 45 };
int size = sizeof(arr) / sizeof(arr[0]);
// Size of Min Heap
int k = 3;
FirstKelements(arr,size,k);
return 0;
}
// This code is contributed by Ankur Goel | linear | nlogn |
#include <bits/stdc++.h>
using namespace std;
// picks up last element between start and end
int findPivot(int a[], int start, int end)
{
// Selecting the pivot element
int pivot = a[end];
// Initially partition-index will be at starting
int pIndex = start;
for (int i = start; i < end; i++) {
// If an element is lesser than pivot, swap it.
if (a[i] <= pivot) {
swap(a[i], a[pIndex]);
// Incrementing pIndex for further swapping.
pIndex++;
}
}
// Lastly swapping or the correct position of pivot
swap(a[pIndex], a[end]);
return pIndex;
}
// THIS PART OF CODE IS CONTRIBUTED BY - rjrachit
// Picks up random pivot element between start and end
int findRandomPivot(int arr[], int start, int end)
{
int n = end - start + 1;
// Selecting the random pivot index
int pivotInd = random() % n;
swap(arr[end], arr[start + pivotInd]);
int pivot = arr[end];
// initialising pivoting point to start index
pivotInd = start;
for (int i = start; i < end; i++) {
// If an element is lesser than pivot, swap it.
if (arr[i] <= pivot) {
swap(arr[i], arr[pivotInd]);
// Incrementing pivotIndex for further swapping.
pivotInd++;
}
}
// Lastly swapping or the correct position of pivot
swap(arr[pivotInd], arr[end]);
return pivotInd;
}
// THIS PART OF CODE IS CONTRIBUTED BY - rjrachit
void SmallestLargest(int a[], int low, int high, int k,
int n)
{
if (low == high)
return;
else {
int pivotIndex = findRandomPivot(a, low, high);
if (k == pivotIndex) {
cout << k << " smallest elements are : ";
for (int i = 0; i < pivotIndex; i++)
cout << a[i] << " ";
cout << endl;
cout << k << " largest elements are : ";
for (int i = (n - pivotIndex); i < n; i++)
cout << a[i] << " ";
}
else if (k < pivotIndex)
SmallestLargest(a, low, pivotIndex - 1, k, n);
else if (k > pivotIndex)
SmallestLargest(a, pivotIndex + 1, high, k, n);
}
}
// Driver Code
int main()
{
int a[] = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
int n = sizeof(a) / sizeof(a[0]);
int low = 0;
int high = n - 1;
// Lets assume k is 3
int k = 3;
// Function Call
SmallestLargest(a, low, high, k, n);
return 0;
}
// This code is contributed by Sania Kumari Gupta | constant | nlogn |
// C++ code for k largest/ smallest elements in an array
#include <bits/stdc++.h>
using namespace std;
// Function to find k largest array element
void kLargest(vector<int>& v, int N, int K)
{
// Implementation using
// a Priority Queue
priority_queue<int, vector<int>, greater<int> >pq;
for (int i = 0; i < N; ++i) {
// Insert elements into
// the priority queue
pq.push(v[i]);
// If size of the priority
// queue exceeds k
if (pq.size() > K) {
pq.pop();
}
}
// Print the k largest element
while(!pq.empty())
{
cout << pq.top() <<" ";
pq.pop();
}
cout<<endl;
}
// Function to find k smallest array element
void kSmalest(vector<int>& v, int N, int K)
{
// Implementation using
// a Priority Queue
priority_queue<int> pq;
for (int i = 0; i < N; ++i) {
// Insert elements into
// the priority queue
pq.push(v[i]);
// If size of the priority
// queue exceeds k
if (pq.size() > K) {
pq.pop();
}
}
// Print the k smallest element
while(!pq.empty())
{
cout << pq.top() <<" ";
pq.pop();
}
}
// driver program
int main()
{
// Given array
vector<int> arr = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
// Size of array
int n = arr.size();
int k = 3;
cout<<k<<" largest elements are : ";
kLargest(arr, n, k);
cout<<k<<" smallest elements are : ";
kSmalest(arr, n, k);
}
// This code is contributed by Pushpesh Raj. | linear | nlogn |
#include <bits/stdc++.h>
using namespace std;
struct Node{
int data;
struct Node *left;
struct Node *right;
};
class Tree{
public:
Node *root = NULL;
void addNode(int data){
Node *newNode = new Node();
newNode->data = data;
if (!root){
root = newNode;
}
else{
Node *cur = root;
while (cur){
if (cur->data > data){
if (cur->left){
cur = cur->left;
}
else{
cur->left = newNode;
return;
}
}
else{
if (cur->right){
cur = cur->right;
}
else{
cur->right = newNode;
return;
}
}
}
}
}
void printGreatest(int &K, vector<int> /, Node* node){
if (!node || K == 0) return;
printGreatest(K, sol, node->right);
if (K <= 0) return;
sol.push_back(node->data);
K--;
printGreatest(K, sol, node->left);
}
};
class Solution{
public:
vector<int> kLargest(int arr[], int n, int k) {
vector<int> sol;
Tree tree = Tree();
for (int i = 0; i < n; i++){
tree.addNode(arr[i]);
}
tree.printGreatest(k, sol, tree.root);
return sol;
}
};
int main() {
int n = 5, k = 2;
int arr[] = {12, 5, 787, 1, 23};
Solution ob;
auto ans = ob.kLargest(arr, n, k);
cout << "Top " << k << " Elements: ";
for (auto x : ans) {
cout << x << " ";
}
cout << "\n";
return 0;
} | linear | nlogn |
Dataset Card for TASTY C++ and Python Codes with Complexities
This is a dataset of code snippets with their complexities, both space and time.
As part of this initial release, we cover C++ and Python.
This data was collected as part of our work on the paper called TASTY, published at the ICLR DL4Code workshop, a few years back.
We scraped the data from the popular coding website called GeeksForGeeks (GFG). It is under the CCBY license.
We published this paper before the advent of ChatGPT, so this is not recent by any means and things on the GFG website might have changed since we scraped the data. There was also a lot of manual work that went into correcting the scraped data and putting it into the format that we needed it to be, so some of the complexities might not be exactly what you see on the GFG website.
There is work being undertaken on the next version of the paper, where we plan to expand to dataset to several more languages and a lot more examples. Probably 10x more samples for 4-5 more languages. There will be a fundamental change in the tone of the work as well since TASTY was published before the ChatGPT, LLMs were not as popular then.
Dataset Details
There are more than 1000 but less than 2000 codes and their space + time complexity.
Dataset Sources
- Repository: Private, will be made public after the next version of the paper is published,.
- Paper: TASTY: A Transformer based Approach to Space and Time complexity
Uses
- Classification of space and time complexity
- Eventual Auto Regressive prediciton of the same
- Cross Language Transfer
Direct Use
Read the paper above for direct uses.
- Downloads last month
- 38