 1627189200

# How to Search an Element in A Sorted & Rotated Array Fluently

In This video, learn about How to Search an Element in A Sorted & Rotated Array Fluently

#element

## Buddha Community  1596650400

## Count of Array elements greater than all elements on its left

Given an array A[ ] consisting of N distinct integers, the task is to find the number of elements which are **strictly greater **than all the elements preceding it and strictly greater than at least K elements on its right.

Examples:

Input:_ A[] = {2, 5, 1, 7, 3, 4, 0}, K = 3_

Output:_ 2_

Explanation:

The only array elements satisfying the given conditions are:

• 5: Greater than all elements on its left {2} and at least K(= 3) elements on its right {1, 3, 4, 0}
• 7: Greater than all elements on its left {2, 5, 1} and at least K(= 3) elements on its right {3, 4, 0}

Therefore, the count is 2.

Input:_ A[] = {11, 2, 4, 7, 5, 9, 6, 3}, K = 2_

Output:_ 1_

Naive Approach:

The simplest approach to solve the problem is to traverse the array and for each element, traverse all the elements on its left and check if all of them are smaller than it or not and traverse all elements on its right to check if at least K elements are smaller than it or not. For every element satisfying the conditions, increase count. Finally, print the value of count.

Time Complexity:_ O(N2)_

Auxiliary Space:_ O(1)_

Efficient Approach:

The above approach can be further optimized by using Self-Balancing BST. Follow the steps below:

• Traverse the array from right to left and insert all elements one by one in an AVL Tree
• Using the AVL Tree generate an array countSmaller[] which contains the count of smaller elements on the right of every array element.
• Traverse the array and for every ith element, check if it is the maximum obtained so far and countSmaller[i] is greater than or equal to K.
• If so, increase count.
• Print the final value of count as the answer.

Below is the implementation of the above approach:

• C++

`// C++ Program to implement`

`// the above appraoch`

`#include <bits/stdc++.h>`

`**using**` `**namespace**` `std;`

`// Structure of 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;`

`};`

`// Utility function to get maximum`

`// of two integers`

`**int**` `max(``**int**` `a,` `**int**` `b);`

`// Utility function to get height`

`// of the tree rooted with N`

`**int**` `height(``**struct**` `node* N)`

`{`

`**if**` `(N == NULL)`

`**return**` `0;`

`**return**` `N->height;`

`}`

`// Utility function to find size of`

`// the tree rooted with N`

`**int**` `size(``**struct**` `node* N)`

`{`

`**if**` `(N == NULL)`

`**return**` `0;`

`**return**` `N->size;`

`}`

`// Utility function to get maximum`

`// of two integers`

`**int**` `max(``**int**` `a,` `**int**` `b)`

`{`

`**return**` `(a > b) ? a : b;`

`}`

`// Helper function to allocates a`

`// new node with the given key`

`**struct**` `node* newNode(``**int**` `key)`

`{`

`**struct**` `node* node`

`= (``**struct**` `node*)`

`**malloc**``(``**sizeof**``(``**struct**` `node));`

`node->key = key;`

`node->left = NULL;`

`node->right = NULL;`

`node->height = 1;`

`node->size = 1;`

`**return**` `(node);`

`}`

`// 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;`

`}`

`// 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;`

`}`

`// Function to obtain Balance factor`

`// of node N`

`**int**` `getBalance(``**struct**` `node* N)`

`{`

`**if**` `(N == NULL)`

`**return**` `0;`

`**return**` `height(N->left)`

`- height(N->right);`

`}`

`// Function to insert a new key to the`

`// tree rooted with node`

`**struct**` `node* insert(``**struct**` `node* node,` `**int**` `key,`

`**int**``* count)`

`{`

`// 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`

`*count = *count + size(node->left) + 1;`

`}`

`// Update height and size of the ancestor`

`node->height = max(height(node->left),`

`height(node->right))`

`+ 1;`

`node->size = size(node->left)`

`+ size(node->right) + 1;`

`// Get the balance factor of the ancestor`

`**int**` `balance = getBalance(node);`

`// 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**` `node;`

`}`

`// Function to generate an array which contains`

`// count of smaller elements on the right`

`**void**` `constructLowerArray(``**int**` `arr[],`

`**int**` `countSmaller[],`

`**int**` `n)`

`{`

`**int**` `i, j;`

`**struct**` `node* root = NULL;`

`**for**` `(i = 0; i < n; i++)`

`countSmaller[i] = 0;`

`// Insert all elements in the AVL Tree`

`// and get the count of smaller elements`

`**for**` `(i = n - 1; i >= 0; i--) {`

`root = insert(root, arr[i],`

`&countSmaller[i]);`

`}`

`}`

`// Function to find the number`

`// of elements which are greater`

