Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Sunday, 24 March 2019

The Interview Question Today#8(3-3-19)


Question:

Given a set of n types of Cuboid, find the maximum height that can be reached stacking instances of this Cuboid

Rules:

·        A Cuboid can be stacked on top of another box only if the dimensions of the 2D base of the lower Cuboid are each strictly larger than those of the 2D base of the higher Cuboid.

·        The Cuboid can be rotated so that any side functions as its base.

·        It is allowable to use multiple instances of the same type of Cuboid.

Example:

n=3

dimensions(l,b,h)
Cuboid 1 - (1,2,3)
Cuboid 2 - (2,3,4)
Cuboid 3 - (3,4,5)

Expected result=15

(Stacking from top to bottom
1,2,3
2,3,4
3,4,5
4,5,3   height=3+4+5+3=15)

Solution:

Approach:

·        initialize new array of boxes of length n*3 which will store all three rotations of box.
·        sort the array in decreasing order of area of boxes
·        initialize new array maxHeight of length n*3 which will store the max height achivable by having box i at the top
·        now the problem is same as LIS with following optimal substructure property.
·        maxHeight[i] = { Max ( maxHeight[j] ) + height(i) } where j < i and width(j) > width(i) and depth(j) > depth(i). If there is no such j then maxHeight[i] = height(i)
·        Iterate through array maxHeight and return max element from it.



Java Program:

import java.util.*;
public class SolutionBoxStacking {
static class Box implements Comparable<Box>
{
int height, width, depth, area;
Box(int h, int w, int d)
{
this.height = h;
this.width = w;
this.depth = d;
this.area = width * depth;
}
//helper function to sort boxes according to their area
@Override
public int compareTo(Box b)
{
return b.area-this.area;
}
}
static int getMaxHeight(int n, Box[] arr)
{
//array to store all rotations of the boxes with original boxes
Box []boxes = new Box[n*3];
// generate all three rotations of the boxes
for(int i = 0;i<n;i++)
{
Box curr = arr[i];
boxes[i*3] = new Box(curr.height,Math.min(curr.width, curr.depth),Math.max(curr.width, curr.depth));
boxes[i*3 + 1] = new Box(curr.width, Math.min(curr.height, curr.depth), Math.max(curr.height, curr.depth));
boxes[i*3 + 2] = new Box(curr.depth, Math.min(curr.height, curr.width), Math.max(curr.height, curr.width));
}
Arrays.sort(boxes);
n *= 3;
//initialize array to store the achievable max height by having box i at the top of the stack
int maxHeight[] = new int[n];
for(int i = 0;i<n;i++) maxHeight[i] = boxes[i].height;
//iterate through all the boxes and update maxHeight using dp
for(int i = 0;i<n;i++)
{
Box curr = boxes[i];
int val = 0;
for(int j=0;j<i;j++)
{
Box temp = boxes[j];
if(temp.width > curr.width && temp.depth > curr.depth)
val = Math.max(val, maxHeight[j]);
}
maxHeight[i] += val;
}
//extract the max value from maxHeight and return
int max = -1;
for(int i = 0;i<n;i++) max = Math.max(max, maxHeight[i]);
return max;
}
public static void main(String[] args)
{
System.out.println("Enter the number of cubiod u have");
Scanner s = new Scanner(System.in);
int n = s.nextInt();
Box arr[] = new Box[n];

for(int i = 0;i<n;i++) {
System.out.println("Enter the length breath height of cubiod"+(i+1));
int h = s.nextInt();
int w = s.nextInt();
int d = s.nextInt();
arr[i] = new Box(h,w,d);
}
System.out.print("Maximum height:");
System.out.println(getMaxHeight(n, arr));
}
}

Output:

Enter the number of cubiod u have
4
Enter the length breath height of cubiod1
1
2
3
Enter the length breath height of cubiod2
2
3
4
Enter the length breath height of cubiod3
3
4
5
Enter the length breath height of cubiod4
4
5
6

Maximum height:22

The Interview Question Today#7(2-3-19)

Question:
The algorithm to find the contiguous sub-array with the maximum sum, for a given array of positive and negative numbers. (Kadane’s Algorithm)



Example:

Input: Array= {-2, -5, 6, -2, -3, 1, 5, -6}

Output: The maximum subarray sum is 7 

Solution:

Approach:
Initialize:
    max_so_far = 0
    max_ending_here = 0

