0% found this document useful (0 votes)
3 views

Dec 12thACA

The document provides algorithms and code for various tree operations, including inorder traversal, converting a tree to a linked list, and printing the bottom view of a binary tree. It also covers heap operations such as heap sort and relative sorting, along with the implementation of a priority queue. Each section includes time and space complexity analysis, along with example outputs for better understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Dec 12thACA

The document provides algorithms and code for various tree operations, including inorder traversal, converting a tree to a linked list, and printing the bottom view of a binary tree. It also covers heap operations such as heap sort and relative sorting, along with the implementation of a priority queue. Each section includes time and space complexity analysis, along with example outputs for better understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Date: 5-12-24

4 Trees
4.1 Inorder Traversal
Algorithm (Recursive):
1. Start at the root node of the tree.
2. Traverse the left subtree in an inorder manner (recursively).
3. Visit the current node (process its value).

4. Traverse the right subtree in an inorder manner (recursively).


Time Complexity:
• Best case: O(n) (all nodes must be visited)

• Worst case: O(n)


• Average case: O(n)
Space Complexity:
• Recursive solution: O(h), where h is the height of the tree (due to the function call stack).

• Iterative solution: O(h), as a stack is used to simulate recursion.


Code:
# include < iostream >
# include < vector >
using namespace std ;

struct Node
{
int val ;
Node * left ;
Node * right ;
Node ( int x ) : val ( x ) , left ( NULL ) , right ( NULL ) {}
};

void inorder ( Node * root )


{
if ( root == NULL )
return ;

inorder ( root - > left ) ;


cout << root - > val << " " ;
inorder ( root - > right ) ;
}

Node * createTree ( vector < int > & nodes , int & index , int n )
{
if ( index >= n || nodes [ index ] == -1)
return NULL ;

Node * root = new Node ( nodes [ index ]) ;


index ++;
root - > left = createTree ( nodes , index , n ) ;
index ++;
root - > right = createTree ( nodes , index , n ) ;

return root ;
}

int main ()
{
int n ;

25
cout << " Enter the number of nodes in the binary tree : " ;
cin >> n ;

vector < int > nodes ( n ) ;


cout << " Enter the nodes of the binary tree ( -1 for NULL ) : " ;
for ( int i = 0; i < n ; i ++)
{
cin >> nodes [ i ];
}

int index = 0;
Node * root = createTree ( nodes , index , n ) ;

cout << " Inorder Traversal of the binary tree : " ;


inorder ( root ) ;
cout << endl ;

return 0;
}

Output 1:
Enter the number of nodes in the binary tree: 7
Enter the nodes of the binary tree (-1 for NULL): 1 2 3 -1 -1 4 5
Inorder Traversal of the binary tree: 2 1 4 3 5
Output 2:
Enter the number of nodes in the binary tree: 5
Enter the nodes of the binary tree (-1 for NULL): 10 5 15 -1 -1
Inorder Traversal of the binary tree: 5 10 15

4.2 Tree to Linked List


Algorithm (Preorder Traversal):
1. Start at the root node of the binary tree.
2. Traverse the left subtree and flatten it recursively.
3. Traverse the right subtree and flatten it recursively.
4. If the left subtree exists:
(a) Save the right subtree in a temporary variable.
(b) Attach the left subtree as the new right subtree.
(c) Move to the end of this new right subtree.
(d) Attach the saved right subtree to the end of the new right subtree.
5. Repeat this process until all nodes are flattened.
Time Complexity:
• O(n): Each node is visited once during traversal.
Space Complexity:
• O(h): Recursive function calls require stack space proportional to the height of the tree.
Code:
# include < iostream >
using namespace std ;

struct Node
{
int val ;
Node * left ;
Node * right ;

26
Node ( int x ) : val ( x ) , left ( NULL ) , right ( NULL ) {}
};

void flatten ( Node * root )


{
if ( root == NULL )
return ;

flatten ( root - > left ) ;


flatten ( root - > right ) ;

if ( root - > left != NULL )


{
Node * temp = root - > right ;
root - > right = root - > left ;
root - > left = NULL ;

Node * current = root - > right ;


while ( current - > right != NULL )
current = current - > right ;

current - > right = temp ;


}
}