`// than all elements on its left`

`// and K elements on its right`

`**int**` `countElements(``**int**` `A[],` `**int**` `n,` `**int**` `K)`

`{`

`**int**` `count = 0;`

`// Stores the count of smaller`

`// elements on its right`

`**int**``* countSmaller`

`= (``**int**``*)``**malloc**``(``**sizeof**``(``**int**``) * n);`

`constructLowerArray(A, countSmaller, n);`

`**int**` `maxi = INT_MIN;`

`**for**` `(``**int**` `i = 0; i <= (n - K - 1); i++) {`

`**if**` `(A[i] > maxi && countSmaller[i] >= K) {`

`count++;`

`maxi = A[i];`

`}`

`}`

`**return**` `count;`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`**int**` `A[] = { 2, 5, 1, 7, 3, 4, 0 };`

`**int**` `n =` `**sizeof**``(A) /` `**sizeof**``(``**int**``);`

`**int**` `K = 3;`

`cout << countElements(A, n, K);`

`**return**` `0;`

`}`

Output:

``````2
``````

_Time Complexity: _O(NlogN)

_Auxiliary Space: _O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#advanced data structure #arrays #binary search tree #mathematical #searching #avl-tree #balanced binary search trees #rotation 1597240800

## Check if an Array can be Sorted by picking only the corner Array elements

Given an array **arr[] **consisting of N elements, the task is to check if the given array can be sorted by picking only corner elements i.e., elements either from left or right side of the array can be chosen.

Examples:

_Input: _arr[] = {2, 3, 4, 10, 4, 3, 1}

_Output: _Yes

Explanation:

The order of picking elements from the array and placing in the sorted array are as follows:

{2, 3, 4, 10, 4, 3, 1} -> {1}

{2, 3, 4, 10, 4, 3} -> {1, 2}

{3, 4, 10, 4, 3} -> {1, 2, 3}

{4, 10, 4, 3} -> {1, 2, 3, 3}

{4, 10, 4} -> {1, 2, 3, 3, 4}

{10, 4} -> {1, 2, 3, 3, 4, 4}

{10} -> {1, 2, 3, 3, 4, 4, 10}

Input:_ a[] = {2, 4, 2, 3}_

_Output: _No

**Approach: **To solve the problem, we need to use a concept similar to Bitonic Sequence.Follow the below steps to solve the problem:

• Traverse the array and check if the sequence of array elements is decreasing, i.e. if the next element is smaller than previous element, then all the remaining elements should be decreasing or equal as well.
• That is, if the sequence is non-increasingnon-decreasing or** non-decreasing followed by non-increasing**, only then the array can be sorted by the given operations.

Below is implementation of above approach:

• C++

`// C++ Program to implement`

`// the above approach`

`#include <bits/stdc++.h>`

`**using**` `**namespace**` `std;`

`// Function to check if an array can`

`// be sorted using given operations`

`**bool**` `check(``**int**` `arr[],` `**int**` `n)`

`{`

`**int**` `i, g;`

`g = 0;`

`**for**` `(i = 1; i < n; i++) {`

`// If sequence becomes increasing`

`// after an already non-decreasing to`

`// non-increasing pattern`

`**if**` `(arr[i] - arr[i - 1] > 0 && g == 1)`

`**return**` `**false**``;`

`// If a decreasing pattern is observed`

`**if**` `(arr[i] - arr[i - 1] < 0)`

`g = 1;`

`}`

`**return**` `**true**``;`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`**int**` `arr[] = { 2, 3, 4, 10, 4, 3, 1 };`

`**int**` `n =` `**sizeof**``(arr) /` `**sizeof**``(``**int**``);`

`**if**` `(check(arr, n) ==` `**true**``)`

`cout <<` `"Yes"`

`"\n"``;`

`**else**`

`cout <<` `"No"`

`<<` `"\n"``;`

`**return**` `0;`

`}`

Output:

``````Yes
``````

_Time Complexity: _O(N)

Auxiliary Space:_ O(1)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #greedy #mathematical #pattern searching #searching #sorting #bitonic 1617742620

## C Program to Count Frequency Of Each Element in an Array

Given an array arr[] of size N, the task is to find the frequency of each distinct element present in the given array.

Examples:

``````Input: arr[] = { 1, 100000000, 3, 100000000, 3 }

Output: { 1 : 1, 3 : 2, 100000000 : 2 }

Explanation:

Distinct elements of the given array are { 1, 100000000, 3 }

Frequency of 1 in the given array is 1.

Frequency of 100000000 in the given array is 2.

Frequency of 3 in the given array is 2.

Therefore, the required output is { 1 : 1, 100000000 : 2, 3 : 2 }

Input: arr[] = { 100000000, 100000000, 800000000, 100000000 }

