Wednesday, July 25, 2012

Kernel Types

Discuss about the following types of kernels used for different operating system architechtures

1.Monolithic Kernel

2.Micro Kernel

3.Exo Kernel

Useful Links:

http://en.wikipedia.org/wiki/Monolithic_kernel

Monday, July 23, 2012

Print the integers that are greater than the average of that array

Given an array of integers print the integers that are greater than the average of that array

DNA Sequence Pattern Match/ String Search Problem

The DNA double helix consists of a long strand of four bases: adenine (abbreviated A), cytosine (C), guanine (G) and thymine (T). Thus, it can be represented as a long string containing the characters A, C, G, and T. The field of bio-informatics involves storing and searching of DNA sequence data. What is a good data structure to facilitate storage and string match/search operation on this kind of data? Write a class that stores the DNA sequence and implement a method which takes another DNA sub-sequence and returns the position of this sub-sequence in the first DNA sequence.

There are several linear time string matching algorithms. See http://en.wikipedia.org/wiki/String_searching_algorithm for a list of such algorithms.
Often a data structure called Suffix Tree or PAT tree is used in DNA sequencing applications in the field of Bio-informatics. A Suffix tree data structure facilitates string match/search in O(m) complexity, where m is the length of the sub-string. It takes an initial O(n) time required to build the suffix tree.
One concern with suffix tree is the high amount of space/memory needed. But, with a small alphabet ( only 4 characters in the DNA search problem ) , its not too bad. More over, there are some advanced techniques that can be used to further reduce the storage requirements.
A thorough treatment of suffix trees can be found here. 

Store a stream of numbers along with the counts

Given a stream of numbers, suggest a data structure to store the numbers in the stream along with their number of occurrences.

Solution: Before solving any problem make sure you lay down all the assumptions you are making and validate them with the interviewer.

Assumptions here:
  • The numbers are 32 bit integers.
  • The size of the set (cardinality) is very small compared to the possible number of integers (lets say 100 numbers)
  • Design for faster lookup
Since the size of the set is small, a data structure like an array of integers 2^32 in size will be a waste of space, even though the insert and lookup is going to be O(1). A hashtable would have a similar issue. A linked list would solve the memory issue by storing only the numbers that were present in the set but the look up suffers ( O(n) ). We would like the look up to be better than O(n).

So we've looked at an array, linked list, hashtable and none seem to solve it. Linked list looked promising but look up was O(n). Can we improve the lookup in a linked list? First of all, whats better than O(n)? O(log n), right? What data structure does that remind you of? A Binary Search Tree!!

Lets explore if we can utilize a Binary Search Tree here. So, if we started inserting numbers in a Binary Search Tree, each insertion would cost us O(log n). There are n number of insertions, so inserting all the numbers is going to be O(n log n). When we insert each number we also store the count at the node. So if a number is inserted for the first time we create a node in the tree and store the number itself and also the count (1 for the 1st occurrence). Any subsequent occurrence will not create a new node. Instead, we'll find the corresponding node and just update the count. So by the time we are done processing all the numbers we'll have a nice binary search tree with all the numbers and their occurrences.

Now the comes the look up part. Look up in a Binary Search Tree is O(log n). Any time we are presented a number and asked for the number of occurrences we can look up (or not ) the number and get its count.

If we were to design for faster insert we'd be better off using an unsorted linked list. Insert would have been O(1) (just insert at the end) and look up would be O(n). So for a small n this wouldn't be terribly bad.

Note: There is another data structure called the skip list which is a layered linked list type data structure which has O(log n) look up and insert. The linked list in the skip list is a sorted list and that would make our insert O(n log n).

Question 2:
Find Duplicates in a million number

Sunday, July 15, 2012

Union and Intersection of two Linked Lists

Given two Linked Lists, create union and intersection lists that contain union and intersection of the elements present in the given lists. Order of elements in output lists doesn't matter.
Example:
Input:
   List1: 10->15->4->20
   lsit2:  8->4->2->10