void p ri nt Li n ke dL is t ( Node * root )


{
while ( root != NULL )
{
cout << root - > val << " " ;
root = root - > right ;
}
cout << endl ;
}

Node * createTree ( int nodes [] , int & index , int n )


{
if ( index >= n || nodes [ index ] == -1)
return NULL ;

Node * root = new Node ( nodes [ index ]) ;


index ++;
root - > left = createTree ( nodes , index , n ) ;
index ++;
root - > right = createTree ( nodes , index , n ) ;

return root ;
}

int main ()
{
int n ;
cout << " Enter the number of nodes in the binary tree : " ;
cin >> n ;

int nodes [ n ];
cout << " Enter the nodes of the binary tree ( -1 for NULL ) : " ;
for ( int i = 0; i < n ; i ++)
cin >> nodes [ i ];

int index = 0;
Node * root = createTree ( nodes , index , n ) ;

flatten ( root ) ;

cout << " Linked list repre sentatio n : " ;


p ri nt Li n ke dL is t ( root ) ;

return 0;
}

Output 1:
Enter the number of nodes in the binary tree: 7

27
Enter the nodes of the binary tree (-1 for NULL): 1 2 5 3 4 -1 6
Linked list representation: 1 2 3 4 5 6
Output 2:
Enter the number of nodes in the binary tree: 5
Enter the nodes of the binary tree (-1 for NULL): 10 5 15 -1 -1
Linked list representation: 10 5 15

4.3 Print Bottom View of Binary Tree


Algorithm:
1. Use a queue for level-order traversal, and a map to store the bottom view.
2. Start at the root node with horizontal distance 0.
3. Traverse each node in the tree:
(a) Update the map with the node’s value at its horizontal distance.
(b) Push the left child into the queue with horizontal distance −1 from the current node.
(c) Push the right child into the queue with horizontal distance +1 from the current node.
4. After traversal, extract and print values from the map in ascending order of horizontal distances.
Time Complexity:
• O(n): Each node is visited once, and map operations are logarithmic.
Space Complexity:
• O(n): Space required for the queue and map storage.
Code:
# include < iostream >
# include <map >
# include < queue >
using namespace std ;

struct Node
{
int val ;
Node * left ;
Node * right ;
Node ( int x ) : val ( x ) , left ( NULL ) , right ( NULL ) {}
};

void p ri nt Bo t to mV ie w ( Node * root )


{
if ( root == NULL )
{
return ;
}

map < int , int > bottomView ;


queue < pair < Node * , int > > q ;

q . push ({ root , 0}) ;

while (! q . empty () )
{
auto front = q . front () ;
q . pop () ;

Node * current = front . first ;


int hd = front . second ;

bottomView [ hd ] = current - > val ;

if ( current - > left != NULL )

28
q . push ({ current - > left , hd - 1}) ;
if ( current - > right != NULL )
q . push ({ current - > right , hd + 1}) ;
}

for ( const auto & pair : bottomView )


cout << pair . second << " " ;
cout << endl ;
}

Node * createTree ( int nodes [] , int & index , int n )


{
if ( index >= n || nodes [ index ] == -1)
return NULL ;

Node * root = new Node ( nodes [ index ]) ;


index ++;
root - > left = createTree ( nodes , index , n ) ;
index ++;
root - > right = createTree ( nodes , index , n ) ;

return root ;
}

int main ()
{
int n ;
cout << " Enter the number of nodes in the binary tree : " ;
cin >> n ;

int nodes [ n ];
cout << " Enter the nodes of the binary tree ( -1 for NULL ) : " ;
for ( int i = 0; i < n ; i ++)
cin >> nodes [ i ];

int index = 0;
Node * root = createTree ( nodes , index , n ) ;

cout << " Bottom view of the binary tree : " ;


p ri nt Bo t to mV ie w ( root ) ;

return 0;
}