Loop for each element of the array
  (a) max_ending_here = max_ending_here + a[i]
  (b) if(max_ending_here < 0)
            max_ending_here = 0
  (c) if(max_so_far < max_ending_here)
            max_so_far = max_ending_here
        
return max_so_far
C Program:
#include<stdio.h>

// Function to find contiguous sub-array with the largest sum
// in given set of integers
int kadane(int arr[], int n)
{

int max_so_far = 0;

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

max_ending_here = max_ending_here + arr[i];
 if(max_ending_here>0){
max_ending_here =max_ending_here;
 }
 else{
    max_ending_here=0;
 }
 if(max_so_far<max_ending_here)
{
    max_so_far=max_ending_here;
}
}
return max_so_far;
}

int main()
{
int arr[100],n,i;
printf("Enter the number elements u wanted insert");
scanf("%d",&n);
printf("Enter the elements\n");
for(i=0;i<n;i++){
        scanf("%d",&arr[i]);
}

printf("The sum of contiguous sub-array with the largest sum is %d",kadane(arr, n));

return 0;
}
Output:
Enter the number elements u wanted insert5
Enter the elements
-2
-1
6
4
-3
The sum of contiguous sub-array with the largest sum is 10


The Interview Question Today#6(1-3-19)

Question:
The algorithm to find the minimum number of platforms required for the railway station so that no train waits according to arrival and departure time
Example:
Input:  arr[]  = {9:00,  9:40, 9:50,  11:00, 15:00, 18:00}
           dep[]  = {9:10, 12:00, 11:20, 11:30, 19:00, 20:00}

Output: 3

Approach:
  1. Sort both arrival(arr) and departure(dep) arrays.
  2. Compare the current element in arrival and departure array and pick smaller one among both.
  3. If the element is pick up from arrival array then increment platform_needed.
  4. If the element is pick up from departure array then decrement platform_needed.
  5. While performing the above steps, we need a track count of maximum value reached for platform_needed.
  6. In the end, we will return the maximum value reached for platform_needed.


C program:
#include<stdio.h>

    void main()
{

int arr[100];
int dep[100];
int n=1,i=0;
while(n!=0){
printf("Enter the train arrival & departure time(format-:12:30=1230 in 24 hrs scale\n");
        scanf("%d %d",&arr[i],&dep[i]);
        i++;
        printf("Enter zero if all train information is feed \n ");
        scanf("%d",&n);
}

printf("Minimum platforms needed:%d",findPlatformsRequiredForStation(arr,dep,i-1));
}