Output:
   Intersection List: 4->10
   Union List: 2->8->20->4->15->10
http://www.geeksforgeeks.org/union-and-intersection-of-two-linked-lists/

Intersection:  Using Hashset
But of course you can do much better.
Now, if you have a HashSet (or other near-O(1)) data structure available then this is what you can do:
Iterate over one list. Add each element to the set. Iterate over the second list. If the element is in the set then add it to the result list.
Solution: O(n)

Intersection of two sorted Lists:
http://www.geeksforgeeks.org/intersection-of-two-sorted-linked-lists/

List getIntersection(int[] a, int[] b){
    int apos = 0, bpos = 0
    List intersection
    while apos < a.length && bpos < b.length:
        if a[apos] == b[bpos]:
            intersection.add(a[apos])
            apos++, bpos++
        else:
            if a[apos] < b[bpos]:
                apos++
            else:
                bpos++
    return intersection 
}

Efficiency is O(m + n).

C Operator Questions

#include<stdio.h>
int main(){
    float a=0.7;d
    if(a<0.7){
         printf("C");
    }
    else{
         printf("C++");
    }
    return 0;
}

0.7 is double constant (Default). Its binary value is written in 64 bit.

Binary value of 0.7 = (0.1011 0011 0011 0011 0011 0011 0011 0011 0011 0011 0011 )

Now here variable a is a floating point variable while 0.7 is double constant. So variable a will contain only 32 bit value i.e.
a = 0.1011 0011 0011 0011 0011 0011 0011 0011 while
0.7 = 0.1011 0011 0011 0011 0011 0011 0011 0011 0011 0011 0011....
It is obvious a < 0.7

2.Rule :- ++ is pre increment operator so in any arithmetic expression it first increment the value of variable by one in whole expression then starts assigning the final value of variable in the expression.

Compiler will treat this expression j = ++i+++i+++i; as
i = ++i + ++i + ++i;

Initial value of i = 5 due to three pre increment operator final value of i=8.
Now final value of i i.e. 8 will assigned to each variable as shown in the following figure:


So, j=8+8+8
j=24 and
i=8
3.#include<stdio.h>
void main(){
    int x;
    x=10,20,30;
    printf("%d",x);
    return 0;
} 
Precedence table:

Operator
Precedence
Associative
 =
More than ,
Right to left
 ,
Least
Left to right