Output 1:
Enter the number of nodes in the binary tree: 7
Enter the nodes of the binary tree (-1 for NULL): 20 8 22 5 3 -1 25
Bottom view of the binary tree: 5 3 22 25
Output 2:
Enter the number of nodes in the binary tree: 10
Enter the nodes of the binary tree (-1 for NULL): 1 2 3 4 5 6 7 -1 -1 8 9
Bottom view of the binary tree: 4 8 6 3 7

5 Operation On heaps
5.1 Heap Sort
Algorithm:
1. Build a max heap from the input array.
2. Swap the first element (largest) with the last element of the heap.
3. Reduce the heap size by 1 and heapify the root element to maintain the max heap property.
4. Repeat steps 2 and 3 until the heap size becomes 1.
Time Complexity:

29
• O(n log n): Building the heap takes O(n), and heapifying each element during the sorting process takes O(log n).
Space Complexity:

• O(1): In-place sorting requires no additional space.


Code:
# include < iostream >
# include < vector >
using namespace std ;

void heapify ( vector < int > & arr , int n , int i )
{
int largest = i ;
int left = 2 * i + 1;
int right = 2 * i + 2;

if ( left < n && arr [ left ] > arr [ largest ])


largest = left ;

if ( right < n && arr [ right ] > arr [ largest ])


largest = right ;

if ( largest != i )
{
swap ( arr [ i ] , arr [ largest ]) ;
heapify ( arr , n , largest ) ;
}
}

void heapSort ( vector < int > & arr )


{
int n = arr . size () ;

for ( int i = n / 2 - 1; i >= 0; i - -)


heapify ( arr , n , i ) ;

for ( int i = n - 1; i > 0; i - -)


{
swap ( arr [0] , arr [ i ]) ;
heapify ( arr , i , 0) ;
}
}

int main ()
{
int n ;
cout << " Enter the number of elements : " ;
cin >> n ;

vector < int > arr ( n ) ;


cout << " Enter the elements : " ;
for ( int i = 0; i < n ; i ++)
cin >> arr [ i ];

heapSort ( arr ) ;

cout << " Sorted array : " ;


for ( int i = 0; i < n ; i ++)
cout << arr [ i ] << " " ;
cout << endl ;

return 0;
}

Output 1:
Enter the number of elements: 5
Enter the elements: 4 10 3 5 1
Sorted array: 1 3 4 5 10
Output 2:

30
Enter the number of elements: 7
Enter the elements: 12 11 13 5 6 7 15
Sorted array: 5 6 7 11 12 13 15

5.2 Relative Sorting


Algorithm:
1. Count the frequency of each element in the first array (arr1) using a hash map.
2. Traverse the second array (arr2) to find and append elements in the relative order:
(a) For each element in arr2, add it to the result as many times as it appears in arr1.
(b) Remove the processed elements from the hash map.
3. Append the remaining elements of arr1 (not in arr2) in sorted order to the result.
Time Complexity:
• O(n+m+r log r): O(n) for counting elements in arr1, O(m) for traversing arr2, and O(r log r) for sorting remaining
elements, where n, m, r are the sizes of arr1, arr2, and remaining elements in arr1, respectively.
Space Complexity:
• O(n + m): Space for the hash map and result vector.
Code:
# include < iostream >
# include < vector >
# include < unordered_map >
# include < algorithm >
using namespace std ;

vector < int > relativeSort ( vector < int > & arr1 , vector < int > & arr2 )
{
unordered_map < int , int > freq ;
vector < int > result ;

for ( int num : arr1 )


freq [ num ]++;

for ( int num : arr2 )


{
while ( freq [ num ] > 0)
{
result . push_back ( num ) ;
freq [ num ] - -;
}
freq . erase ( num ) ;
}

vector < int > remaining ;


for ( const auto & entry : freq )
for ( int i = 0; i < entry . second ; i ++)
remaining . push_back ( entry . first ) ;
sort ( remaining . begin () , remaining . end () ) ;

result . insert ( result . end () , remaining . begin () , remaining . end () ) ;

return result ;
}