Output: { 100000000 : 3, 800000000 : 1}

``````

#arrays #c #c programs #mathematical #searching #sorting #binary search #frequency-counting #quick sort 1596619983

## Rearrange an Array such that Sum of same-indexed subsets differ

Given an array A[] consisting of N distinct integers, the task is to rearrange the given array such that the sum of every same-indexed non-empty subsets of size less than N, is not equal to their sum in the original array.

Examples:

Input:_ A[] = {1000, 100, 10, 1}_

Output:_ 100 10 1 1000_

Explanation:

Original Array A[] = {1000, 100, 10, 1}

Final Array B[] = {100, 10, 1, 1000}

Subsets of size 1:

``````A = 1000  B = 100
A = 100   B = 10
A = 10    B = 1
A = 1     B = 1000
``````

Subsets of size 2:

``````{A, A} = 1100  {B, B} = 110
{A, A} = 1010  {B, B} = 101
{A, A} = 110   {B, B} = 11
.....
Similarly, all same-indexed subsets of size 2 have a different sum.
``````

Subsets of size 3:

``````{A, A, A} = 1110  {B, B, B} = 111
{A, A, A} = 1011 {B, B, B} = 1101
{A, A, A} = 111  {B, B, B} = 1011
``````

Therefore, no same-indexed subsets have equal sum.

Input:_ A[] = {1, 2, 3, 4, 5}_

_Output: _5 1 2 3 4

Approach:

The idea is to simply replace every array element except one, by a smaller element. Follow the steps below to solve the problem:

• Store the array elements in pairs of {A[i], i}.
• Sort the pairs in ascending order of the array elements
• Now, traverse the sorted order, and insert each element at the original index of its next greater element(i.e. at the index v[(i + 1) % n].second). This ensures that every index except one, now has a smaller element than the previous value stored in it.

Proof:

Let S = { arr1, arr2, …, arrk } be a subset.

If_ u does not belong to S__ initially, upon insertion of u into S, the sum of the subset changes._

Similarly, if_ u belongs to S, _let S’ contains all the elements not present in S. This means that u do not belong to S’. Then, by the same reasoning above, the sum of the subset S’ differs from its original sum.

Below is the implementation of the above approach:

• C++

`// C++ Program to implement`

`// the above approach`

`#include <bits/stdc++.h>`

`**using**` `**namespace**` `std;`

`// Function to rearrange the array such`

`// that no same-indexed subset have sum`

`// equal to that in the original array`

`**void**` `printNewArray(vector<``**int**``> a,` `**int**` `n)`

`{`

`// Initialize a vector`

`vector<pair<``**int**``,` `**int**``> > v;`

`// Iterate the array`

`**for**` `(``**int**` `i = 0; i < n; i++) {`

`v.push_back({ a[i], i });`

`}`

`// Sort the vector`

`sort(v.begin(), v.end());`

`**int**` `ans[n];`

`// Shift of elements to the`

`// index of its next cyclic element`

`**for**` `(``**int**` `i = 0; i < n; i++) {`

`ans[v[(i + 1) % n].second]`

`= v[i].first;`

`}`

`// Print the answer`

`**for**` `(``**int**` `i = 0; i < n; i++) {`

`cout << ans[i] <<` `" "``;`

`}`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`vector<``**int**``> a = { 4, 1, 2, 5, 3 };`

`**int**` `n = a.size();`

`printNewArray(a, n);`

`**return**` `0;`

`}`

Output:

``````3 5 1 4 2
``````

_Time Complexity: _O(N log N)

_Auxiliary Space: _O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #greedy #mathematical #pattern searching #searching #sorting #array-rearrange #subset 1603644780

## Print X array elements closest to the Kth smallest element in the array

Given two integers KX, and an array arr[] consisting of **N **distinct elements, the task is to find X elements closest to the Kth smallest element from the given array.

Examples:

Input:_ arr[] = {1, 2, 3, 4, 10}, K = 3, X = 2_

Output:_ 2 3_

_Explanation: _Kth smallest element present in the given array is 3 and X(= 2) closest array elements to 3 are {2, 3} or {3, 4}.

Therefore, the required output is 2 3.

Input:_ arr[] = {1, 9, 8, 2, 7, 3, 6, 4, 5, 10, 13, 12, 16, 14, 11, 15}, K = 3, X = 5_

Output:_ 1 2 3 4 5_

**Naive Approach: **The simplest approach to solve this problem is to sort the array and print X closest elements to the Kth smallest element of the given array using the two-pointers technique.

Time Complexity:_ O(N * log N)_

Auxiliary Space:_ O(1)_

#arrays #divide and conquer #hash #mathematical #searching #sorting #cpp-map #frequency-counting #java-hashmap #median-finding