Since assignment operator (=) has more precedence than comma operator .So = operator will be evaluated first than comma operator. In the following expression
x = 10, 20, 30
First 10 will be assigned to x then comma operator will be evaluated.
4.
#include<stdio.h>
int main(){
    int a;
    a=015 + 0x71 +5;
    printf("%d",a);
    return 0;
}
015 is octal number its decimal equivalent is = 5 * 8 ^ 0 + 1 * 8 ^ 1 = 5 + 8 = 13
0x71 is hexadecimal number (0x is symbol of hexadecimal) its decimal equivalent is = 1 * 16 ^ 0 + 7 * 16 ^ 1 = 1 + 112 = 113
So, a = 13 + 113 + 5 = 131
5.
#include<stdio.h>
int main(){
    float a;
    (int)a= 45;
    printf("%d,a);
    return 0;
}
After performing any operation on operand it always return some constant value.

(int) i.e. type casting operator is not exception for this. (int) a will return one constant value and we cannot assign any constant value to another constant value in c.

(int)a = 45; is equivalent to
3456 = 45 ( Here 3456 in any garbage value of int(a)).

Saturday, July 14, 2012

C Arrays Questions


#include<stdio.h>
enum power{
    Dalai,
    Vladimir=3,
    Barack,
    Hillary
};
void main(){
    float leader[Dalai+Hillary]={1.f,2.f,3.f,4.f,5.f};
    enum power p=Barack;
    printf("%0.f",leader[p>>1+1]);
}

Output:2

Size of an array can be enum constantan.
Value of enum constant Barack will equal to Vladimir + 1 = 3 +1 = 4
So, value of enum variable p  = 4
leader[p >> 1 +1]
= leader[4 >> 1+1]
=leader[4 >> 2]   //+ operator enjoy higher precedence than >> operator.
=leader[1]  //4>>2 = (4 / (2^2) = 4/4 = 1
=2

#include<stdio.h>
void main(){
    int const SIZE=5;
    int expr;
    double value[SIZE]={2.0,4.0,6.0,8.0,10.0};
    expr=1|2|3|4;
    printf("%f",value[expr]);
}

Size of any array in c cannot be constantan variable.

Structure & Bit Fields

Both C and C++ allow integer members to be stored into memory spaces smaller than the compiler would ordinarily allow. These space-saving structure members are called bit fields, and their width in bits can be explicitly declared. Bit fields are used in programs that must force a data structure to correspond to a fixed hardware representation and are unlikely to be portable.
The syntax for declaring a bit field is as follows:
>>-type_specifier--+------------+--:--constant_expression--;---><
                   '-declarator-'
 
 
A bit field declaration contains a type specifier followed by an optional declarator, a colon, a constant integer expression that indicates the field width in bits, and a semicolon. A bit field declaration may not use either of the type qualifiers, const or volatile.
C The C99 standard requires the allowable data types for a bit field to include qualified and unqualified _Bool, signed int, and unsigned int. In addition, this implementation supports the following types.
  • int
  • short, signed short, unsigned short
  • char, signed char, unsigned char
  • long, signed long, unsigned long
  • long long, signed long long, unsigned long long
In all implementations, the default integer type for a bit field is unsigned.
C++ C++ extends the list of allowable types for bit fields to include any integral type or enumeration type.
In either language, when you assign a value that is out of range to a bit field, the low-order bit pattern is preserved and the appropriate bits are assigned.
Bit fields with a length of 0 must be unnamed. Unnamed bit fields cannot be referenced or initialized. A zero-width bit field can cause the next field to be aligned on the next container boundary where the container is the same size as the underlying type of the bit field.
Mac OS X Bit fields are also subject to the align compiler option. Each of the align suboptions gives a different set of alignment properties to the bit fields. For a full discussion of the align compiler option and the #pragmas affecting alignment, see XL C/C++ Compiler Reference.
The following restrictions apply to bit fields. You cannot:
  • Define an array of bit fields
  • Take the address of a bit field
  • Have a pointer to a bit field
  • Have a reference to a bit field
The following structure has three bit-field members kingdom, phylum, and genus, occupying 12, 6, and 2 bits respectively:
struct taxonomy {
     int kingdom : 12;
     int phylum : 6;
     int genus : 2;
     };
Alignment of Bit Fields
If a series of bit fields does not add up to the size of an int, padding can take place. The amount of padding is determined by the alignment characteristics of the members of the structure.
The following example demonstrates padding, and is valid for all implementations. Suppose that an int occupies 4 bytes. The example declares the identifier kitchen to be of type struct on_off:
struct on_off {
                  unsigned light : 1;
                  unsigned toaster : 1;
                  int count;            /* 4 bytes */
                  unsigned ac : 4;
                  unsigned : 4;
                  unsigned clock : 1;
                  unsigned : 0;
                  unsigned flag : 1;
                 } kitchen ;
The structure kitchen contains eight members totalling 16 bytes. The following table describes the storage that each member occupies:

Member Name Storage Occupied
light 1 bit
toaster 1 bit
(padding -- 30 bits) To the next int boundary
count The size of an int (4 bytes)
ac 4 bits
(unnamed field) 4 bits
clock 1 bit
(padding -- 23 bits) To the next int boundary (unnamed field)
flag 1 bit
(padding -- 31 bits) To the next int boundary
All references to structure fields must be fully qualified. For instance, you cannot reference the second field by toaster. You must reference this field by kitchen.toaster.
The following expression sets the light field to 1:
  kitchen.light = 1;
When you assign to a bit field a value that is out of its range, the bit pattern is preserved and the appropriate bits are assigned. The following expression sets the toaster field of the kitchen structure to 0 because only the least significant bit is assigned to the toaster field:
  kitchen.toaster = 2;
 
Reference Links:
http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/
index.jsp?topic=%2Fcom.ibm.vacpp6m.doc%2Flanguage%2Fref%2Fclrc03defbitf.htm
 
http://c-faq.com/struct/bitfields.html

C String Questions

1.void main(){
   char *str=NULL;
   strcpy(str,"cquestionbank");
   printf("%s",str);
}
We cannot copy any thing using strcpy function to the character pointer pointing to NULL.

C Evaluation Order Questions

1.void main(){
  int i=4,x;
  x=++i + ++i + ++i;
  printf("%d",x);
}
In ++a, ++ is pre increment operator. In any mathematical expression pre increment operator first increment the variable up to break point then starts assigning the final value to all variable.
Step 1: Increment the variable I up to break point.


Step 2: Start assigning final value 7 to all variable i in the expression.



So, i=7+7+7=21
2.void main(){
  int a=10;
  printf("%d %d %d",a,a++,++a);
} 
In c printf function follows cdecl parameter passing scheme. In this scheme parameter is passed from right to left direction.


So first ++a will pass and value of variable will be a=10 then a++ will pass now value variable will be a=10 and at the end a will pass and value of a will be a=12. 

C Datatype Questions

 1.void main(){
   int i=320;
   char *ptr=(char *)&i;
   printf("%d",*ptr);
}

As we know size of int data type is two byte while char pointer can pointer one byte at time.
Memory representation of int i=320


So char pointer ptr is pointing to only first byte as shown above figure.
*ptr i.e. content of first byte is 01000000 and its decimal value is 64.
2.void main(){
char c=125;
    c=c+10;
    printf("%d",c);
}

As we know char data type shows cyclic properties i.e. if you will increase or decrease the char variables beyond its maximum or minimum value respectively it will repeat same value according to following cyclic order:
So,
125+1= 126
125+2= 127
125+3=-128
125+4=-127
125+5=-126
125+6=-125
125+7=-124
125+8=-123
125+9=-122
125+10=-121

3.
void main(){
   float a=5.2;
  if(a==5.2)
     printf("Equal");
  else if(a<5.2)
     printf("Less than");
  else
     printf("Greater than");
}

5.2 is double constant in c. In c size of double data is 8 byte while a is float variable. Size of float variable is 4 byte.
So double constant 5.2 is stored in memory as:
101.00 11001100 11001100 11001100 11001100 11001100 11001101
Content of variable a will store in the memory as:
101.00110 01100110 01100110
It is clear variable a is less than double constant 5.2
Since 5.2 is recurring float number so it different for float and double. Number likes 4.5, 3.25, 5.0 will store same values in float and double data type.
Note: In memory float and double data is stored in completely different way

3.
void main(){
char c='\08';
printf("%d",c);
}

In c any character is starting with character ‘\’ represents octal number in character. As we know octal digits are: 0, 1, 2, 3, 4, 5, 6, and 7. So 8 is not an octal digit. Hence ‘\08’ is invalid octal character constant.


Reference Links:

Friday, July 13, 2012

Memory Representation of int data type in C

int may be signed or unsigned both have different memory representation.

1. Memory representation of:
unsigned int a=7;

It is 16-bit data type and all 16 bit is data bit.
Binary equivalent of 7 is: 111
for 16 bit we will add 13 zero in the left side i.e. 00000000 00000111
Since Turbo C is based on 8085 microprocessor which follow little-endian.
Here A is 00000111 and B is 00000000

Memory representation: 
Note: same memory representation will be of:
unsigned short int a=7;
2. Memory representation of:
 
int a=7 or signed int a=7;
 
It is 16 bit data type.
15 bit: data bit
1 bit: signed bit
Binary equivalent of 7 is 111
for 16 bit we will add 13 zero in the left side i.e. 00000000 00000111
Here
A is 00000111
B is 00000000


Memory representation:


Note: same memory representation will be of:



3. Memory representation of:



int a= -7 or signed int a= -7;
It is 16 bit data type.Binary equivalent of 7 is 111 for 16 bit we will add 13 zero in the left side 

i.e. 00000000 00000111 since a is negative number so it will first convert in 
the 2’s complement format before stored in the memory. 1’s Complement of a: 11111111 11111000 + 1 ______________________ 2’s Complement of a: 11111111 11111001 Memory representation

Note: same memory representation will be of:
short int a=-7 or signed short int a=-7;

Note:
Above memory representation is for TURBO C compiler. Both linux gcc and tubro c follow little endianess architecture. But size of data type in linux gcc and turbo c is not same. So memory representation may vary in gcc.

Thursday, July 5, 2012

Find the nearest numbers that have same number of 1s for an integer

Given an integer, print the next smallest and next largest number that have the same number of 1 bits in their binary representation.

Naive Solution:
For the next largest, keep adding 1 to the number until find the number that has same number of 1 bits. For the next smallest, keep decreasing 1.

Advanced Solution:

  1. Traverse from right to left. Once we’ve passed a 1, turn on the next 0. We’ve now increased the number by 2^i. Yikes! Example: xxxxx011100 becomes xxxxx111100.
  2. Turn off the one that’s just to the right side of that. We’re now bigger by 2^i – 2^(i-1). Example: xxxxx111100 becomes xxxxx101100
  3. Make the number as small as possible by rearranging all the 1s to be as far right as possible: Example: xxxxx101100 becomes xxxxx100011
Code:

boolean GetBit(int n, int index) {
    return ((n & (1 << index)) > 0);
}

int SetBit(int n, int index, boolean b) {
    if (b) {
        return n | (1 << index);
    } else {
        int mask = ~(1 << index);
        return n & mask;
    }
}

int GetNext_NP(int n) {
    if (n <= 0)
        return -1;
    int index = 0;
    int countOnes = 0;
   
    // Find first one.
    while (!GetBit(n, index))
        index++;
   
    // Turn on next zero.
    while (GetBit(n, index)) {
        index++;
        countOnes++;
    }
    n = SetBit(n, index, true);

    // Turn off previous one
    index--;
    n = SetBit(n, index, false);
    countOnes--;

    // Set zeros
    for (int i = index - 1; i >= countOnes; i--) {
        n = SetBit(n, i, false);
    }

    // Set ones
    for (int i = countOnes - 1; i >= 0; i--) {
        n = SetBit(n, i, true);
    }
   
    return n;
}

int GetPrevious_NP(int n) {
    if (n <= 0)
        return -1; // Error

    int index = 0;
    int countZeros = 0;

    // Find first zero.
    while (GetBit(n, index))
        index++;

    // Turn off next 1.
    while (!GetBit(n, index)) {
        index++;
        countZeros++;
    }
    n = SetBit(n, index, false);

    // Turn on previous zero
    index--;
    n = SetBit(n, index, true);
    countZeros--;

    // Set ones
    for (int i = index - 1; i >= countZeros; i--) {
        n = SetBit(n, i, true);
    }

    // Set zeros
    for (int i = countZeros - 1; i >= 0; i--) {
        n = SetBit(n, i, false);
    }
    return n;
}

Wednesday, June 27, 2012

Misc C Conecpts [Uncategorised]

1.What is the memory allocated for the following definition.

char* n[]={"name1","name2","name3"};

Solution:
n is an array of 3 elements. Each element is the address of a const char array. The sizeof n is the size of 3 addresses. On my machine this is 12 bytes.

n is not a two dimesional array. The strings are 6 bytes .So
Memory for 3 pointers[12 bytes] + memory for 3 string literals[18 bytes]=30 bytes

2.