int main ()
{
int n , m ;
cout << " Enter the size of the first array : " ;
cin >> n ;
vector < int > arr1 ( n ) ;
cout << " Enter the elements of the first array : " ;
for ( int i = 0; i < n ; i ++)
cin >> arr1 [ i ];

31
cout << " Enter the size of the second array : " ;
cin >> m ;
vector < int > arr2 ( m ) ;
cout << " Enter the elements of the second array : " ;
for ( int i = 0; i < m ; i ++)
cin >> arr2 [ i ];

vector < int > result = relativeSort ( arr1 , arr2 ) ;

cout << " Resulting array after relative sorting : " ;


for ( int num : result )
cout << num << " " ;
cout << endl ;

return 0;
}

Output 1:
Enter the size of the first array: 7
Enter the elements of the first array: 2 1 2 5 7 1 9
Enter the size of the second array: 4
Enter the elements of the second array: 2 1 8 3
Resulting array after relative sorting: 2 2 1 1 5 7 9
Output 2:

Enter the size of the first array: 6


Enter the elements of the first array: 8 6 4 3 7 2
Enter the size of the second array: 3
Enter the elements of the second array: 7 4 3
Resulting array after relative sorting: 7 4 3 2 6 8

5.3 Implementing a priority queue


Algorithm:
1. Define a class PriorityQueue to manage the priority queue.

2. Use a vector to store elements internally.


3. Provide the following methods:
• push(int x): Add an element to the queue and maintain the max-heap property.
• pop(): Remove the highest-priority element (the root of the heap) and restore the heap property.
• top(): Return the highest-priority element without removing it.
4. Implement a helper function heapify(int i) to restore the max-heap property by comparing the root with its
children and swapping as necessary.
5. Ensure that the queue behaves as a max-heap, where the largest element has the highest priority.

Time Complexity:
• Push Operation: O(log n): Inserting an element involves heapify-up, which takes O(log n).
• Pop Operation: O(log n): Removing the root element involves heapify-down, which takes O(log n).

• Top Operation: O(1): Accessing the top element is O(1).


Space Complexity:
• O(n): Space is required to store n elements in the vector.
Code:

32
# include < iostream >
# include < vector >
using namespace std ;

class PriorityQueue
{
private :
vector < int > heap ;

void heapifyDown ( int i )


{
int largest = i ;
int left = 2 * i + 1;
int right = 2 * i + 2;

if ( left < heap . size () && heap [ left ] > heap [ largest ])
largest = left ;
if ( right < heap . size () && heap [ right ] > heap [ largest ])
largest = right ;

if ( largest != i )
{
swap ( heap [ i ] , heap [ largest ]) ;
heapifyDown ( largest ) ;
}
}

void heapifyUp ( int i )


{
int parent = ( i - 1) / 2;
if ( i > 0 && heap [ i ] > heap [ parent ])
{
swap ( heap [ i ] , heap [ parent ]) ;
heapifyUp ( parent ) ;
}
}

public :
void push ( int x )
{
heap . push_back ( x ) ;
heapifyUp ( heap . size () - 1) ;
}

void pop ()
{
if ( heap . empty () )
{
cout << " Priority queue is empty ! " << endl ;
return ;
}
heap [0] = heap . back () ;
heap . pop_back () ;
heapifyDown (0) ;
}

int top ()
{
if ( heap . empty () )
{
cout << " Priority queue is empty ! " << endl ;
return -1;
}
return heap [0];
}

bool empty ()
{
return heap . empty () ;
}
};

int main ()

33
{
PriorityQueue pq ;

int n , choice , value ;


cout << " Enter the number of operations : " ;
cin >> n ;

cout << " Operations :\ n1 . Push \ n2 . Pop \ n3 . Top \ n " ;


for ( int i = 0; i < n ; i ++)
{
cout << " Enter operation : " ;
cin >> choice ;

switch ( choice )
{
case 1:
cout << " Enter value to push : " ;
cin >> value ;
pq . push ( value ) ;
break ;
case 2:
pq . pop () ;
break ;
case 3:
cout << " Top element : " << pq . top () << endl ;
break ;
default :
cout << " Invalid operation ! " << endl ;
}
}

return 0;
}

