0% found this document useful (0 votes)
1K views17 pages

Myntra Interview Questions

The document provides solutions to common interview questions involving data structures and algorithms. It includes: 1. A C program to detect and remove a loop in a linked list. 2. An implementation of quick select to find the kth largest element in an array in O(n) time. 3. A recursive C++ program to check if a number is a palindrome. 4. Methods to find the maximal sum of contiguous and non-contiguous subsequences in an array. 5. A C implementation of heapsort algorithm to sort an array in O(n log n) time.

Uploaded by

SelvamSathappan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views17 pages

Myntra Interview Questions

The document provides solutions to common interview questions involving data structures and algorithms. It includes: 1. A C program to detect and remove a loop in a linked list. 2. An implementation of quick select to find the kth largest element in an array in O(n) time. 3. A recursive C++ program to check if a number is a palindrome. 4. Methods to find the maximal sum of contiguous and non-contiguous subsequences in an array. 5. A C implementation of heapsort algorithm to sort an array in O(n log n) time.

Uploaded by

SelvamSathappan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

INTERVIEW QUESTIONS

1. Write a C program to detect a loop in a linked list and remove


it.
SOLUTION
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct node
{
int data;
struct node* next;
};
/* Function to remove loop. Used by detectAndRemoveLoop() */
void removeLoop(struct node *, struct node *);
/* This function detects and removes loop in the list
If loop was there in the list then it returns 1,
otherwise returns 0 */
int detectAndRemoveLoop(struct node *list)
{
struct node *slow_p = list, *fast_p = list;
while (slow_p && fast_p && fast_p->next)
{
slow_p = slow_p->next;
fast_p = fast_p->next->next;
/* If slow_p and fast_p meet at some point then there
is a loop */
if (slow_p == fast_p)
{
removeLoop(slow_p, list);
/* Return 1 to indicate that loop is found */
return 1;
}

/* Return 0 to indeciate that ther is no loop*/


return 0;
}
/* Function to remove loop.
loop_node --> Pointer to one of the loop nodes
head --> Pointer to the start node of the linked list */
void removeLoop(struct node *loop_node, struct node *head)
{

struct node *ptr1;


struct node *ptr2;
/* Set a pointer to the beging of the Linked List and
move it one by one to find the first node which is
part of the Linked List */
ptr1 = head;
while (1)
{
/* Now start a pointer from loop_node and check if it ever
reaches ptr2 */
ptr2 = loop_node;
while (ptr2->next != loop_node && ptr2->next != ptr1)
ptr2 = ptr2->next;
/* If ptr2 reahced ptr1 then there is a loop. So break the
loop */
if (ptr2->next == ptr1)
break;

/* If ptr2 did't reach ptr1 then try the next node after ptr1 */
ptr1 = ptr1->next;

/* After the end of loop ptr2 is the last node of the loop. So
make next of ptr2 as NULL */
ptr2->next = NULL;

/* Function to print linked list */


void printList(struct node *node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
struct node *newNode(int key)
{
struct node *temp = new struct node;
temp->data = key;
temp->next = NULL;
return temp;
}
/* Drier program to test above function*/
int main()
{
struct node *head = newNode(50);
head->next = newNode(20);
head->next->next = newNode(15);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(10);

/* Create a loop for testing */


head->next->next->next->next->next = head->next->next;
detectAndRemoveLoop(head);
printf("Linked List after removing loop \n");
printList(head);
return 0;
}

2. Find the kth largest element in an array.


SOLUTION (Quick Select Method)
#include<iostream>
#include<climits>
using namespace std;
int partition(int arr[], int l, int 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 = partition(arr, l, r);
// If position is same as k
if (pos-l == k-1)
return arr[pos];
if (pos-l > k-1) // If position is more, recur for left subarray
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;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// Standard partition process of QuickSort(). It considers the last
// element as pivot and moves 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;
}
// Driver program to test above methods
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);
return 0;
}

Output:
K'th smallest element is 5

3. Determine if a given number is a palindrome or not.


SOLUTION
// A recursive C++ program to check whether a given number is
// palindrome or not
#include <stdio.h>
// A function that reurns true only if num contains one digit
int oneDigit(int num)
{
// comparison operation is faster than division operation.
// So using following instead of "return num / 10 == 0;"
return (num >= 0 && num < 10);
}
// A recursive function to find out whether num is palindrome
// or not. Initially, dupNum contains address of a copy of num.
bool isPalUtil(int num, int* dupNum)
{
// Base case (needed for recursion termination): This statement
// mainly compares the first digit with the last digit
if (oneDigit(num))
return (num == (*dupNum) % 10);

//
//
//
if

This is the key line in this method. Note that all recursive
calls have a separate copy of num, but they all share same copy
of *dupNum. We divide num while moving up the recursion tree
(!isPalUtil(num/10, dupNum))
return false;

// The following statements are executed when we move up the


// recursion call tree
*dupNum /= 10;

// At this point, if num%10 contains i'th digit from beiginning,


// then (*dupNum)%10 contains i'th digit from end
return (num % 10 == (*dupNum) % 10);

// The main function that uses recursive function isPalUtil() to


// find out whether num is palindrome or not
int isPal(int num)
{
// If num is negative, make it positive
if (num < 0)
num = -num;
// Create a separate copy of num, so that modifications made
// to address dupNum don't change the input number.
int *dupNum = new int(num); // *dupNum = num

return isPalUtil(num, dupNum);

// Driver program to test above functions


int main()
{
int n = 12321;
isPal(n)? printf("Yes\n"): printf("No\n");
n = 12;
isPal(n)? printf("Yes\n"): printf("No\n");
n = 88;
isPal(n)? printf("Yes\n"): printf("No\n");
n = 8999;
isPal(n)? printf("Yes\n"): printf("No\n");
return 0;
}

Output:
Yes
No

Yes
No

4. Determine the maximal sum of contiguous subsequences in an


array. Also find the maximal sum of non-contiguous subsequences
in the array.
Solution
Maximal contiguous subarray sum
// C++ program to print largest contiguous array sum
#include<iostream>
using namespace std;
int maxSubArraySum(int a[], int size)
{
int max_so_far = 0, max_ending_here = 0;
for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_ending_here < 0)
max_ending_here = 0;
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
}
return max_so_far;
}
/*Driver program to test maxSubArraySum*/
int main()
{
int a[] = {-2, -3, 4, -1, -2, 1, 5, -3};
int n = sizeof(a)/sizeof(a[0]);
int max_sum = maxSubArraySum(a, n);
cout << "Maximum contiguous sum is \n" << max_sum;
return 0;
}

Maximal non-contiguous subarray sum


public int maxsumNonContiguous(int[] array){
/* Empty array */
if(array == null)

return 0;
int arrayLength = array.length;
/* Current maximum sum including the current value */
int sum1 = array[0];
/* Current maximum sum excluding the current value */
int sum2 = 0;
/* Iterate through the array from second element to the end */
for(int i = 1; i < arrayLength; i++){
/* Current maximum sum excluding the current index value */
sum3 = Math.max(sum1,sum2);
/* Move the value of sum3 into sum2 */
sum2 = sum3;
/* Current maximum sum including the current index value */
sum1 = sum2 + array[i];
}
/* Return the maximum of sum1 and sum2 */
return Math.max(sum1, sum2);
}

5. Write a C program to implement heapsort algorithm.


Solution
// C implementation of Heap Sort
#include <stdio.h>
#include <stdlib.h>
// A heap has current size and array of elements
struct MaxHeap
{
int size;
int* array;
};
// A utility function to swap to integers
void swap(int* a, int* b) { int t = *a; *a = *b;

*b = t; }

// The main function to heapify a Max Heap. The function


// assumes that everything under given root (element at
// index idx) is already heapified
void maxHeapify(struct MaxHeap* maxHeap, int idx)
{
int largest = idx; // Initialize largest as root
int left = (idx << 1) + 1; // left = 2*idx + 1
int right = (idx + 1) << 1; // right = 2*idx + 2

// See if left child of root exists and is greater than


// root
if (left < maxHeap->size &&
maxHeap->array[left] > maxHeap->array[largest])
largest = left;
// See if right child of root exists and is greater than
// the largest so far
if (right < maxHeap->size &&
maxHeap->array[right] > maxHeap->array[largest])
largest = right;

// Change root, if needed


if (largest != idx)
{
swap(&maxHeap->array[largest], &maxHeap->array[idx]);
maxHeapify(maxHeap, largest);
}

// A utility function to create a max heap of given capacity


struct MaxHeap* createAndBuildHeap(int *array, int size)
{
int i;
struct MaxHeap* maxHeap =
(struct MaxHeap*) malloc(sizeof(struct MaxHeap));
maxHeap->size = size;
// initialize size of heap
maxHeap->array = array; // Assign address of first element of array

// Start from bottommost and rightmost internal mode and heapify all
// internal modes in bottom up way
for (i = (maxHeap->size - 2) / 2; i >= 0; --i)
maxHeapify(maxHeap, i);
return maxHeap;

// The main function to sort an array of given size


void heapSort(int* array, int size)
{
// Build a heap from the input data.
struct MaxHeap* maxHeap = createAndBuildHeap(array, size);
// Repeat following steps while heap size is greater than 1.
// The last element in max heap will be the minimum element
while (maxHeap->size > 1)
{
// The largest item in Heap is stored at the root. Replace
// it with the last item of the heap followed by reducing the
// size of heap by 1.
swap(&maxHeap->array[0], &maxHeap->array[maxHeap->size - 1]);
--maxHeap->size; // Reduce heap size

// Finally, heapify the root of tree.


maxHeapify(maxHeap, 0);

}
// A utility function to print a given array of given size
void printArray(int* arr, int size)
{
int i;
for (i = 0; i < size; ++i)
printf("%d ", arr[i]);
}
/* Driver program to test above functions */
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int size = sizeof(arr)/sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, size);
heapSort(arr, size);
printf("\nSorted array is \n");
printArray(arr, size);
return 0;
}

6. Provide a solution to the sum of subsets problem.


Solution
// A recursive solution for subset sum problem
#include <stdio.h>
// Returns true if there is a subset of set[] with sun equal to given sum
bool isSubsetSum(int set[], int n, int sum)
{
// Base Cases
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;
// If last element is greater than sum, then ignore it
if (set[n-1] > sum)
return isSubsetSum(set, n-1, sum);
/* else, check if sum can be obtained by any of the following
(a) including the last element
(b) excluding the last element
*/
return isSubsetSum(set, n-1, sum) || isSubsetSum(set, n-1, sum-set[n-1]);
}
// Driver program to test above function

int main()
{
int set[] = {3, 34, 4, 12, 5, 2};
int sum = 9;
int n = sizeof(set)/sizeof(set[0]);
if (isSubsetSum(set, n, sum) == true)
printf("Found a subset with given sum");
else
printf("No subset with given sum");
return 0;
}

7. Given a binary tree, display only the elements in the odd levels
of the tree.
Solution
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.

#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/*Function protoypes*/
void printGivenLevel(struct node* root, int level);
int height(struct node* node);
struct node* newNode(int data);
/* Function to print level order traversal a tree*/
void printLevelOrder(struct node* root)
{
int h = height(root);
int i;
for (i = 1; i <= h; i+=2)
printGivenLevel(root, i);
}
/* Print nodes at a given level */
void printGivenLevel(struct node* root, int level)
{

30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.

if (root == NULL)
return;
if (level == 1)
printf("%d ", root->data);
else if (level > 1)
{
printGivenLevel(root->left, level - 1);
printGivenLevel(root->right, level - 1);
}
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(struct node* node)
{
if (node == NULL)
return 0;
else
{
/* compute the height of each subtree */
int lheight = height(node->left);
int rheight = height(node->right);
/* use the larger one */
if (lheight > rheight)
return (lheight + 1);
else
return (rheight + 1);
}
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*) malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}

73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.

/* Driver program to test above functions*/


int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Level Order traversal of binary tree is \n");
printLevelOrder(root);
return 0;
}

8. Find the nth node from the end of a linked list


SOLUTION
// C program to find n'th node from end using slow and
// fast pointers
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct node
{
int data;
struct node* next;
};
/* Function to get the nth node from the last of a linked list*/
void printNthFromLast(struct node *head, int n)
{
struct node *main_ptr = head;
struct node *ref_ptr = head;
int count = 0;
if(head != NULL)
{
while( count < n )
{
if(ref_ptr == NULL)
{
printf("%d is greater than the no. of "
"nodes in list", n);
return;
}
ref_ptr = ref_ptr->next;

count++;
} /* End of while*/

while(ref_ptr != NULL)
{
main_ptr = main_ptr->next;
ref_ptr = ref_ptr->next;
}
printf("Node no. %d from last is %d ",
n, main_ptr->data);

}
void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref)
= new_node;
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 15);
printNthFromLast(head, 3);
}

