Showing posts with label fresher job interview tips. Show all posts
Showing posts with label fresher job interview tips. Show all posts

Examples for Loop in List

Q.1 How do you find whether there is a loop in a linked list? For example, the list in Figure bellow contains a loop. 


                                                              A list with a loop 
  1. This is a popular interview question. It can be solved with two pointers, which are initialized at the head of list. One pointer advances once at each step, and the other advances twice at each step. If the faster pointer meets the slower one again, there is a loop in the list. Otherwise, there is no loop if the faster one reaches the end of list.
    The sample code in bellow is implemented based on this solution. The faster pointer is pFast, and the slower one is pSlow.

     C++ Code to Check Whether a List Contains a Loop
    bool HasLoop(ListNode* pHead) {
        if(pHead == NULL)
    
            return false;
    
        ListNode* pSlow = pHead->m_pNext;
        if(pSlow == NULL)
    
            return false;
    
        ListNode* pFast = pSlow->m_pNext;
        while(pFast != NULL && pSlow != NULL) {
    
            if(pFast == pSlow)
                return true;
    
            pSlow = pSlow->m_pNext;
    
            pFast = pFast->m_pNext;
            if(pFast != NULL)
    
                pFast = pFast->m_pNext;
    
    }
        return false;
    }
    
    Test Cases:
    • There is a loop in a list (including cases where there are one/multiple nodes in a loop, or a loop contains all nodes in a list)
    • There is not a loop in a list
    • The input node of the list head is NULL  

      Q.

      If there is a loop in a linked list, how do you get the entry node of the loop? The entry node is the first node in the loop from the head of a list. For instance, the entry node of the loop in the list of Figure bellow is the node with value 3. 
                                                                             A list with a loop 
      we can also solve this problem with two pointer.Two pointers P1 and P2 are initialized to point to the head of a list. If there are n nodes in the loop, the first pointer move forward n steps, and then two pointers move together with same speed. When the second pointer reaches the entry node of the loop, the first one travels around the loop and returns back to the entry node.
      Let’s take the list in Figure above as an example. P1 and P2 are first initialized to point to the head node of the list (Figure (a)). There are four nodes in the loop of the list, so P1 moves four steps ahead and reaches the node with value 5 (Figure (b)). Then these two pointers move two steps, and they meet at the node with value 3, which is the entry node of the loop, as shown in Figure (c). 


      Process to find the entry node of a loop in a list. (a) Pointers P1 and P2 are initialized at the head of list. (b) The pointer P1 moves four steps ahead since there are four nodes in the loop. (c) Both P1 and P2 move ahead till they meet at the entry node of the loop.
      The only problem is how to figure out the number of nodes inside a loop. Let’s go back to the solution of the previous question. Two pointers are employed, and the faster one meets the slower one if there is a loop. The meeting node should be inside the loop. Therefore, we can move forward from the meeting node and count nodes in the loop until we arrive at the meeting node again.
      The function Meeting Node in bellow code finds the meeting node of two pointers if there is a loop in a list, which is a minor modification of the previous HasLoop.
       C++ Code to Get a Meeting Node in a Loop
      ListNode* MeetingNode(ListNode* pHead) {
          if(pHead == NULL)
      
      return NULL;
          ListNode* pSlow = pHead->m_pNext;
          if(pSlow == NULL)
      
      return NULL;
          ListNode* pFast = pSlow->m_pNext;
          while(pFast != NULL && pSlow != NULL) {
      
              if(pFast == pSlow)
                  return pFast;
      
              pSlow = pSlow->m_pNext;
              pFast = pFast->m_pNext;
      

      if(pFast != NULL)
          pFast = pFast->m_pNext;
      
      }
          return NULL;
      }
      
      The function MeetingNode returns a node in the loop when there is a loop in the list. Otherwise, it returns NULL.
      After finding the meeting node, it counts nodes in a loop of a list, as well as finding the entry node of the loop with the sample code, as shown inbellow code.
      C++ Code to Get a Meeting Node in a Loop
      ListNode* EntryNodeOfLoop(ListNode* pHead) {
          ListNode* meetingNode = MeetingNode(pHead);
          if(meetingNode == NULL)
      
      return NULL;
          // get the number of nodes in loop
          int nodesInLoop = 1;
          ListNode* pNode1 = meetingNode;
          while(pNode1->m_pNext != meetingNode) {
      
              pNode1 = pNode1->m_pNext;
      
              ++nodesInLoop;
          }
      
          // move pNode1
          pNode1 = pHead;
          for(int i = 0; i < nodesInLoop; ++i)
      
              pNode1 = pNode1->m_pNext;
      
          // move pNode1 and pNode2
          ListNode* pNode2 = pHead;
          while(pNode1 != pNode2){
      
              pNode1 = pNode1->m_pNext;
      
              pNode2 = pNode2->m_pNext;
          }
      
          return pNode1;
      }
      
      Test Cases:
      • There is a loop in a list (including cases where there are one/multiple nodes in a loop, or a loop contains all nodes in a list)
      • There is not a loop in a list
      • The input node of the list head is NULL

       
