Posts

Merge two sorted linked lists (Amazon SDE)

Problem - Given two sorted linked lists, merge them so that the resulting linked list is also sorted. Approach - Create a linked list with NULL value, Maintain a head and tail pointer to traverse the linked lists. Choose head of the merged linked list by comparing the first nodes of both the linked lists, the one with lowest value gets inside the merged linked list. Move pointer one step forward and repeat. Code-  typedef  node *  temp ; node *  merge_sorted ( temp head1 ,  temp head2 ) {    if ( head1 == NULL )    {      return  head2 ;    }    else   if ( head2 == NULL )    {      return  head1 ;    }      temp mergedhead =  NULL ;   //merged head     if ( head1->data <= head2->data )    {     mergedhead = head1 ;     head1 =...

Find Missing Number (Amazon SDE)

Problem - You are given an array from 1 to n, such that all numbers are present except 'x'.  Find 'x' Approach - We know that the sum of all numbers from 1 to n is n(n+1)/2, If we know this value, then we can easily delete the sum of all the elements except x to find x. Code - #include< bits/stdc++.h > using   namespace  std ; int  main () {    int  n ;  cin >> n ;    int  sum_of_n  =   ( n *( n + 1 ))/ 2 ;    int  arr [ n ];    int  sum_of_arr ;    for ( int  i = 0 ; i < n ; i ++)    {     cin >> arr [ i ];     sum_of_arr += arr [ i ];    }    int  x =  sum_of_arr  -  sum_of_n ;   cout << x ;    return   0 ; }

Finding the Subarrays (Hackerearth)

Image
Finding subarrays can become a cumbersome task to handle if we don't know the right approach for it. In this particular question we will be using a new method.  Pair is used to combine together two values which may be different in type. Pair provides a way to store two heterogeneous objects as a single unit. Such as vector<first attribute, second attribute>. To access these attributes we use keywords 'first' and 'second' Approach - Input values and find total sum of all terms Create a loop and calculate average term by term, use logic ->  sum= first element this_average=sum/elements in the sum SZ= Elements left in array= size-elements in sum other_average=(total-sum)/SZ Use if loop to find whether this_average is bigger than other_average or not. If true, input the (i+1)th and (j+1)th element in the pair, Increment counter by 1 Sort the pair and output it. Code- #include< bits/stdc++.h > using namespace std ; int main () {       ...

Self Balancing Trees (Hackerrank)

Image
An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(right subtree) The balance factor of any node of an AVL tree is in the integer range [-1,+1]. If after any modification in the tree, the balance factor becomes less than −1 or greater than +1, the subtree rooted at this node is unbalanced, and a rotation is needed. Code -  int height(node* root) {     if(root)             return root->ht;     else         return -1; } void rotateright(node* &root) {     node* temp= root->left;     root->left= root->left->right;     temp->right=ro...

Swap Nodes(Algo) (Hackerrank)

Question - A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from the left child of the root node and keep exploring the left subtree until you reach a leaf. When you reach a leaf, back up to its parent, check for a right child and visit it if there is one. If there is not a child, you've explored its left and right subtrees fully. If there is a right child, traverse its left subtree then its right in the same manner. Keep doing this until you have traversed the entire tree. You will only store the values of a node as you visit when one of the following is true: it is the first node visited, the first time visited it is a leaf, should only be visited once...

Grid Challenge (Hackerrank)

There's one thing i realized over the course of these months, given time and practice, you can become good at the things you thought you were not capable or smart enough to crack.  I had flagged this question because i wasn't sure of how to code it and 3 days later i started with this question, all along playing with ideas and somehow, all the test cases passed. Remember kids, If you don't get it in first try, try again, if you fail...give some time and come back to it after some time.  Question- Given a square grid of characters in the range ascii[a-z], rearrange elements of each row alphabetically, ascending. Determine if the columns are also in ascending alphabetical order, top to bottom. Return  YES  if they are or  NO  if they are not. Approach- Sort the elements in the array Create a bool function to check if element in column 1 is lesser than or greater than element in column 2 Implement the bool function over the array Return YES or NO accordingly...

Sherlock and Array (Hackerrank)

Image
Sometimes it's better to stop and first formulate a way to solve a problem before jumping right into it. Why? Well because it gives you more time to better understand a problem and secondly, in some cases even a simpler way to solve a problem.  Remember kids! When solving algorithms, Math is your friend! I realized that a little late into this question and when i did, it was just a 5 min snippet. Question-  Approach - It's quite simple and straight forward.  Instead of dividing array into two halves, getting their sums, checking whether the sums are equal and trying to find out if an element which causes sum to be unequal exist or not, here's a better approach. array - [5,6,8,11] , here we have 5+6=11 in LHS and 11 in RHS with 8 being an extra element. Imagine LHS and RHS as same, ex - x+y+x= sum. i.e 2x= sum-y. Here we just need to check if this equality holds, if it does we print YES and add value to x, else we print NO Code-