9. Reverse a linked list.


SOLUTION
Iterative Solution
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct node
{

int data;
struct node* next;
};
/* Function to reverse the linked list */
static void reverse(struct node** head_ref)
{
struct node* prev
= NULL;
struct node* current = *head_ref;
struct node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
/* Function to push a node */
void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref)
= new_node;
}
/* Function to print linked list */
void printList(struct node *head)
{
struct node *temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}
/* Driver program to test above function*/
int main()
{
/* Start with the empty list */
struct node* head = NULL;
push(&head, 20);

push(&head, 4);
push(&head, 15);
push(&head, 85);
printList(head);
reverse(&head);
printf("\n Reversed Linked list \n");
printList(head);
getchar();
}

Recursive Solution
void recursiveReverse(struct node** head_ref)
{
struct node* first;
struct node* rest;
/* empty list */
if (*head_ref == NULL)
return;
/* suppose first = {1, 2, 3}, rest = {2, 3} */
first = *head_ref;
rest = first->next;
/* List has only one node */
if (rest == NULL)
return;
/* reverse the rest list and put the first element at the end */
recursiveReverse(&rest);
first->next->next = first;
/* tricky step -- see the diagram */
first->next = NULL;
/* fix the head pointer */
*head_ref = rest;
}

10. Given a HTML tag remove the substrings present within <>.
Example:
Input 1: <<i>am> india><
Output: india