Output 1:
Enter the number of operations: 6
Operations:
1. Push
2. Pop
3. Top
Enter operation: 1
Enter value to push: 10
Enter operation: 1
Enter value to push: 5
Enter operation: 1
Enter value to push: 20
Enter operation: 3
Top element: 20
Enter operation: 2
Enter operation: 3
Top element: 10
Output 2:
Enter the number of operations: 5
Operations:
1. Push
2. Pop
3. Top
Enter operation: 1
Enter value to push: 7
Enter operation: 1
Enter value to push: 15
Enter operation: 3
Top element: 15
Enter operation: 2

34
Enter operation: 3
Top element: 7

6 Implementation of Hash Table and Applications


6.1 Implementing a Hash Table
Algorithm:
1. Create a class HashTable to manage the hash table.
2. Use an array of vectors (buckets) to handle collisions using chaining.

3. Provide the following methods:


• insert(int key, int value): Compute the hash index for the key and append the key-value pair to the
corresponding bucket.
• search(int key): Compute the hash index and search the bucket for the key. Return the value if found,
otherwise indicate it is not present.
• remove(int key): Compute the hash index and delete the key-value pair from the bucket if it exists.
4. Use a simple hash function: hash = key mod size.
Time Complexity:
• Best Case: O(1): No collisions.

• Worst Case: O(n): All keys hash to the same index.


• Average Case: O(1): For a good hash function and moderate load factor.
Space Complexity:

• O(n): Space is required to store n key-value pairs in the hash table.


Code:
# include < iostream >
# include < vector >
# include < list >
using namespace std ;

class HashTable
{
private :
vector < list < pair < int , int > > > table ;
int size ;

int hashFunction ( int key )


{
return key % size ;
}

public :
HashTable ( int s )
{
size = s ;
table . resize ( size ) ;
}

void insert ( int key , int value )


{
int index = hashFunction ( key ) ;
for ( auto & pair : table [ index ])
{
if ( pair . first == key )
{
pair . second = value ;
return ;

35
}
}
table [ index ]. emplace_back ( key , value ) ;
}

int search ( int key )


{
int index = hashFunction ( key ) ;
for ( auto & pair : table [ index ])
if ( pair . first == key )
return pair . second ;
return -1;
}

void remove ( int key )


{
int index = hashFunction ( key ) ;
for ( auto it = table [ index ]. begin () ; it != table [ index ]. end () ; ++ it )
{
if ( it - > first == key )
{
table [ index ]. erase ( it ) ;
return ;
}
}
cout << " Key not found ! " << endl ;
}

void display ()
{
for ( int i = 0; i < size ; i ++)
{
cout << " Bucket " << i << " : " ;
for ( auto & pair : table [ i ])
cout << " ( " << pair . first << " , " << pair . second << " ) " ;
cout << endl ;
}
}
};

int main ()
{
int size , choice , key , value ;
cout << " Enter the size of the hash table : " ;
cin >> size ;

HashTable ht ( size ) ;

cout << " Operations :\ n1 . Insert \ n2 . Search \ n3 . Remove \ n4 . Display \ n " ;


do
{
cout << " Enter your choice (0 to exit ) : " ;
cin >> choice ;

switch ( choice )
{
case 1:
cout << " Enter key and value to insert : " ;
cin >> key >> value ;
ht . insert ( key , value ) ;
break ;
case 2:
cout << " Enter key to search : " ;
cin >> key ;
value = ht . search ( key ) ;
if ( value != -1)
cout << " Value : " << value << endl ;
else
cout << " Key not found ! " << endl ;
break ;
case 3:
cout << " Enter key to remove : " ;
cin >> key ;
ht . remove ( key ) ;

36
break ;
case 4:
ht . display () ;
break ;
case 0:
cout << " Exiting . " << endl ;
break ;
default :
cout << " Invalid choice ! " << endl ;
}
} while ( choice != 0) ;

return 0;
}