int findPlatformsRequiredForStation(int arr[], int dep[], int n)
{
int platform_needed = 0, maxPlatforms = 0;
int k,m;
double swap;
for(k=0;k<n;k++)
    {
        for(m=0;m<n;m++)
        {
            if(arr[k]<arr[m])
            {
                swap=arr[k];
                arr[k]=arr[m];
                arr[m]=swap;
            }

        }

    }
for(k=0;k<n;k++)
    {
        for(m=0;m<n;m++)
        {

            if(dep[k]<dep[m])
            {
                swap=dep[k];
                dep[k]=dep[m];
                dep[m]=swap;
            }

        }

    }
     int i = 0, j = 0;

while (i < n && j < n)
{
if (arr[i] < dep[j])
{
platform_needed++;
i++;
if (platform_needed > maxPlatforms)
maxPlatforms = platform_needed;
}
else
{
platform_needed--;
j++;
}
}
return maxPlatforms;
}
Output:
Enter the train arrival & departure time(format-:12:30=1230 in 24 hrs scale
200
230
Enter zero if all train information is feed
 210
Enter the train arrival & departure time(format-:12:30=1230 in 24 hrs scale
210
320
Enter zero if all train information is feed
 1
Enter the train arrival & departure time(format-:12:30=1230 in 24 hrs scale
300
340
Enter zero if all train information is feed
 1
Enter the train arrival & departure time(format-:12:30=1230 in 24 hrs scale
320
400
Enter zero if all train information is feed
 3
Enter the train arrival & departure time(format-:12:30=1230 in 24 hrs scale
350
430
Enter zero if all train information is feed
 5
Enter the train arrival & departure time(format-:12:30=1230 in 24 hrs scale
500
520
Enter zero if all train information is feed
 0
Minimum platforms needed:2

The Interview Question Today#5(28-02-19)

Question: 

Find the length of the longest palindrome subsequence.

Example:
 Input string: qwertykeyppyeky

 Output String: ykeyppyeky

  Length is: 10

Solution:

Approach:

We maintain a int table[n][n] that is filled in bottom up manner. The value of table[i][j] is 1(true), if the substring is palindrome, otherwise 0(false). To calculate table[i][j], we first check the value of table[i+1][j-1], if the value is 1(true) and str[i] is same as str[j], then we make table[i][j] 1(true). Otherwise, the value of table[i][j] is made 0(false).

C program:

#include <stdio.h>
#include <string.h>
// A utility function to print a substring
void printSubStr( char str[], int low, int high )
{int i;
    for( i = low; i <= high; ++i )
        printf("%c", str[i]); }
// This function prints the longest palindrome substring of str[].
// It also returns the length of the longest palindrome
int longestPalSubstr( char str[] )
{
    int i,k,n = strlen( str ); // get length of input string

    // table[i][j] will be false(0) if substring str[i..j] is not palindrome.
    // Else table[i][j] will be true(1)
    int table[n][n];
    memset(table, 0, sizeof(table));

    // All substrings of length 1 are palindromes
    int maxLength = 1;
    for ( i = 0; i < n; ++i)
        table[i][i] =1;

    // check for sub-string of length 2.
    int start = 0;
    for (i = 0; i < n-1; ++i)
    {
        if (str[i] == str[i+1])
        {
            table[i][i+1] =1;
            start = i;
            maxLength = 2;
        }
    }

    // Check for lengths greater than 2. k is length of substring
    for ( k = 3; k <= n; ++k)
    {
        // Fix the starting index
        for ( i = 0; i < n-k+1 ; ++i)
        {
            // Get the ending index of substring from
            // starting index i and length k
            int j = i + k - 1;

            // checking for sub-string from ith index to
            // jth index if str[i+1] to str[j-1] is palindrome
            if (table[i+1][j-1] && str[i] == str[j])
            {
                table[i][j] =1;

                if (k > maxLength)
                {
                    start = i;
                    maxLength = k;
           }
            }      }    }

    printf("Longest palindrome substring is: ");
    printSubStr( str, start, start + maxLength - 1 );

    return maxLength;
}

int main()
{
    char str[100];
    printf("Enter the String\n");
    scanf("%s",str);
    printf("\nLength is: %d\n", longestPalSubstr( str ) );
    return 0;
}

Output:
Enter the String
Qwertykeyppyeky
Longest palindrome substring is: ykeyppyeky

Length is: 10

The Interview Question Today#4(27-2-19)

Question:

Compute the sum of digits in all number from 1 to n.

Example:

Input: n = 10

Output:
Enter the Upper Limit 10
Sum of digits in numbers from 1 to 10 is 46


Solution:

Approach:

The solution is to go through every number x from 1 to n, and compute sum in x by traversing all digits of x. 

C program:


#include<stdio.h>
int sumOfDigits(int );

int sumOfDigitsFrom1ToN(int n)
{
    int result = 0; // initialize result
int x;
    for ( x = 1; x <= n; x++)
        result += sumOfDigits(x);

    return result;
}

int sumOfDigits(int x)
{
    int sum = 0;
    while (x != 0)
    {
        sum += x %10;
        x   = x /10;
    }
    return sum;
}

int main()
{
    int n;
    printf("Enter the Upper Limit");
    scanf("%d",&n);
    printf("Sum of digits in numbers from 1 to %d is %d",n,sumOfDigitsFrom1ToN(n));
    return 0;

}

Output:

Enter the Upper Limit 10

Sum of digits in numbers from 1 to 10 is 46

The Interview Question Today#3 (26-2-19)

Question:

Print all permutations of a given string.

Example:

Input string: ABC.

Output: ABC ACB BAC BCA CBA CAB
No of String=6

Solution:

Approach:

Begin
   if left = right, then
      display str
   else
      for i := left to right, do
         swap str[left] and str[i]
         stringPermutation(str, left+1, right)
         swap str[left] and str[i]             //for backtrack
      done
End

C program:

#include <stdio.h>
#include <string.h>
int count=0;
/* Function to swap values at two pointers */
void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;

}

/* Function to print permutations of string*/
void permute(char *a, int l, int r)
{
   int i;
   if (l == r){
           printf("%d) %s\n",count+1,a);
         count++;
         }
   else
   {
       for (i = l; i <= r; i++)       {
          swap((a+l), (a+i));
          permute(a, l+1, r);
          swap((a+l), (a+i)); //backtrack
       }
   }
}

int main()
{
    char str[100];
    printf("Enter the String ");
    scanf("%s",str);
    int n = strlen(str);
    permute(str, 0, n-1);
    printf("Total number of Strings possible from String:%s =%d",str,count);
    return 0;
}


Output:

Enter the String qwer
1) qwer
2) qwre
3) qewr
4) qerw
5) qrew
6) qrwe
7) wqer
8) wqre
9) weqr
10) werq
11) wreq
12) wrqe
13) ewqr
14) ewrq
15) eqwr
16) eqrw
17) erqw
18) erwq
19) rweq
20) rwqe
21) rewq
22) reqw
23) rqew
24) rqwe