www.cinterviews.com appreciates your contribution please mail us the questions you have to cinterviews.blogspot.com@gmail.com so that it will be useful to our job search community

Exception Safety in c++


In the previous code, the old m_pData is deleted before it is renewed. If an exception is thrown while reallocating memory due to insufficient memory, m_pData is a NULL pointer and it is prone to crash the whole application. In other words, when an exception is thrown in the assignment operator function, the status of a CMyString instance is invalid. It breaks the requirement of exception safety: If an exception is thrown, everything in the program must remain in a valid state.
Two approaches are available to achieve the goal of exception safety. The first one is to allocate memory with the new operator before deleting. It makes sure the old memory is deleted only after it allocates memory successfully, and the status of CMyString instances is valid if it fails to allocate memory.
A better choice is to create a temporary instance to copy the input data and then to swap it with the target. The code in Listing 2-11 is based on the copy-and-swap solution.
Listing 2-11. C++ Code for Assignment Operator (Version 2)
CMyString& CMyString::operator =(const CMyString &str) {
    if(this != &str) {
        CMyString strTemp(str);
        char* pTemp = strTemp.m_pData;
        strTemp.m_pData = m_pData;
        m_pData = pTemp;
}
    return *this;
}
In this code, a temporary instance strTemp is constructed first, copying data from the input str. Next, it swaps strTemp.m_pData with this->m_pData. Because strTemp is a local variable, its destructor will be called automatically when the execution flow exits this function. The memory pointed to by strTemp.m_pData is what was pointed to by this->m_pData before, so the memory of the old instance is deleted when the destructor of strTemp is invoked.
It allocates memory with the new operator in the constructor of CMyString. Supposing that a bad_alloc exception is thrown due to insufficient memory, the old instance has not been modified, and its status is still valid. Therefore, it is an exception-safe solution.
Source Code:
    002_AssignmentOperator.cpp
Test Cases:
  •  Assign an instance to another 
  • Assign an instance to itself
  • Chain multiple assignments together
  • Stress tests to check whether the code contains memory leaks
www.cinterviews.com appreciates your contribution please mail us the questions you have to cinterviews.blogspot.com@gmail.com so that it will be useful to our job search community

Analyzing Execution of C++ Code

