Showing posts with label C++. Show all posts
Showing posts with label C++. Show all posts

Friday, January 25, 2013

Top 30 Programming questions asked in Interview - Java C C++ Answers



JUST RUN THROUGH IT!!!!

Top 30 Programming interview questions

String Programming Interview Questions
String is the primary and probably most common thing you come across on any programming language and so is with any programming interview. There is almost always a question on String whether its related to length or replace but I have always find one or two String programming questions on interviews.
1) Write code to check a String is palindrome or not?
Palindrome are those String whose reverse is equal to original.This can be done by following technique demonstrated in How to reverse String in Java without using API
 
2) Write a method which will remove any given character from a String?
3) Print all permutation of String both iterative and Recursive way?
4) Write a function to find out longest palindrome in a given string?

Some more String related Questions which mostly appear in Java programming interviews:
Difference between String and StringBuffer in Java
Why String is final in Java
How to Split String in java 
Why Char array is preferred over String for storing password?

Programming questions on Array

Array is one of the topics where most of programming questions is asked. There are many and many programming questions on Array and here I have included only some of them which is not very difficult to solve but some of array programming question can be extremely challenging, so well prepare this topic.
5) In an array 1-100 numbers are stored, one number is missing how do you find it?
6) In an array 1-100 exactly one number is duplicate how do you find it?
This article contains a trick to find duplicates in Array using Java programming language
 
7) In an array 1-100 many numbers are duplicates, how do you find it?
trick in this programming questions is by using hashmap or hashtable , we can store number as key and its occurrence as value, if number is already present in hashtable then increment its value or insert value as 1 and later on print all those numbers whose values are more than one.

8)Given two arrays, 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array.
Here is a quick tip to solve this programming question:  put the elements of the second array in the Hashtable and for every element of the first array, check whether it’s present in the hash or not, O/P all those elements from the first array that are not present in the hash table

9) How do you find second highest number in an integer array?


LinkedList Programming Interview Questions

10) How do you find middle element of a linked list in single pass?
To answer this programming question I would say you start with simple solution on which you traverse the LinkedList until you find the tail of linked list where it points to null to find the length of linked list  and then reiterating till middle. After this answer interviewer will ask you find the middle element in single pass and there you can explain that by doing space-time tradeoff you can use two pointers one incrementing one step at a time and other incrementing two step a time, so when first pointer reaches end of linked second pointer will point to the middle element.

11) How do you find 3rd element from last in single pass?
This programming question is similar to above and can be solved by using 2 pointers, start second pointer when first pointer reaches third place.
12) How do you find if there is any loop in singly linked list? How do you find the start of the loop?
This programming question can also be solved using 2 pointers and if you increase one pointer one step at a time and other as two steps at a time they will meet in some point if there is a loop.
13) How do you reverse a singly linked list?


Binary Tree Programming Interview Questions

Binary tree or simply tree is one of favorite topic for most of interviewer and pose real challenge if you struggle with recursion. Programming questions on tree can become increasingly difficult when you think iterative but sometime can be very easy if you come with recursive solution.
14) How do you find depth of binary tree?
15) Write code to print InOrder traversal of a tree?
16) Print out all leaf node of a binary tree?

 

Programming questions on searching and sorting

I have only included two programming questions related to searching and sorting but there are more can be finding on google. Purpose of these programming questions is to see whether programmer is familiar with essential search and sort mechanism or not.
17) Write a program to sort numbers using quick sort?
18) Write a program to implement binary search algorithm
19) How do you sort Java object using Comparator?
This is another Java specific programming questions and you can check how to sort Object using Comparator and Comparable for answer.


Programming questions on numbers

Most of the programming questions are based on numbers and these are the ones which most of us did on college level and mind you they still has value I have seen programmers with experience of 3 years struggle with these programming questions and doesn’t solve it some time and take a lot of time which simply shows that they are not in programming in there day to day work.
19) Write code to check whether a no is power of two or not?
20) Write a program to check whether a no is palindrome or not?
check out this post which shows how to reverse number in Java and can be used to find if its palindrome or not.
 
21) Write code to check whether a no is Armstrong no or not
Here is a Java program to find Armstrong number, you can use same logic to write code in any other programming language like C and C++.
 
