Interview questions on C/C++

A reader submitted the interview questions he was asked. More C/C++ questions will be added here, as people keep sending us a set of 2-3 questions they got on their job itnerview.

Q1: Tell how to check whether a linked list is circular.

A: Create two pointers, each set to the start of the list. Update each as follows:

while (pointer1) {
 pointer1 = pointer1->next;
 pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;
 if (pointer1 == pointer2) {
   print ("circular\n");
 }
}


Q2: OK, why does this work?

If a list is circular, at some point pointer2 will wrap around and be either at the item just before pointer1, or the item before that. Either way, it’s either 1 or 2 jumps until they meet.

How can you quickly find the number of elements stored in a a) static array b) dynamic array ?

Why is it difficult to store linked list in an array?

How can you find the nodes with repetetive data in a linked list?

Write a prog to accept a given string in any order and flash error if any of the character is different. For example : If abc is the input then abc, bca, cba, cab bac are acceptable but aac or bcd are unacceptable.

This is a C question that I had for an intern position at Microsoft: Write out a function that prints out all the permutations of a string. For example, abc would give you abc, acb, bac, bca, cab, cba. You can assume that all the characters will be unique. After I wrote out my function, he asked me to figure out from the code how many times the printf statement is run, and also questions on optimizing my algorithm.

What’s the output of the following program? Why?

#include <stdio.h>
main()
{
	typedef union
	{
		int a;
		char b[10];
		float c;
	}
	Union;

	Union x,y = {100};
	x.a = 50;
	strcpy(x.b,"hello");
	x.c = 21.50;

	printf("Union x : %d %s %f \n",x.a,x.b,x.c );
	printf("Union y :%d %s%f \n",y.a,y.b,y.c);
}

Given inputs X, Y, Z and operations | and & (meaning bitwise OR and AND, respectively)

What is output equal to in

output = (X & Y) | (X & Z) | (Y & Z)

This entry was posted in C++. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