The second type of interview questions in C++ concerns analyzing execution results of some sample code. Candidates without deep understanding of C++ are prone to make mistakes because the code to be analyzed is usually quite tricky.
For example, an interviewer hands a piece of paper printed with the code in Listing 2-8 to a candidate and asks the candidate what the result is if we try to compile and execute the code: (A) Compiling error; (B) It compiles well, but crashes in execution; or (C) It compiles well, and executes smoothly with an output of 10.
Listing 2-8. C++ Code about Copy Constructor
class A {
private:
int value; 

public:
    A(int n) {
value = n; }
    A(A other) {
        value = other.value;
    }
    void Print() {
         std::cout << value << std::endl;
    }
};
int main(int argc, _TCHAR* argv[]) {
    A a = 10;
    A b = a;
    b.Print();
return 0; }
The parameter in the copy constructor A(A other) is an instance of type A. When the copy constructor is executed, it calls the copy constructor itself because of the pass-by-value parameter. Since endless recursive calls cause call stack overflow, a pass-by-value parameter is not allowed in the C++ standard, and both Visual Studio and GCC report an error during compiling time. We have to modify the constructor as A(const A& other) to fix this problem. That is to say, the parameter in a copy constructor should be passed by a reference.
 www.cinterviews.com appreciates your contribution please mail us the questions you have to cinterviews.blogspot.com@gmail.com so that it will be useful to our job search community

Clear Thoughts about Solutions



Three tools are available to analyze and solve complicated problems: figures, examples, and division.
 Candidates cannot solve complex problems without clear thinking. Sometimes interviewers ask very difficult questions that they do not even expect candidates to solve in less than an hour. What interviewers are interested in are the candidates' thinking processes in such situations, rather than complete and correct answers. Usually, interviewers dislike candidates who write code in haste, with lots of bugs in it.
There are a few methods to help candidates to formulate clear ideas. First, candidates can employ some examples to help themselves to analyze problems. Simulating operations with one or two examples may uncover the hidden rules. Second, figures are helpful to visualize abstract data structures and algorithms. Many problems related to lists and binary trees might become easier if they are visualized with figures. Another approach is to divide a complicated problem into multiple manageable pieces and then solve them one at a time. Many recursive solutions, such as divide-and-conquer algorithms, as well as dynamic programming algorithms, are all essentially utilization of division.
For example, it is quite a complex problem to convert a binary search tree into a sorted doubly linked list. When confronted with such a problem during interviews, candidates may draw some figures about one or two sample binary search trees and their corresponding sorted doubly linked lists in order to visualize the relationship between them. They can also try to divide a binary tree into three parts: the root node, the left subtree, and the right subtree. After the left and right subtrees are converted to linked lists, they are connected with the root node to form a sorted linked list, and the problem is solved. More details about this problem are available in the section Binary Search Trees and Double-Linked Lists.
www.cinterviews.com appreciates your contribution please mail us the questions you have to cinterviews.blogspot.com@gmail.com so that it will be useful to our job search community

Relocation of job interview

Relocation of job interview

So you have made it through the first few rounds of the interview process and you are now at the final stage of the interview. You are meeting the Hiring Manager and you know that everything is going great except you know that he/she is concerned about your willingness to relocate out-of-state for the position. How can you set his/her mind at ease concerning this alarming issue? Here, are our tips:

1. Write out a list of all your ties to the area. Before the interview, make a list of all the ties you have to the area or state. This list should include times you have visited or lived in the state. It should also include any family or friends that you have in the state.

2. Write out a list of all time you were away from home. Also, make a list of all the times you have been away from home. These can be to any location. Essentially, you are trying to make a record of times where you have been away from home for extended periods of time and were not homesick.

a. Examples could include going to a college out of state or going to Europe over the summer.

3. Research the city for more “useful” information. Research the city in which the job will be located. Make a list of the things that appeal to you about the city and how they would be a natural extension of you.

a. For example, if you do artwork on the side, talk in the interview about how great it would be to see “such and such” museum.

b. If you belong to any clubs or groups (avoid discussing any controversial groups) that have chapters in that area, state how
you look forward to joining those groups chapters.

c. Also, you can use the uniqueness of the city to your advantage as well. If you have never lived near the beach or the mountains, state how you are looking forward to a change from your own environment. If housing costs are cheaper, state this as well. Essentially, you are trying to show that a moving would be in your best interest.