22) Write a program to find all prime number up to a given numbers?
Here is another Java program to find prime numbers and print them. By using logic demonstrated in this program; you can write similar program in C and C++.
 
23) Write function to compute Nth Fibonacci number? Both iterative and recursive?
Check this Java program to print Fibonacci Series using recursion and iteration.

General Programming Interview Questions

In this category of programming questions I have put questions which are not fit into any data structure but presents a real life problem and you need to provide solution. These programming questions are sometime based on problems faced by developer itself. I have not included many Software design related programming question which I have shared on Top 20 software design questions and answers; you can also check that.
24) Write a program to find out if two rectangles R1 and R2 are overlapping?
35) You need to write a function to climb n steps you can climb either 1 step at a time or 2 steps a time, write a function to return number of ways to climb a ladder with n step.
26) Write code for Generate Random No in a range from min to max?
27) Write program for word-wrap which should work on any screen size?
28) Design an algorithm to find the frequency of occurrence of a word in an article?
29) Write a program to implement blocking queue in Java?
30) Write a program for producer-consumer problem?
This article solves producer consumer problem using BlockingQueue in Java. You can refer it to answer this question.

Tips on answering programming questions

1. If Interviewer asks you to write function then make sure you do some necessary check for bad input e.g. null check or empty check. Most of the time programmer forgets to test for not null, empty, less than 1, greater than 1 or zero input.
2. If you write iterative version of function then Interviewer may ask you to write recursive version or vice-versa so be prepare for that.
3. If you write a recursive function then Interviewer will ask to optimize it, even in case of Iterative version. So remember that you can optimize recursive function by Memorization (caching already calculated value) and by applying some space/time tradeoff principle. For example recursive version of Fibonacci series has O(n2) which can be reduced to O(n) using Memoziation.
4. Interviewer may ask you to calculate Order of complexity for best and worst case of any method so be prepared.
5. Most of the time Interviewer ask how to fix a problem as follow-up question e.g. he will ask how do you find deadlock and then how to fix deadlock in java etc.

Friday, January 4, 2013

mergge sort in C

Merge sort is a divide and conquer algorithm. It is an O(n log n) comparison-based sorting algorithm. Most implementations produce a stable sort, meaning that the implementation preserves the input order of equal elements in the sorted output.

Conceptually, a merge sort works as follows
  1. If the list is of length 0 or 1, then it is already sorted. Otherwise:
  2. Divide the unsorted list into two sublists of about half the size.
  3. Sort each sublist recursively by re-applying the merge sort.
  4. Merge the two sublists back into one sorted list

Source code of simple merge sort implementation using array in ascending order in c programming language

#include<stdio.h>
#define MAX 50

void mergeSort(int arr[],int low,int mid,int high);
void partition(int arr[],int low,int high);

int main(){
   
    int merge[MAX],i,n;

    printf("Enter the total number of elements: ");
    scanf("%d",&n);

    printf("Enter the elements which to be sort: ");
    for(i=0;i<n;i++){
         scanf("%d",&merge[i]);
    }

    partition(merge,0,n-1);

    printf("After merge sorting elements are: ");
    for(i=0;i<n;i++){
         printf("%d ",merge[i]);
    }

   return 0;
}

void partition(int arr[],int low,int high){

    int mid;

    if(low<high){
         mid=(low+high)/2;
         partition(arr,low,mid);
         partition(arr,mid+1,high);
         mergeSort(arr,low,mid,high);
    }
}

void mergeSort(int arr[],int low,int mid,int high){

    int i,m,k,l,temp[MAX];

    l=low;
    i=low;
    m=mid+1;

    while((l<=mid)&&(m<=high)){

         if(arr[l]<=arr[m]){
             temp[i]=arr[l];
             l++;
         }
         else{
             temp[i]=arr[m];
             m++;
         }
         i++;
    }

    if(l>mid){
         for(k=m;k<=high;k++){
             temp[i]=arr[k];
             i++;
         }
    }
    else{
         for(k=l;k<=mid;k++){
             temp[i]=arr[k];
             i++;
         }
    }
   
    for(k=low;k<=high;k++){
         arr[k]=temp[k];
    }
}