Output 1:
Enter the size of the hash table: 5
Operations:
1. Insert
2. Search
3. Remove
4. Display
Enter your choice (0 to exit): 1
Enter key and value to insert: 10 100
Enter your choice (0 to exit): 1
Enter key and value to insert: 15 200
Enter your choice (0 to exit): 2
Enter key to search: 10
Value: 100
Enter your choice (0 to exit): 4
Bucket 0:
Bucket 1:
Bucket 2:
Bucket 3:
Bucket 4: (10, 100) (15, 200)
Enter your choice (0 to exit): 0
Exiting.

Output 2:
Enter the size of the hash table: 7
Operations:
1. Insert
2. Search
3. Remove
4. Display
Enter your choice (0 to exit): 1
Enter key and value to insert: 5 50
Enter your choice (0 to exit): 1
Enter key and value to insert: 12 120
Enter your choice (0 to exit): 4
Bucket 0:
Bucket 1:
Bucket 2:
Bucket 3:
Bucket 4:
Bucket 5: (5, 50)
Bucket 6: (12, 120)
Enter your choice (0 to exit): 3
Enter key to remove: 5
Enter your choice (0 to exit): 4
Bucket 0:

37
Bucket 1:
Bucket 2:
Bucket 3:
Bucket 4:
Bucket 5:
Bucket 6: (12, 120)
Enter your choice (0 to exit): 0
Exiting.

6.2 Sorting elements of an array by frequency


Algorithm:
1. Create a frequency map to count the occurrences of each element in the array.
2. Store elements in a vector of pairs, where each pair contains an element and its frequency.
3. Sort the vector of pairs based on the following criteria:
• Higher frequency comes first.
• If frequencies are the same, sort by the element value in ascending order.
4. Reconstruct the sorted array using the sorted vector of pairs.
5. Output the sorted array.
Time Complexity:
• O(n log n):
– Building the frequency map takes O(n).
– Sorting the vector of pairs takes O(n log n), where n is the number of distinct elements.
• Overall: O(n log n).
Space Complexity:
• O(n): Space for the frequency map and the sorted vector.
Code:
# include < iostream >
# include < vector >
# include < unordered_map >
# include < algorithm >
using namespace std ;

bool comparator ( const pair < int , int > &a , const pair < int , int > & b )
{
if ( a . second == b . second )
return a . first < b . first ;
return a . second > b . second ;
}

void s or tB yF r eq ue nc y ( vector < int > & arr )


{
unordered_map < int , int > freqMap ;

for ( int num : arr )


freqMap [ num ]++;

vector < pair < int , int > > freqVec ( freqMap . begin () , freqMap . end () ) ;
sort ( freqVec . begin () , freqVec . end () , comparator ) ;

vector < int > sortedArr ;


for ( const auto & pair : freqVec )
for ( int i = 0; i < pair . second ; i ++)
sortedArr . push_back ( pair . first ) ;

arr = sortedArr ;

38
}

int main ()
{
int n ;
cout << " Enter the number of elements : " ;
cin >> n ;

vector < int > arr ( n ) ;


cout << " Enter the elements : " ;
for ( int i = 0; i < n ; i ++)
cin >> arr [ i ];

s or tB yF r eq ue nc y ( arr ) ;

cout << " Sorted array by frequency : " ;


for ( int num : arr )
cout << num << " " ;
cout << endl ;

return 0;
}

Output 1:
Enter the number of elements: 8
Enter the elements: 4 5 6 5 4 3 3 3
Sorted array by frequency: 3 3 3 4 4 5 5 6
Output 2:
Enter the number of elements: 7
Enter the elements: 1 2 3 2 1 1 4
Sorted array by frequency: 1 1 1 2 2 3 4

6.3 Longest Consecutive Subsequence