4. Determine how your marital and family status will be benefit in the move. It is usually a no-no for the interviewer to ask you about these things. However, you can bring them up if you believe they will help your case. For instance, if you are single and have no children, you bring this point up to show that you can make this decision without consulting family. If you do have a family, you can state how your family supports your decision and would love to move there for such and such reasons.

5. Sell your commitment to the position. If this position would be an excellent learning opportunity or is with a very prestigious firm, state you would be more than willing to trade any small degree of homesickness because the benefits significantly outweigh this one minor issue.

6. Create a presentation for this interview question or concern. After you have compiled your research, you want to create a basic presentation that you will use when asked about this issue. By way of your preparation and your answer, you will be able to show you have thought about this issue and will give you a chance to state reasons why this will not be an issue and possibly even a benefit.

7. Take your cues from the interviewer. Try to gauge what specifically they are concerned about in your possible move and tailor your answer to that particular aspect. Often times, you can determine this by seeing how they respond to different parts of your answer to their question or what follow-up questions they ask you.

Implementing these steps will not guarantee the interviewer will be satisfied. However, it should go a long way towards planting seeds of thought that relocating will not be a significant issue. Your goal here is really to minimize any lingering doubts. If you are able to do effectively this, you just might be able to beat out a local candidate for the position.

Fresher Job Interview Tips

Fresher Job Interview Tips
Even the smartest and most qualified job seekers need to prepare for job interviews.
Why, you ask? Interviewing is a learned skill, and there are no second chances to make a great first impression. So study these 10 strategies to enhance your interview IQ
Practice Good Nonverbal Communication
It’s about demonstrating confidence: standing straight, making eye contact and connecting with a good, firm handshake. That first impression can be a great beginning — or quick ending — to your interview.
Dress for the Job or Company
Today’s casual dress codes do not give you permission to dress as “they” do when you interview. It is important to look professional and well-groomed. Whether you wear a suit or something less formal depends on the company culture and the position you are seeking. If possible, call to find out about the company dress code before the interview.
Listen
From the very beginning of the interview, your interviewer is giving you information, either directly or indirectly. If you are not hearing it, you are missing a major opportunity. Good communication skills include listening and letting the person know you heard what was said. Observe your interviewer, and match that style and pace.
Don’t Talk Too Much
Telling the interviewer more than he needs to know could be a fatal mistake. When you have not prepared ahead of time, you may tend to ramble, sometimes talking yourself right out of the job. Prepare for the interview by reading through the job posting, matching your skills with the position’s requirements and relating only that information.
Don’t Be Too Familiar
The interview is a professional meeting to talk business. This is not about making a new friend. Your level of familiarity should mimic the interviewer’s demeanor. It is important to bring energy and enthusiasm to the interview and to ask questions, but do not overstep your place as a candidate looking for a job.
Use Appropriate Language
It’s a given that you should use professional language during the interview. Be aware of any inappropriate slang words or references to age, race, religion, politics or sexual orientation — these topics could send you out the door very quickly.
Don’t Be Cocky
Attitude plays a key role in your interview success. There is a fine balance between confidence, professionalism and modesty. Even if you’re putting on a performance to demonstrate your ability, overconfidence is as bad, if not worse, as being too reserved.
Take Care to Answer the Questions
When an interviewer asks for an example of a time when you did something, he is seeking a sample of your past behavior. If you fail to relate a specific example, you not only don’t answer the question, but you also miss an opportunity to prove your ability and talk about your skills.
Ask Questions
When asked if they have any questions, most candidates answer, “No.” Wrong answer. It is extremely important to ask questions to demonstrate an interest in what goes on in the company. Asking questions also gives you the opportunity to find out if this is the right place for you. The best questions come from listening to what is asked during the interview and asking for additional information.
Don’t Appear Desperate
When you interview with the “please, please hire me” approach, you appear desperate and less confident. Maintain the three C’s during the interview: cool, calm and confident. You know you can do the job; make sure the interviewer believes you can, too.