Sample output:

Enter the total number of elements: 5
Enter the elements which to be sort: 2 5 0 9 1
After merge sorting elements are: 0 1 2 5 9

Insertion sort in C


Source code of simple insertion sort implementation using array in ascending order in c programming language

#include<stdio.h>
int main(){

  int i,j,s,temp,a[20];

  printf("Enter total elements: ");
  scanf("%d",&s);

  printf("Enter %d elements: ",s);
  for(i=0;i<s;i++)
      scanf("%d",&a[i]);

  for(i=1;i<s;i++){
      temp=a[i];
      j=i-1;
      while((temp<a[j])&&(j>=0)){
      a[j+1]=a[j];
          j=j-1;
      }
      a[j+1]=temp;
  }

  printf("After sorting: ");
  for(i=0;i<s;i++)
      printf(" %d",a[i]);

  return 0;
}

Output:
Enter total elements: 5
Enter 5 elements: 3 7 9 0 2
After sorting:  0 2 3 7 9

Quicksort: simple code for quick sort ...


public class Quicksort {
  
    public static void main(String[] args) {
        int arr[]=new int[]{3,4,2,5,2,7,8,9,1,6};
        quicksort(arr,0,arr.length-1);
        for(int i=0;i<arr.length-1;i++){
            System.out.println(arr[i]);
        }
    }
    static void quicksort(int x[],int first,int last){
        int pivot,j,temp,i;

         if(first<last){
             pivot=first;
             i=first;
             j=last;

             while(i<j){
                 while(x[i]<=x[pivot]&&i<last)
                     i++;
                 while(x[j]>x[pivot])
                     j--;
                 if(i<j){
                     temp=x[i];
                      x[i]=x[j];
                      x[j]=temp;
                 }
             }

             temp=x[pivot];
             x[pivot]=x[j];
             x[j]=temp;
             quicksort(x,first,j-1);
             quicksort(x,j+1,last);
         }
        }

}

pragma in C language


Each implementation of C and C++ supports some features unique to its host machine or
operating system. Some programs, for instance, need to exercise precise control over the
memory areas where data is placed or to control the way certain functions receive
parameters. The #pragma directives offer a way for each compiler to offer machine- and
operating system-specific features while retaining overall compatibility with the C and
C++ languages. Pragmas are machine- or operating system-specific by definition, and are usually different for every compiler.

height of binary tree BST...


int maxDepth(struct node* node)
{
if (node==NULL)
return 0;
else
{
/* compute the depth of each subtree */
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
/* use the larger one */
if (lDepth > rDepth)
return(lDepth+1);
else return(rDepth+1);
}
}

Wednesday, January 2, 2013

what is the difference between #define and typedef


Q1 - what is the difference between #define and typedef
defines are handled by a preprocessor (a program run before the actual c compiler) which
works like replace all in you editor.
Typedef is handled by the c compiler itself, and is an actual definition of a new type.
Answer
The distinction given between #define and typedef has one significant error: typedef does
not in fact create a new type. According to Kernighan & Richie, the authors of the
authoritative and universally acclaimed book, "The C Programming Language":
It must be emphasized that a typedef declaration does not create a new type in any sense;
it merely adds a new name for some existing type. Nor are there any new semantics:
variables declared this way have exactly the same properties as variables whose
declarations are spelled out explicitly. In effect, typedef is like #define, except that
since it is interpreted by the compiler, it can cope with textual substitutions that are
beyond the capabilities of the preprocessor.
Answer
There are some more subtleties though. The type defined with a typedef is exactly like
its counterpart as far as its type declaring power is concerned BUT it cannot be modified
like its counterpart. For example, let's say you define a synonim for the int type with:
typedef int MYINT
Now you can declare an int variable either with
int a;
or
MYINT a;
But you cannot declare an unsigned int (using the unsigned modifier) with
unsigned MYINT a;
although
unsigned int a;
would be perfectly acceptable.
some things can be done with typedef that cannot be done with define.
Examples:
Code:
typedef int* int_p1;
int_p1 a, b, c; // a, b, and c are all int pointers.
#define int_p2 int*
int_p2 a, b, c; // only the first is a pointer!

Creating mirror of BST