Total number of Strings possible from String:qwer = 24

The Interview Question Today#2 (25-2-19)

Question:

Find the number of triangles that can be formed with three different array elements as three sides of triangles, for a given unsorted array of n elements.

Example:

Input : [5, 4, 3, 1, 2,6,8,7,9]
Output: Yes
Sides of the possible triangle are <1,2,3>,<2,3,4>,<3,4,5>,<4,5,6>,<5,6,7>,<6,7,8>.

Solution:

Approach:

1. Sort the array in increasing order.

2. Initialize
   i = 0;      // First Element
   j = 1;      // Second Element
   count = 0;  // Number of triangles

3. WHILE (i<n-2)      
     k = j+1;      
     move k forward until arr[k] becomes > (arr[i] + arr[j]) or k               moves out of bound
     count = count +1
     increment j
     if j is at end of array
       increment i and set j=i+1

4. Print count.


C program:

// C program to find if it is possible to form a
// triangle from array values and Display it and count it.
#include <stdio.h>

// Method prints possible triangle when array values
// are taken as sides
int isPossibleTriangle(int arr[],int N)
{
    int i,j,swap,flag=0,count=0;
    // If number of elements are less than 3, then no
    // triangle is possible
    if (N < 3)
    return 0;

    // first sort the array
    for(i=0;i<N;i++)
    {
        for(j=i+1;j<N;j++)
        {
            if(arr[i]>arr[j])
            {
                swap=arr[j];
                arr[j]=arr[i];
                arr[i]=swap;
            }
        }

    }

    // loop for all 3
    // consecutive triplets
    for ( i = 0; i < N - 2; i++)

        // If triplet satisfies
        // triangle condition that a+b>c

        if (arr[i] + arr[i + 1] > arr[i + 2])
        {
            printf("<%d,%d,%d>\n",i,i+1,i+2);
            count++;
            }
            return count;
}

int main()
{
    int arr[] = {5, 4, 3, 1, 2,6,8,7,9};
    int N = sizeof(arr) / sizeof(int);

    int a=isPossibleTriangle(arr, N);
     if(a>1)
     printf("Yes: No of triangle that can formed=%d",a);
     else
     printf("No");
    return 0;
}

Output:

<1,2,3>
<2,3,4>
<3,4,5>
<4,5,6>
<5,6,7>
<6,7,8>
Yes: No of triangle that can formed=6





The Interview Question Today#1 (24-2-19)

Question:

Find Minimum number that cannot be formed by Sum of any subset of an array
Input: A Sorted Array
Output: The smallest number which cannot be formed by any subset of an array
Example:
If Array[]={1,2,3,4,5};
Then the smallest number:16.


Solution:

      Approach/Method:

1.      Take a variable small and initialize it to 1
2.      Now Compare small with array current location (starts              with  0 index)
·    if it is not present our answer is small
·    else add array current location value to the small variable and  increment the location And jump back to step 2 Do is till u get smallest value.
3.      Example: Array[]={1,2,3,4,5}
i=0, array [0] =1, small=1, array [0] <=small (1<=1) => small=small+array [0] = 1+1=2
i++,i=1, array[1]=2, small=2, array[1] <=small (2<=2) => small= small+ array [1]= 2+2=4
i++,i=2, array[2]=3, small=4, array[2] <=small (3<=4) => small= small+ array [2]= 4+3=7
i++,i=3, array[3]=4, small=7, array[3] <=small (4<=7) => small= small+ array [3]= 7+4=11
i++,i=4,array[4]=5,small=11,array[4]<=small(5<=11)=>small=small+array[4]=11+5=16
small=16.