Algorithm:
1. Use a hash set to store all elements of the array for O(1) lookup.
2. Iterate through the array, treating each element as a potential starting point of a sequence:
• If the current element minus one (x − 1) is not in the set, it marks the start of a new sequence.
3. For each starting point, count the length of the consecutive subsequence by checking subsequent elements (x + 1, x +
2, . . .) in the set.
4. Track the maximum sequence length encountered during the traversal.
5. Return the maximum length.
Time Complexity:
• O(n):
– Each element is added to the set once and processed at most twice (once as a starting point and during sequence
extension).
Space Complexity:
• O(n): Space for the hash set.
Code:
# include < iostream >
# include < unordered_set >
# include < vector >
using namespace std ;

int l o n g e s t C o n s e c u t i v e S u b s e q u e n c e ( vector < int > & arr )

39
{
unordered_set < int > elements ( arr . begin () , arr . end () ) ;
int longest = 0;

for ( int num : arr )


{
if ( elements . find ( num - 1) == elements . end () )
{
int currentNum = num ;
int currentStreak = 1;
while ( elements . find ( currentNum + 1) != elements . end () )
{
currentNum ++;
currentStreak ++;
}
longest = max ( longest , currentStreak ) ;
}
}
return longest ;
}

int main ()
{
int n ;
cout << " Enter the number of elements : " ;
cin >> n ;

vector < int > arr ( n ) ;


cout << " Enter the elements : " ;
for ( int i = 0; i < n ; i ++)
cin >> arr [ i ];

int result = l o n g e s t C o n s e c u t i v e S u b s e q u e n c e ( arr ) ;


cout << " Length of the longest consecutive subsequence : " << result << endl ;

return 0;
}

Output 1:
Enter the number of elements: 6
Enter the elements: 100 4 200 1 3 2
Length of the longest consecutive subsequence: 4
Output 2:
Enter the number of elements: 7
Enter the elements: 2 6 1 9 4 3 5
Length of the longest consecutive subsequence: 6

6.4 Check if two arrays are equal or not


Algorithm:

1. Check if the lengths of the two arrays are different. If they are, the arrays are not equal.
2. Use a hash map to count the frequency of each element in the first array.
3. Traverse the second array and decrement the frequency of each element in the hash map:
• If an element is not found or its count goes below zero, the arrays are not equal.

4. After processing the second array, check if all values in the hash map are zero. If they are, the arrays are equal.
5. Return the result.
Time Complexity:

• O(n):
– Building the frequency map takes O(n).

40
– Traversing the second array and checking the map also takes O(n).
Space Complexity:
• O(n): Space for the hash map.
Code:
# include < iostream >
# include < vector >
# include < unordered_map >
using namespace std ;

bool areArray sEqual ( vector < int > & arr1 , vector < int > & arr2 )
{
if ( arr1 . size () != arr2 . size () )
return false ;

unordered_map < int , int > freqMap ;


for ( int num : arr1 )
freqMap [ num ]++;

for ( int num : arr2 )


{
if ( freqMap . find ( num ) == freqMap . end () || freqMap [ num ] == 0)
return false ;
freqMap [ num ] - -;
}
return true ;
}

int main ()
{
int n1 , n2 ;
cout << " Enter the size of the first array : " ;
cin >> n1 ;
vector < int > arr1 ( n1 ) ;
cout << " Enter elements of the first array : " ;
for ( int i = 0; i < n1 ; i ++)
cin >> arr1 [ i ];

cout << " Enter the size of the second array : " ;
cin >> n2 ;
vector < int > arr2 ( n2 ) ;
cout << " Enter elements of the second array : " ;
for ( int i = 0; i < n2 ; i ++)
cin >> arr2 [ i ];

if ( areArray sEqual ( arr1 , arr2 ) )


cout << " The arrays are equal . " << endl ;
else
cout << " The arrays are not equal . " << endl ;

return 0;
}

Output 1:
Enter the size of the first array: 5
Enter elements of the first array: 1 2 3 4 5
Enter the size of the second array: 5
Enter elements of the second array: 5 4 3 2 1
The arrays are equal.
Output 2:
Enter the size of the first array: 4
Enter elements of the first array: 1 2 3 4
Enter the size of the second array: 4
Enter elements of the second array: 1 2 2 4
The arrays are not equal.

41

You might also like