77 Comments on Interview questions on C/C++

  1. Rohit
    Posted 2/23/2006 at 9:48 am | Permalink

    //Answer for is Circular link list
    //start and p initially the given pointer

    While(p)
    if(start==(p=p->next))
    printf(”Circular”);
    printf(”not a circular”);

    #What say

  2. neetu
    Posted 4/12/2006 at 10:47 am | Permalink

    I tried to solve the question using the approach given by Hari :)
    “Write a prog to accept a given string in any order and flash error if any of the character is different. For example : If abc is the input then abc, bca, cba, cab bac are acceptable but aac or bcd are unacceptable.

    Tech Interviews comment by Hari ”
    #include
    #include

    void main()
    {
    char s[10],dup[10];
    int sum_org=0,sum_dup=0;
    printf(”\nEnter the string “);
    scanf(”%s”,s);
    sum_org=parse_sum(s);

    printf(”\nEnter the duplicate string :”);
    scanf(”%s”,dup);
    sum_dup=parse_sum(dup);

    if(sum_org==sum_dup)
    printf(”\nAllowed duplication”);
    else
    printf(”\nNot same !!”);
    }

    int parse_sum(char *s)
    {
    char temp,*c;
    int equi,sum=0;
    c=s;
    while(*c!=”)
    {
    temp=*c;
    equi=temp;
    sum=sum+equi;
    c++;
    }
    return sum;
    }

  3. kevin
    Posted 5/10/2006 at 12:05 pm | Permalink

    Code for printing out all permutaions of a string, gurantee to work correctly:

    #include
    #include
    #include

    //recursive function to permute a string
    void permute(char permulist[], int start, int n)
    {
    char templist[100];
    char tempchar;
    int i;
    if (start == n-1)
    {
    for (i=0; i>str;
    n = strlen(str);
    permute(str,0,n);
    return 0;
    }

  4. kevin
    Posted 5/10/2006 at 12:06 pm | Permalink

    test program for comment 53 (print out permutations)
    int main()
    {
    char str[100];
    int n;
    cout>str;
    n = strlen(str);
    permute(str,0,n);
    system(”PAUSE”);
    return 0;
    }

  5. kevin
    Posted 5/10/2006 at 12:08 pm | Permalink

    The followint header files should be included in Comment 53 and 54:
    iostream.h
    stdlib.h
    string.h

  6. kevin
    Posted 5/10/2006 at 12:11 pm | Permalink

    sorry, this website wipes out the character “

  7. Posted 6/27/2006 at 5:45 am | Permalink

    can anyone tell how to find the common node in a circular list without flagging?? in o(n) time

  8. Sachidanand Joshi
    Posted 7/26/2006 at 2:09 am | Permalink

    can anyone tell how to find the common node in a circular list without flagging?? in o(n) time

    Please elaborate the question. It is not clear. What is a common node in cicular list???

  9. Posted 8/14/2006 at 7:22 am | Permalink

    Hi friends this is the best solution to find Circular Linklist in O(n).

    // Best solution
    function boolean hasLoop(Node startNode){
    Node slowNode = Node fastNode1 = Node fastNode2 = startNode;
    while (slowNode && fastNode1 = fastNode2.next() && fastNode2 = fastNode1.next()){
    if (slowNode == fastNode1 || slowNode == fastNode2) return true;
    slowNode = slowNode.next();
    }
    return false;
    }

    also see this site
    http://ostermiller.org/find_loop_singly_linked_list.html

  10. sanchit
    Posted 10/31/2006 at 1:20 am | Permalink

    how can i find the tenth prime number after the decimal point in e…ie e=2.71….(i need the tenth prime aftr the decimal)…my prog wont wrk…

  11. Peeush Harsh
    Posted 1/5/2007 at 2:02 am | Permalink

    What is output equal to in

    output = (X & Y) | (X & Z) | (Y & Z)

    if any of the two of {X,Y,Z} are true then the expression is true.

  12. bhushan rao
    Posted 1/6/2007 at 4:12 am | Permalink

    hello everybody,
    i want to know why is the sizeof empty class is 1.
    i.e. class abc{ };
    cout

  13. Dex
    Posted 1/8/2007 at 3:54 am | Permalink

    Hi,
    one of the frequentr question reg Copy constructor..
    syntax for Copy constructor:

    classname(const classname &obj)
    {
    ….
    }

    what will happen if u haapen to remove the reference used.. say

    classname(const classname obj)
    {
    ….
    }

    ANS:
    if not used without reference , it will end in infinite loop…bcoz again (as per the stmt) again it tries to create a obj which inturn invokes again the same function and again the same thing continues…making it an infinite loop

  14. Rohit Adhlakha
    Posted 1/12/2007 at 12:52 am | Permalink

    here I give a soln which is able to find whether link list is circular or not in O(n) time
    take two pointers as start1 & start2
    set start1 & start2 at any node which is in the given linklist

  15. Rohit Adhlakha
    Posted 1/12/2007 at 12:56 am | Permalink

    here I give a soln which is able to find whether link list is circular or not in O(n) time
    take two pointers as start1 & start2
    set start1 at any node which is in the given linklist such
    start2 = start1;

    while(start2->next!=start1&&start2->next!=NULL)
    start2=start2->next;

    if(start2->next=start1)
    printf(”circular”);
    else
    printf(”not circular)

  16. Gopal
    Posted 1/16/2007 at 12:08 am | Permalink

    The following code works (tested):
    void isCircularList(nodePtr head, nodePtr curr, bool &circ) {

    if (head) {
    if ( curr && (curr->next == head) )
    circ = true;
    else {
    if (curr)
    isCircularList(head, curr->next, circ);
    else
    circ = false;
    }
    }

    }

  17. Pralhad
    Posted 2/10/2007 at 7:59 pm | Permalink

    Write a prog to accept a given string in any order and flash error if any of the character is different. For example : If abc is the input then abc, bca, cba, cab bac are acceptable but aac or bcd are unacceptable.

    The most efficient and scalable way would be:
    1. sort the original string.
    2. sort the input string.
    3. if(strcmp(original_string, input_string))
    printf(”Error”);

    -Pralhad

  18. P.Rakesh
    Posted 4/29/2007 at 2:42 am | Permalink

    main()
    {
    printf(”hello friends”);
    }
    without using void function in main and %d in printf we can print a mesg similarly in c++ can also we can do
    but there are only few simple programs only why we can all that is bec there exist a rule fr which we have to be defined fr structure, pointers, arrays etc

  19. Mike Mountrakis
    Posted 5/29/2007 at 8:00 pm | Permalink

    bool isCircular( node * head, node * current ) throws exception
    {

    if( head == NULL )
    throw new exception( "NULL reference passed!");

    if( current == NULL)
    throw new exception( "NULL reference passed!");

    for( ; ; )
    {
    //Check if we have reached the dead - end.
    if( current->next == NULL )
    return false;
    else
    {
    //Check if we have reached the Head (circular)
    if( current->next == head )
    return true;
    else //iterate
    current = current->next;
    }
    }

    //Point not reached.
    }

    //Use it like:

    try
    {
    bool is_circular = isCircular( head, head );
    }
    catch( exception e)
    {
    cout

    Mike Mountrakis
    http://www.illumine.gr

  20. Mike Mountrakis
    Posted 5/29/2007 at 8:05 pm | Permalink

    For the array size:


    unsigned log getSize( Cell_t array [])
    {
    return sizeof(array)/sizeof( Cell_t);
    }

    Mike Mountrakis
    http://www.illumine.gr

  21. Sandeep
    Posted 6/12/2007 at 8:29 am | Permalink

    Hi all,
    What i am thinking the best solution to find the loop in a sigly linked list by O(n) complexity u can implement by this logic ..

    bool is_circular()
    {
    node *sNode, *f1Node, *f2Node;
    node startNode;

    sNode = f1Node = f2Node = &startNode;

    while(sNode && f1Node = f2Node.next && f2Node = f1Node.next)
    {
    if (sNode == f1Node || sNode == f2Node)
    return true; // means loop found

    sNode = sNode.next;
    }
    }

  22. haseeb baber
    Posted 12/26/2007 at 8:24 am | Permalink

    void * ptr,*ptr2;
    ptr=begining;
    while(ptr->next!=null)//fix the element
    {
    ptr2=ptr->next;
    if(ptr2==ptr)//elemnet has its own address
    {
    coutnext;
    }
    ptr=ptr->next;
    }

  23. Prasad
    Posted 3/22/2008 at 11:13 am | Permalink

    Easy way to detect the circle in the Link List.
    Using C++ string class.

    unsigned int LinkList :: detect_circle_string () const
    {
        struct node *t = head ;
        char buf [10] ;
        string ptr = " " ;
        size_t found ;

        for ( ; t ; t=t->next )
        {
            sprintf ( buf, " %u ", t ) ;
            found =  ptr.find ( string(buf) ) ;
            if ( found!=string::npos  )
            {
                cout << "Circle Detected At : " << t->data << " Address : " << (unsigned int) t ;

                return (unsigned int ) t ;
            }
            ptr += buf ;
        }
    }

  24. Posted 8/11/2008 at 1:19 pm | Permalink

    Write a prog to accept a given string in any order and flash error if any of the character is different. For example : If abc is the input then abc, bca, cba, cab bac are acceptable but aac or bcd are unacceptable.

    —for this we can multiply the ascii values of each character in original string and compare it with that of duplicate string… the working code is as:-
    #include
    #include
    #include
    void main()
    {
    int i,n1,n2,mul1=1,mul2=1,sum=0;
    char str1[15],str2[15];
    clrscr();

    printf(”Enter the length of string\n”);
    scanf(”%d”,&n1);
    printf(”Enter the original string\n”);
    for(i=0;i<n1;i++)
    {
    scanf(”%s”,&str1[i]);
    mul1*=str1[i];
    }
    printf(”Enter the length of duplicate string\n”);
    scanf(”%d”,&n2);
    if(n1!=n2)
    {
    printf(”ERROR different\n”);
    exit(0);
    }
    printf(”Enter the duplicate string\n”);
    for(i=0;i<n2;i++)
    {
    scanf(”%s”,&str2[i]);
    mul2*=str2[i];
    }
    if(mul1==mul2)
    printf(”SAME\n”);
    else
    printf(”Different ERROR\n”);

    getch();
    }

  25. stampede
    Posted 11/10/2008 at 2:14 pm | Permalink

    Hi.
    This is my permutation func.

    void
    permutate( string s, int n=0 ){
    static int len=s.length();
    if( n == len-2 ){
    cout << s << endl;
    swap(s[len-2],s[len-1]);
    cout << s << endl;
    }
    else{
    for( int i=n ; i<len ; ++i ){
    permutate(s,n+1);
    swap(s[n],s[i+1]);
    }
    }
    }

  26. stampede
    Posted 11/10/2008 at 2:22 pm | Permalink

    It is based on simple fact, that to perform permutation of a n-element set, you should:
    0.If your set has only 2 elements, you can simply print them, then swap them, and print them again. End.
    1. print (save, whatever) the value of first element
    2. permute the rest of the set (means elements from 2, …, n )
    3. Swap the first element with all the next elements, and repeat the procedure.

    It’s clear, that this algorithm performs T(n) = n*T(n-1) steps, which is exactly n!
    T(1) = 1 of course.

    Or maybe I’m wrong? Hope not:P

    Regards from Poland!

  27. Eduard Sinelnikov(Israel,Technion)
    Posted 11/24/2008 at 9:47 am | Permalink

    Got a question that extends on the detecting circular linked list question:
    Given the constraints that you cannot modify the struct (or class) of the elements, and that you have to remove the loop in the cyclic linked list in O(n) time and O(1) space, how would you do it?
    By removing the loop, I mean something like:
    _______________________________
    __ __ __ _| __ __ __ _|
    | | -> | | -> | | -> | | -> | | -> | | -> | | -> | |
    — — — — — — — –

    Ans:
    You know how to make them meet. (By two pointers, one runs twice faster then the usual).
    Once they meet cut the list. Its looks like this :
    —–|————-
    ——-|
    OR
    ——-|———
    —|

    now run two normal pointers from anchor and from the place cut was made.
    Count the lengths.Once you know we lengths go over the longer so the lengths will be equal. Now run the two pointers and every step check if the pointers are equal.

    Look like
    —*———–|——
    ———- |

    or

    —|————–
    ——*—|

    When you find the common link. cut one
    of the list and copy to the end.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*