C program:

// C program to find the smallest positive value that cannot be
// represented as sum of subsets of a given sorted array

#include<stdio.h>
int getsmallest(int arr[], int n)
{
   int small = 1,i;
   for (i = 0; i < n; i++)
        if( arr[i] <= small)
       small = small + arr[i];
   return small;
}
int main()
{
   int arr[100],n,i;
   printf("Enter the no of elements u want to insert\n");
   scanf("%d",&n);
   printf("enter the elements in ascending order\n");
   for(i=0;i<n;i++){
    scanf("%d",&arr[i]);
   }
    printf("Smallest Element=%d",getsmallest(arr,n));
   return 0;
}

Output:

Enter the no of elements u want to insert
5
enter the elements in ascending order
1
2
3
4
5

Smallest Element=16

Aptitude Hack#29(24-3-19)

Question:
On selling 17 balls at Rs. 720, there is a loss equal to the cost price of 5 balls. The cost price of a ball is:
A) Rs. 45
B) Rs.50
C) Rs. 55
D) Rs. 60

Saturday, 23 March 2019

Aptitude Hack#28(23-3-19)

Question:
Excluding stoppages, the speed of a bus is 54 kmph and including stoppages, it is 45 kmph. For how many minutes does the bus stop per hour?
A) 9
B) 10
C) 12
D) 20


Friday, 22 March 2019

Aptitude Hack#27(22-3-19)

Question:
A can lay railway track between two given stations in 16days and B can do the Same job in 12 days. With the help of C, they did the job in 4 days only. Then, C alone can do the job in:
A. 12 days
B. 11 days
C.48/5 days
D.10 days

Thursday, 21 March 2019

Aptitude Hack#26(21-3-19)

Question:
The age of a father 10 years ago was thrice the age of his son.10 years hence, the father’s age will be twice that of his son. The ratio of their present ages is?
A) 5:3
B) 3:2
C) 7:3
D) 10:7

Wednesday, 20 March 2019

Aptitude Hack#25(20-3-19)

Question:
Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After a further 8 years, how many times would he be of Sunil's age?
A. 4 times
B. 5 times
C. 2 times
D. 3 times


Tuesday, 19 March 2019

Aptitude Hack#24(19-3-19)

Question:
A mixture of 85 kg contains milk and water in the ratio 27: 7. How much more water is to be added to get a new mixture containing milk and water in the ratio 3:1?

A) 5 kg     
B)6.5 kg       
C) 7.5 kg  
D) 8 kg
  

Monday, 18 March 2019

Aptitude Hack#23(18-3-19)

Question:
A man has Rs.480 in the denominations of one-rupee notes, five-rupee notes and ten-rupee notes. The number of notes of each denomination is equal. What is the total number of notes that he has?

A. 45
B. 60
C. 75
D. 90

Sunday, 17 March 2019

Aptitude Hack#22(17-3-19)

Question:
An error of 2% in excess is made while measuring the side of a square. The percentage of error in the calculated area of the square is:

A. 2%
B. 2.02%
C. 4%
D. 4.04%



Saturday, 16 March 2019

Aptitude Hack#21(16-3-19)

Question:
A and B take part in 100 m race. A runs at 5 kmph. A gives B a start of 8 m and still beats him by 8 seconds. The speed of B is:

A. 5.15 kmph
B. 4.14 kmph
C. 4.25 kmph
D. 4.40 kmph


Friday, 15 March 2019

Aptitude Hack#20(15-3-19)

Question:

Mr. Nagaraj got married 12 years ago to Parvathy and she becomes the 7th member of the family. Today his mother died And Mrs. Parvathy gave birth to a baby. The Average age of Nagaraj Family at the time of his marriage is the same as of today. What is the age of his mother when she died?
A) 54
B) 60
C) 72
D) 84
|

Thursday, 14 March 2019

Aptitude Hack#19(14-3-19)

Question:
A sum of money amounts to Rs. 9800 after 5 years and Rs. 12005 after 8 years at the same rate of simple interest. The rate of interest per annum is:

A. 5%
B. 8%
C. 12%
D. 15%

Wednesday, 13 March 2019

Aptitude Hack#18(13-3-19)

Question:
A train 125 m long passes a man, running at 5 km/hr in the same direction in which the train is going, in 10 seconds. The speed of the train is:

A. 45 km/hr
B. 50 km/hr
C. 54 km/hr
D. 55 km/hr