Input2: <i rock < india>


Output: none
11. Write a program to find 100!. How will you store such a big
number in a variable and what is its type?
Solution
// C++ program to compute factorial of big numbers
#include<iostream>
using namespace std;
// Maximum number of digits in output
#define MAX 500
int multiply(int x, int res[], int res_size)
// This function finds factorial of large numbers and prints them
void factorial(int n)
{
int res[MAX];
// Initialize result
res[0] = 1;
int res_size = 1;
// Apply simple factorial formula n! = 1 * 2 * 3 * 4...*n
for (int x=2; x<=n; x++)
res_size = multiply(x, res, res_size);

cout << "Factorial of given number is \n";


for (int i=res_size-1; i>=0; i--)
cout << res[i];

// This function multiplies x with the number represented by res[].


// res_size is size of res[] or number of digits in the number represented
// by res[]. This function uses simple school mathematics for multiplication.
// This function may value of res_size and returns the new value of res_size
int multiply(int x, int res[], int res_size)
{
int carry = 0; // Initialize carry
// One by one multiply n with individual digits of res[]
for (int i=0; i<res_size; i++)
{
int prod = res[i] * x + carry;
res[i] = prod % 10; // Store last digit of 'prod' in res[]
carry = prod/10;
// Put rest in carry
}
// Put carry in res and increase result size
while (carry)

res[res_size] = carry%10;
carry = carry/10;
res_size++;

}
return res_size;
}
// Driver program
int main()
{
factorial(100);
return 0;
}

Output:
Factorial of given number is
9332621544394415268169923885626670049071596826438162146859296389
5217599993229915608941463976156518286253697920827223758251185210
916864000000000000000000000000

You might also like