Sample Interview Questions
Interview Questions
This page lists some common interview questions for software engineers.
Questions
Click on the question to see its answer.
Useful tips
- Introduction
- The Basic Rules
- Don't assume all data is given to you.
- Think out loud.
- Good programming practice.
- Check all boundary conditions.
- Work Things Into Your Conversations
- Typical Technical Questions
- Conclusion
Logic questions
- Given a rectangular (cuboidal for the puritans) cake with a rectangular piece removed (any size or orientation), how would you cut the remainder of the cake into two equal halves with one straight cut of a knife ?
- You're given an array containing both positive and negative integers and required to find the subarray with the largest sum (O(N) a la KBL). Write a routine in C for the above.
- Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like.
- Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.
- How many points are there on the globe where by walking one mile south, one mile east and one mile north you reach the place where you started.
- In a X's and 0's game (i.e. TIC TAC TOE) if you write a program for this give a fast way to generate the moves by the computer. I mean this should be the fastest way possible.
- A version of the "There are three persons X Y Z, one of which always lies"..
- There are 3 ants at 3 corners of a triangle, they randomly start moving towards another corner.. what is the probability that they don't collide.
- If you are on a boat and you throw out a suitcase, Will the level of water increase.
- There are 4 men who want to cross a bridge. They all begin on the same side. You have 17 minutes to get all of them across to the other side. It is night. There is one flashlight. A maximum of two people can cross at one time. Any party who crosses, either 1 or 2 people, must have the flashlight with them. The flashlight must be walked back and forth, it cannot be thrown, etc. Each man walks at a different speed. A pair must walk together at the rate of the slower mans pace.
Man 1:1 minute to cross
Man 2: 2 minutes to cross
Man 3: 5 minutes to cross
Man 4: 10 minutes to cross
- You have 5 jars of pills. Each pill weighs 10 gram, except for contaminated pills contained in one jar, where each pill weighs 9 gm. Given a scale, how could you tell which jar had the contaminated pills in just one measurement?
- One train leaves Los Angeles at 15 MPH heading for New York. Another train leaves from New York at 20mph heading for Los Angeles on the same track. If a bird, flying at 25mph, leaves from Los Angeles at the same time as the train and flies back and forth between the two trains until they collide, how far will the bird have traveled?
- Imagine that you have 26 constants, labelled A through Z. Each constant is assigned a value in the following way: A = 1; the rest of the values equal their position in the alphabet (B corresponds to the second position so it equals 2, C = 3, etc.) raised to the power of the preceeding constant value. So, B = 2 ^ (A's value), or B = 2^1 = 2. C = 3^2 = 9. D = 4^9, etc., etc. Find the exact numerical value to the following equation:
(X - A) * (X - B) * (X - C) * ... * (X - Y) * (X - Z)
- You have 12 balls. All of them are identical except one, which is either heavier or lighter than the rest - it is either hollow while the rest are solid, or solid while the rest are hollow. You have a simple two-armed scale, and are permitted three weighings. Can you identify the odd ball, and determine whether it is hollow or solid.
Programming questions that require thinking
- Write a routine to draw a circle (x ** 2 + y ** 2 = r ** 2) without making use of any floating point computations at all.
- Given only putchar (no sprintf, itoa, etc.) write a routine putlong that prints out an unsigned long in decimal.
- Give a one-line C expression to test whether a number is a power of 2. [No loops allowed - it's a simple test.]
- Give a very good method to count the number of ones in a 32 bit number. (caution: looping through testing each bit is not a solution).
- What are the different ways to say, the value of x can be either a 0 or a 1.
- I was given two lines of assembly code which found the absolute value of a number stored in two's complement form. I had to recognize what the code was doing.
- Give a fast way to multiply a number by 7.
- Write an efficient algo and C code to shuffle a pack of cards.. this one was a feedback process until we came up with one with no extra storage.
- A real life problem - A square picture is cut into 16 sqaures and they are shuffled. Write a program to rearrange the 16 squares to get the original big square.
- Consider the base -2 representation of numbers. (-2 instead of usual +2). Give the condition for a number represented in this form to be positive? Also, if P(A, B) is a function that takes two 0-1 strings A,B in this representation, when can we say that P(A,B) returns the sum of these two numbers?
- Given an expression tree with no parentheses in it, write the program to give equivalent infix expression with parentheses inserted where necessary.
- Given a maze with cheese at one place and a mouse at some entrance, write a program to direct the mouse to cheese correctly. (Assume there is a path). Following primitives are given: moveforward, turnright, turnleft, iswall?, ischeese?, eatcheese.
- Give me an algorithm and C code to find the subarray with the largest sum given an array containing both positive and negative integers.
- Write a function that returns the factorial of a number.
- Write a function that computes the nth number in the Fibonacci sequence.
- Write an implementation of strlen().
- Switch the integer values stored in two registers without using any additional memory.
- Given two strings S1 and S2. Delete from S2 all those characters which occur in S1 also and finally create a clean S2 with the relevant characters deleted.
- Write a small lexical analyzer - interviewer gave tokens. expressions like "a*b" etc.
- Write a routine that prints out a 2-D array in spiral order!
- How is the readers-writers problem solved? - using semaphores/ada .. etc.
- Write code for reversing a linked list.
- Write, efficient code for extracting unique elements from a sorted list of array. e.g. (1, 1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9) -> (1, 3, 5, 9).
Microsoft question
- Given a rectangular (cuboidal for the puritans) cake with a rectangular piece removed (any size or orientation), how would you cut the remainder of the cake into two equal halves with one straight cut of a knife ?
- You're given an array containing both positive and negative integers and required to find the subarray with the largest sum (O(N) a la KBL). Write a routine in C for the above.
- Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like.[I ended up giving about 4 or 5 different solutions for this, each supposedly better than the others ].
- Write a routine to draw a circle (x ** 2 + y ** 2 = r ** 2) without making use of any floating point computations at all. [ This one had me stuck for quite some time and I first gave a solution that did have floating point computations ].
- Given only putchar (no sprintf, itoa, etc.) write a routine putlong that prints out an unsigned long in decimal. [ I gave the obvious solution of taking % 10 and / 10, which gives us the decimal value in reverse order. This requires an array since we need to print it out in the correct order. The interviewer wasn't too pleased and asked me to give a solution which didn't need the array ].
- Give a one-line C expression to test whether a number is a power of 2. [No loops allowed - it's a simple test.]
- Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.
- How many points are there on the globe where by walking one mile south, one mile east and one mile north you reach the place where you started.
- Give a very good method to count the number of ones in a 32 bit number. (caution: looping through testing each bit is not a solution).
- What are the different ways to say, the value of x can be either a 0 or a 1. Apparently the if then else solution has a jump when written out in assembly. if (x == 0) y=0 else y =x
- (a-1) xor a == 0 - What does this do?
- How can you print singly linked list in reverse order? (it's a huge list and you cant use recursion)
- How can you find out if there is a loop in a very long list?
- A character set has 1 and 2 byte characters. One byte characters have 0 as the first bit. You just keep accumulating the characters in a buffer. Suppose at some point the user types a backspace, how can you remove the character efficiently. ( Note: You cant store the last character typed because the user can type in arbitrarily many backspaces)
- How would you reverse the bits of a number with log N arithmetic operations, where N is the number of bits in the integer (eg 32,64..)
- Whats the simples way to check if the sum of two unsigned integers has resulted in an overflow.
- Induction on i:1..n: Maintain the subarray with largest sum and suffix with largest sum and then update both after adding the i+1th element...
- Sum of the numbers or copy i into A[i] so on till conflict.
- Update deltaY while incrementing x. Have to multiply so that the deltay is not a floating pt number.
- Find the largest 10**n less than given number, then div etc.
- Infinite.
- Shivku said this question is garbled thru ages.
- reverse the pointers till you reach the end and print-and-reverse as you return.
- Have two 'threads' one at twice the speed of the other traversing the list and see if at anytime they meet.
- Scan the bytes backward till you reach one with the first bit set to 0. Now this is either a one byte character or the second byte of a two byte one. Either way it marks a Character boundary. Start from there an scan forward to find what the last character is.
- Flip adjacent bits, then flip adjacent 2 bit sets, then 4-bits and so on. Each of this swap can be done in constant time using appropriate masks and shifts.
- if (a+b) < a or (a+b) < b then overflow has occurred
Data structures and algorithms questions
- Write a function and the node data structure to visit all of the nodes in a binary tree.
- You know what a queue is .... Implement a queue class with Java. What is the cost of enqueue and dequeue? Can you improve this? What if the queue is full (I was using an looping array)? What kind of mechanism would you use to increase its size?
- Give an algorithm that calculates the distance between two text strings (only operations you can have are: delete, add, and change, one by one).
- Given the definition of a sequence (5 4 7 6 is, but 1 2 4 5 is not), write an algorithm to check if an arbitrary array is a sequence or not. Once I figured out a solution, I was asked to do a space and time complexity analysis.
- Describe a situation where concurrent access would lead to inconsistency in your application. How would you solve this problem?
- You are given a list of n numbers from 1 to n-1, with one of the numbers repeated. Devise a method to determine which number is repeated.
- Write an algorithm to detect loop in a linked list.
- Given the time, devise an algorithm to calculate the angle between the hour and minute hands of an analog clock.
- Devise an algorithm for detecting whether a given string is a palindrome (spelled the same way forwards and backwards). For example, "A man, a plan, a canal, Panama."
- Given an eight-bit bitmap graphics file, devise an algorithm to convert the file into a two-bit ASCII approximation.
- Reverse a linked list.
- Insert in a sorted list
- First some definitions for this problem: a) An ASCII character is one byte long and the most significant bit in the byte is always '0'. b) A Kanji character is two bytes long. The only characteristic of a Kanji character is that in its first byte the most significant bit is '1'. Now you are given an array of a characters (both ASCII and Kanji) and, an index into the array. The index points to the start of some character. Now you need to write a function to do a backspace (i.e. delete the character before the given index).
- Delete an element from a doubly linked list.
- Write a function to find the depth of a binary tree.
- Assuming that locks are the only reason due to which deadlocks can occur in a system. What would be a foolproof method of avoiding deadlocks in the system.
- Besides communication cost, what is the other source of inefficiency in RPC?
- Ways of optimizing symbol table storage in compilers.
- A walk-through through the symbol table functions, lookup() implementation etc - The interv. was on the Microsoft C team.
- Given an array t[100] which contains numbers between 1..99. Return the duplicated value. Try both O(n) and O(n-square).
- Given an array of characters. How would you reverse it. ? How would you reverse it without using indexing in the array.
- Given a sequence of characters. How will you convert the lower case characters to upper case characters. ( Try using bit vector - sol given in the C lib -> typec.h)
- Give a good data structure for having n queues ( n not fixed) in a finite memory segment. You can have some data-structure separate for each queue. Try to use at least 90% of the memory space.
- Do a breadth first traversal of a tree.
- Given a list of numbers ( fixed list) Now given any other list, how can you efficiently find out if there is any element in the second list that is an element of the first list (fixed list).
- What is a balanced tree
- How would you find a cycle in a linked list? Try to do it in O(n) time. Try it using a constant amount of memory.
- Implement an algorithm to reverse a doubly linked list.
- A square picture is cut into 16 squares and they are shuffled. Write a program to rearrange the 16 squares to get the original big square.
- The Web can be modeled as a directed graph. Come up with a graph traversal algorithm. Make the algorithm non-recursive and breadth-first.
- How would you implement a hash table ? How do you deal with collisions?
- How would you find a cycle in a linked list? Try to do it in O(n) time. Try it using a constant amount of memory.
- Given a history of URLs, how would you determine if a particular URL had been seen before?
- Since pages can have multiple URLs pointing to them, how can you make sure you've never seen the same CONTENT before?
- Write a function to print all of the permutations of a string.
- Come up with the plan on how to traverse a graph, as well as to quickly determine if a given URL is one of the million or so you've previously seen.
- The Web can be modeled as a directed graph. Come up with a graph traversal algorithm. Make the algorithm non-recursive and breadth-first.
- Implement an algorithm to reverse a singly linked list. (with and without recursion)
- Implement an algorithm to reverse a doubly linked list.
- Implement an algorithm to insert in a sorted list.
- Delete an element from a doubly linked list.
- Write a function to copy two strings, A and B. The last few bytes of string A overlap the first few bytes of string B.
- Implement an algorithm to sort an array.
- Given a sequence of characters, how will you convert the lower case characters to upper case characters?
- Write a routine that prints out a 2-D array in spiral order.
- Count the number of set bits in a number without using a loop.
- Give me an algorithm and C code to shuffle a deck of cards, given that the cards are stored in an array of ints. Try to come up with a solution that does not require any extra space.
- Write a function that takes in a string parameter and checks to see whether or not it is an integer, and if it is then return the integer value.
- How would you print out the data in a binary tree, level by level, starting at the top?
- Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words in it.
- Write a function to find the depth of a binary tree.
- Given a list of numbers ( fixed list) Now given any other list, how can you efficiently find out if there is any element in the second list that is an element of the first list (fixed list).
- How would you implement a queue from a stack?
- Write a funtion that finds repeating characters in a string.
- Write a routine to reverse a series of numbers without using an array.
- Give me an algorithm for telling me the number I didn't give you in a given range of numbers. (Numbers are given at random)
From CSRI
- Write a function to check if two rectangles defined as below overlap or not.
struct rect {
int top, bot, left, right;
} r1, r2;
- Write a program to print the elements of a very long linked list in ascending order. There may be duplicates in the list. You cannot modify the list or create another one. Memory is tight, speed is not a problem.
- Write a function to reverse a singly linked list, given number of links to reverse.
- Write a function to convert an int to a string.
- Some weird problem on vector calculus with some transformation matrices being applied - need paper and pencil to describe it.
- Given ships travel between points A and B, one every hour leaving from both ends (simultaneously), how many ships are required (minimum), if the journey takes 1hr 40 mts. How many ships does each ship encounter in its journey, and at what times?
- Write a SetPixel(x, y) function, given a pointer to the bitmap. Each pixel is represented by 1 bit. There are 640 pixels per row. In each byte, while the bits are numbered right to left, pixels are numbered left to right. Avoid multiplications and divisions to improve performance.
- How do you represent an n-ary tree? Write a program to print the nodes of such a tree in breadth first order.
- Write the 'tr' program of UNIX. Invoked as
tr -str1 -str2.
It reads stdin and prints it out to stdout, replacing every occurance of str1[i] with str2[i]. eg.
tr -abc -xyz
to be and not to be <- input
to ye xnd not to ye <- output
C syntax, semantics and simple programming questions
- What does the term cast refer to? Why is it used?
- In arithmetic expressions, to what data type will the C compiler promote a character?
- What is the difference between a statement and a block?
- Increment the variable next three different ways.
- How is a comment formed in C.
- Can comments be nested?
- From the standpoint of programming logic, what is the difference between a loop with the test at the top, and a loop where the test is at the bottom?
- Specify the skeletons of two C loops with the test at the top.
- Specify a C loop with the test at the bottom.
- What is the switch statement?
- What does a break statement do? Which control structures use it?
- In a loop, what is the difference between a break and continue statement?
- Where may variables be defined in C?
- What is the difference between a variable definition and a variable declaration?
- What is the purpose of a function prototype?
- What is type checking?
- To what does the term storage class refer?
- List C's storage classes and what they signify.
- State the syntax for the printf() and scanf() functions. State their one crucial difference with respect to their parameters.
- With respect to function parameter passing, what is the difference between call-by-value and call-by-reference? Which method does C use?
- What is a structure and a union in C?
- Define a structure for a simple name/address record.
- What does the typedef keyword do?
- Use typedef to make a short-cut way to declare a pointer to the nameAddr structure above. Call it addrPtr.
- Declare a variable with addrPtr called address.
- Assuming the variable address above, how would one refer to the city portion of the record within a C expression?
- What is the difference between: #include <stdio.h> and #include "stdio.h"
- What is #ifdef used for?
- How do you define a constant in C?
- Why can't you nest structure definitions?
- Can you nest function definitions?
- What is a forward reference?
- What are the following and how do they differ: int, long, float and double?
- Define a macro called SQR which squares a number.
- Is it possible to take the square-root of a number in C. Is there a square-root operator in C?
- Using fprintf() print a single floating point number right-justified in a field of 20 spaces, no leading zeros, and 4 decimal places. The destination should be stderr and the variable is called num.
- What is the difference between the & and && operators and the | and || operators?
- What is the difference between the -> and . operators?
- What is the symbol for the modulus operator?
- From the standpoint of logic, what is the difference between the fragment:
if (next < max)
next++;
else
next = 0;
and the fragment:
next += (next < max)? (1):(-next);
- What does the following fragment do?
while((d=c=getch(),d)!=EOF&&(c!='\t'||c!=' '||c!='\b')) *buff++ = ++c;
- Is C case sensitive (ie: does C differentiate between upper and lower case letters)?
- Specify how a filestream called inFile should be opened for random reading and writing. the file's name is in fileName.
- What does fopen() return if successful. If unsuccessful?
- What is the void data type? What is a void pointer?
- Declare a pointer called fnc which points to a function that returns an unsigned long.
- Declare a pointer called pfnc which points to a function that returns a pointer to a structure of type nameAddr.
- It is possible for a function to return a character, an integer, and a floating point number. Is it possible for a function to return a structure? Another function?
- What is the difference between an lvalue and an rvalue?
- Given the decimal number 27, how would one express it as a hexadecimal number in C?
- What is malloc()?
- What is the difference between malloc() and calloc()?
- What kind of problems was C designed to solve?
- write C code for deleting an element from a linked listy traversing a linked list efficient way of elimiating duplicates from an array
- Declare a void pointer
- Make the pointer aligned to a 4 byte boundary in a efficient manner
- What is a far pointer (in DOS)
- Write an efficient C code for 'tr' program. 'tr' has two command line arguments. They both are strings of same length. tr reads an input file, replaces each character in the first string with the corresponding character in the second string. eg. 'tr abc xyz' replaces all 'a's by 'x's, 'b's by 'y's and so on.
- Write C code to implement strtok() 'c' library function.
- Implement strstr(), strcpy(), strtok() etc
- Reverse a string.
- Given a linked list which is sorted, how will you insert in sorted way.
- Write a function that allocates memory for a two-dimensional array of given size (parameter x & y)
- Write source code for printHex(int i) in C/C++
- Write a function that finds the last instance of a character in a string.
C++ syntax, semantics and concepts questions
- What is an object in C++?
- What is a message?
- What is a class?
- What is an instance?
- What is a super-class?
- What is inheritance?
- To what does message protocol refer?
- What is polymorphism?
- What are instance variables?
- What are class variables?
- What is a method?
- In C++ what is a constructor? A destructor?
- Compare and contrast C and C++.
- What is operator overloading?
- What is cin and cout?
- Contrast procedural and object oriented programming.
- How do you link a C++ program to C functions?
- Explain the scope resolution operator.
- What are the differences between a C++ struct and C++ class?
- How many ways are there to initialize an int with a constant?
- How does throwing and catching exceptions differ from using setjmp and longjmp?
- What is your reaction to this line of code?
delete this;
- What is a default constructor?
- What is a conversion constructor?
- What is the difference between a copy constructor and an overloaded assignment operator?
- When should you use multiple inheritance?
- What is a virtual destructor?
- Explain the ISA and HASA class relationships. How would you implement each in a class design?
- When is a template a better solution than a base class?
- What is the result of compiling this program in a C compiler? in a C++ compiler?
int __ = 0;
main() {
int ___ = 2;
printf("%d\n", ___ + __);
}
- What is the difference between C and C++ ? Would you prefer to use one over the other ?
- What are the access privileges in C++ ? What is the default access level ?
- What is data encapsulation ?
- What is inheritance ?
- What is multiple inheritance ? What are it's advantages and disadvantages ?
- What is polymorphism?
- What do the keyword static and const signify ?
- How is memory allocated/deallocated in C ? How about C++ ?
- What is UML ?
- What is the difference between a shallow copy and a deep copy ?
- What are the differences between new and malloc?
- What is the difference between delete and delete[]?
- What are the differences between a struct in C and in C++?
- What are the advantages/disadvantages of using #define?
- What are the advantages/disadvantages of using inline and const?
- What is the difference between a pointer and a reference?
- When would you use a pointer? A reference?
- What does it mean to take the address of a reference?
- What does it mean to declare a function or variable as static?
- What is the order of initalization for data?
- What is name mangling/name decoration?
- What kind of problems does name mangling cause?
- How do you work around them?
- What is a class?
- What are the differences between a struct and a class in C++?
- What is the difference between public, private, and protected access?
- For class CFoo { }; what default methods will the compiler generate for you>?
- How can you force the compiler to not generate them?
- What is the purpose of a constructor? Destructor?
- What is a constructor initializer list?
- When must you use a constructor initializer list?
- What is a: Constructor? Destructor? Default constructor? Copy constructor? Conversion constructor?
- What does it mean to declare a... member function as virtual? member function as static? member varible as static? destructor as static?
- Can you explain the term "resource acqusition is initialization?"
- What is a "pure virtual" member function?
- What is the difference between public, private, and protected inheritance?
- What is virtual inheritance?
- What is placement new?
- What is the difference between operator new and the new operator?
- What is exception handling?
- Explain what happens when an exception is thrown in C++.
- What happens if an exception is not caught?
- What happens if an exception is throws from an object's constructor?
- What happens if an exception is throws from an object's destructor?
- What are the costs and benefits of using exceptions?
- When would you choose to return an error code rather than throw an exception?
- What is a template?
- What is partial specialization or template specialization?
- How can you force instantiation of a template?
- What is an iterator?
- What is an algorithm (in terms of the STL/C++ standard library)?
- What is std::auto_ptr?
- What is wrong with this statement? std::auto_ptr ptr(new char[10]);
- It is possible to build a C++ compiler on top of a C compiler. How would you do this?
- What output does the following code generate? Why? What output does it generate if you make A::Foo() a pure virtual function?
- What output does this program generate as shown? Why?
- C++ ( what is virtual function ? what happens if an error occurs in constructor or destructor. Discussion on error handling, templates, unique features of C++. What is different in C++, ( compare with unix).
- I was given a c++ code and was asked to find out the bug in that. The bug was that he declared an object locally in a function and tried to return the pointer to that object. Since the object is local to the function, it no more exists after returning from the function. The pointer, therefore, is invalid outside.
Questions for ANSI-Knowledgeable Applicants
- What is a mutable member?
- What is an explicit constructor?
- What is the Standard Template Library?
- Describe run-time type identification.
- What problem does the namespace feature solve?
- Are there any new intrinsic (built-in) data types?
Design
- Draw a class diagram (UML) for a system. (They described the system in plain english).
- Which do you prefer, inheritance or delegation? Why?
- What is the difference between RMI and IIOP?
Java questions
- http://www.javaprepare.com/quests/question.html
Misc. Questions (Design pattern, HTTP, OOP, SQL)
- What's the difference between SQL, DDL, and DML?
- What's a join? An inner join? An outer join?
- Describe HTTP.
- What's a design pattern?
- Can you explain the singleton, vistor, facade, or handle class design pattern?
- When you do an ls -l, describe in detail everything that comes up on the screen.
- Tell me three ways to find an IP address on a Unix box.
- Write a bubble sort.
- Write a linked list.
- Describe an object.
- What does object-oriented mean to you.
- Can you explain what a B tree is?
- What's the difference between UDP and TCP?
- What is ICMP?
- What's the difference between a stack and a Queue?
- Do you know anything about the protection rings in the PC architecture?
- How much hardware/Assembler/Computer Architecture experience do you have.
- Explain final, finalize, and finally. When the finalize is invoked? How does GC work? etc.
- What is your experience with Servlet and JSP?
- What is the Prototype design pattern?
- In a system that you are designing and developing, a lot of small changes are expected to be committed at the end of a method call (persisted to the DB). If you don't want to query the database frequently. what would you do?
- Give an example in which you will combine several design patterns, and explain how the system can benefit from that.
- Why would you apply design patterns (benefits)?
- What is a two-phase commit?
- What will happen if one of your web-server or appserver crashs during its execution?
- What are various problems unique to distributed databases
- Describe the file system layout in the UNIX OS
- what is disk interleaving
- why is disk interleaving adopted
- given a new disk, how do you determine which interleaving is the best
- give 1000 read operations with each kind of interleaving determine the best interleaving from the statistics
- draw the graph with performace on one axis and 'n' on another, where 'n' in the 'n' in n-way disk interleaving. (a tricky question, should be answered carefully)
- Design a memory management scheme.
- What sort of technique you would use to update a set of files over a network, where a server contains the master copy.
General questions
- How did you get into computer science?
- What kind of technical publications (print or online) do you read on a regular basis?
- What was the last book you read (does not have to be job related!)
- If you could recommend one resource (book, web site, etc.) to a new software developer just out of school, what would it be?
- What was the most interesting project that you worked on?
- What was the most challenging project that you worked on?
- If you could have any job in the world, what would it be?
- Tell me about your favorite class.
- Tell me about your favorite project [with lots of follow-up questions].
- Tell me about a something you did that was unsuccessful, a project or class that didn't go well.
- Do you prefer a structured or unstructured working environment.
- A chemist calls you up and says his Netscape isn't working. What's wrong and how do you find out?
- How do you prioritize multiple projects?
- Tell me about previous jobs?
- What are your greatest strengths and weaknesses?
- Tell us about yourself.
- Where would you like to be in five years?
- How do you see yourself fitting in to this company?
- Do you have any questions for me?
- Why did you leave your last job.
- Did you finance your own education?
- Are you good with people?
- Have you experience working on a group project?
- How well do you know the windows menus?
- What was the hardest program error for you to find and correct?
- What did you find hardest when working with others in a project?
- What is a tool or system that you learned on your own? i.e. not in a class room?
- As a developer, would you prefer to use application server? Why?
- How would go about finding out where to find a book in a library. (You don't know how exactly the books are organized beforehand).
- Tradeoff between time spent in testing a product and getting into the market first.
- What to test for given that there isn't enough time to test everything you want to.
- Why do u think u are smart.
- Questions on the projects listed on the Resume.
- Do you want to know any thing about the company.( Try to ask some relevant and interesting question).
- How long do u want to stay in USA and why?
- What are your geographical preference?
- What are your expectations from the job.
Questions and Answers
- Introduction
The technical interview is perhaps the most intimidating and mysterious event that job hunters experience in the quest for that "killer offer." The rigor and format of the technical interview varies from one company to the next, but there are some fundamental similarities. An interviewer presents you with a problem to be solved. The interviewer may leave the room and give you some time to work the solution out before returning. Or the interviewer may wait patiently while you study the problem and figure it out. The interviewer may even start quizzing you right away about aspects of the problem and approaches to solving it. Some of these problems can appear quite challenging, especially if you've never been through a technical interview before. To make matters worse, simply getting the answer to the problem may not be enough to land the job. On the other hand, getting the correct answer may not even be necessary. What is an interviewer looking for in candidates during the technical interview? Interviewers recognize that this setting is, by its very nature, stressful. Otherwise competent candidates may be completely stumped by an interview problem only to discover an elegant, simple solution later that night. Interviewers may be interested in seeing how you work under stressful situations or how well you adapt. It is worth noting that interviewers are more interested in seeing how you work than seeing whether you can come up with the correct answer. In this article, I will deal with both how you can better showcase your skills and experience, and what kinds of problems you can expect to be asked.
- The Basic Rules
These basic rules are often taught to programmers and are (or at any rate, should be) drilled into your head in computer-science classes. For some reason, however, they are easily forgotten during the technical interview. Being one of the few candidates careful and experienced enough to remember these important steps can make the difference between getting an offer and getting the cold shoulder. Don't be afraid to ask for clarifications of the problem or the requirements for the solution.
- Don't assume all data is given to you.
You should never assume that you have been given all the data necessary to solve the problem to the satisfaction of the interviewer. This is especially likely to be the case when interviewing with IT consulting companies. In this environment, the client may need some prodding in order to provide a complete specification. So, the reasoning goes, ideal candidates will be willing to talk to the client to figure out the expected inputs, the desired outputs, the data ranges and data types, and the special cases. The ideal candidate will ask these questions rather than spend all the allotted time coming up with a solution that doesn't meet the client's needs. The first thing to do, then, is to make sure that you and the interviewer agree on what the problem is and what an acceptable solution would be. Make all of your assumptions explicit and up-front, so the interviewer can correct you if you are mistaken.
- Think out loud.
If the interviewer stays in the room after presenting the problem, he or she is interested in seeing how you analyze and approach a problem. Of interest are how possible solutions are considered and eliminated. And frankly, watching a candidate sit and stare at a problem isn't all that entertaining for the interviewer. Always allow sufficient time for design. The worst thing that you can do while attempting to solve a technical problem is to dive right into coding a solution and get about half way through it before realizing that the approach is all wrong. This is where a little forethought can save a great deal of effort and embarrassment. Don't worry about running out of time to answer the question before finishing the code for the solution. The idea, the algorithm, and the approach are the most important elements here. If you're having trouble writing the code, offer to explain the algorithm. Stress and anxiety can make the technical interview more difficult than it needs to be. If you find yourself having difficulty with programming syntax or constructs, you should make sure that the interviewer knows that you understand the problem and its solution. While it's best to get both the algorithm and the implementation correct, it's far better to get points for demonstrating facility with one than fail to demonstrate either. Be prepared to identify bottlenecks, possible optimizations, and alternative algorithms. Just because you've found one solution that produces the correct output, doesn't mean the problem has been solved to the interviewer's satisfaction. Interviewers, hinting at possible improvements, may prod you at this point. Occasionally, you may take an approach that the interviewer didn't anticipate. At this point, an interviewer may ask you to take a more conventional approach. This doesn't mean that you've done anything wrong; very often, an interviewer may be leading you along a particular approach with a purpose in mind. The interviewer may be intending to ask follow-up questions or present new problems that build on a particular solution.
- Good programming practice.
Initialize all variables, give variables descriptive names, and always use comments.
Interviewers may be watching your solutions to determine whether you follow good programming practices. Good programming practices make it easy to understand other people's code. This means that there aren't cryptic variables, functions with undocumented side effects, obfuscated algorithms, and sloppy (read: buggy) code. Just because you are being interviewed (and therefore, coding on a whiteboard or on a piece of paper) doesn't give you an excuse to be sloppy or lazy. Commenting code for an interview may seem like a waste of time, but some interviewers do look to see that candidates write comments while coding or before coding, rather than adding them in as an afterthought.
- Check all boundary conditions.
Candidates forget to do this frighteningly often. In fact, practicing programmers sometimes forget to do this. That's how bugs get started. You should verify that your code properly handles cases where inputs are negative or zero, lists are empty, strings are empty, and pointers are NULL. This is also a good habit to have after you get the job. Expect bad input from users. Users rarely do as they are expected. You should protect your code, and return a descriptive error back to the user. Display enthusiasm. Don't underestimate the importance of your appearance and attitude during the interview. While your skills and experience may be the focus of the technical interview, looking bored or uninterested may do more to sabotage your chances than blowing an interview problem.
- Work Things Into Your Conversations
In addition to these basic rules for the technical interview, there are some other things worth pointing out. Interviewers don't always have the chance to examine your r閟um?in advance. This means that the interviewer may not be aware of your past work experience. Don't hesitate to point out experiences working in teams (whether as a part of a past job, a class programming project, or a hobby), working on large projects (paying attention to time spent on design, implementation, and testing), dealing with customers to define requirements, and managing people and projects. Interviewers are interested in hearing about successes as well as failures. When these past experiences weren't successful, you should point out the lessons learned or wisdom gained as a result of these failures. Interviewers want to see that candidates who have had negative experiences are not going to repeat their mistakes.
- Typical Technical Questions
When preparing for a technical interview, you should review basic structures (linked lists, binary trees, heaps) and algorithms (searching, sorting, hashing). Having a mastery of these topics will likely give you all the necessary knowledge to tackle the problems you will encounter during the technical interview. Also, review the areas for which you're interviewing. If you're interviewing for a systems programming job, review the differences between threads and processes, OS scheduling algorithms, and memory allocation. If you're interviewing for a job that requires experience with an object- oriented language, spend some time brushing up on object-oriented methodology.
Fortunately, some of the same problems come up with surprising frequency. Even if a given interviewer doesn't use any of the problems I present here, studying them should give you insight into solving other problems.
- Conclusion
The specific details of your interview will, of course, depend on a number of factors -- the type of job you are applying for, the needs and expertise of the technical interviewer, and guidelines set forth by the organization seeking to hire you. Still, if you generalize and apply the tips I've presented here, you should be well on your way to getting the programming job that you want.
- Given a rectangular (cuboidal for the puritans) cake with a rectangular piece removed (any size or orientation), how would you cut the remainder of the cake into two equal halves with one straight cut of a knife ?
The cut (plane) should pass through the center of the two rectangles: the outer cake and the inner hollow area. Since any plane passing through the center of the cuboid will divide the volume in two halves, both the cake and hollow area are divided into two equal halves.
- You're given an array containing both positive and negative integers and required to find the subarray with the largest sum (O(N) a la KBL). Write a routine in C for the above.
- Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like.
Many solutions: Bit vector, sorting...
- Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.
- How many points are there on the globe where by walking one mile south, one mile east and one mile north you reach the place where you started.
The answer is "many points". The set of such points is given as {North pole, special circle}.
From north pole, walking one mile south followed by one mile east still keeps you one mile south of North pole.
The special circle consists of a set of points defined as follows. Let's say you were to locate a spot near the South Pole where the circular distance "around" the Earth's North-South axis is 1 mile. The path of such a journey would create a circle with a radius of approximately 840.8 feet (because C=2.r.pi). Call this point X. Now consider another point Y one mile north of X. The special circle is the circular path around North-South axis going through Y. If you begin you journey from any point (say Y1) on this special circle, and travel one mile south, you get to a point (say X1) on the circle of point X. Now one mile east will bring you back to X1, because circumference of circle of X is 1 mile. Then one mile North brings you back to Y1. (Answer supplied by Kristie Boman)
- In a X's and 0's game (i.e. TIC TAC TOE) if you write a program for this give a fast way to generate the moves by the computer. I mean this should be the fastest way possible.
The answer is that you need to store all possible configurations of the board and the move that is associated with that. Then it boils down to just accessing the right element and getting the corresponding move for it. Do some analysis and do some more optimization in storage since otherwise it becomes infeasible to get the required storage in a DOS machine.
- A version of the "There are three persons X Y Z, one of which always lies"..
- There are 3 ants at 3 corners of a triangle, they randomly start moving towards another corner.. what is the probability that they don't collide.
All three should move in the same direction - clockwise or anticlockwise. Probability is 1/4.
- If you are on a boat and you throw out a suitcase, Will the level of water increase.
- There are 4 men who want to cross a bridge. They all begin on the same side. You have 17 minutes to get all of them across to the other side. It is night. There is one flashlight. A maximum of two people can cross at one time. Any party who crosses, either 1 or 2 people, must have the flashlight with them. The flashlight must be walked back and forth, it cannot be thrown, etc. Each man walks at a different speed. A pair must walk together at the rate of the slower mans pace.
Man 1:1 minute to cross
Man 2: 2 minutes to cross
Man 3: 5 minutes to cross
Man 4: 10 minutes to cross
1 and 2 cross together. 1 comes back. then 3 and 4 cross. 2 comes back. then 1 and 2 cross. Total time is 2+1+10+2+2 = 17.
- You have 5 jars of pills. Each pill weighs 10 gram, except for contaminated pills contained in one jar, where each pill weighs 9 gm. Given a scale, how could you tell which jar had the contaminated pills in just one measurement?
Take one pill from first, two from second, three from third and so on. Total pills are n(n+1)/2 and should weigh 10n(n+1)/2. If it weighs x gm less than that then the x'th jar is contaminated, since we took x pills from that jar which weighed 1 gm less.
- One train leaves Los Angeles at 15 MPH heading for New York. Another train leaves from New York at 20mph heading for Los Angeles on the same track. If a bird, flying at 25mph, leaves from Los Angeles at the same time as the train and flies back and forth between the two trains until they collide, how far will the bird have traveled?
If distance is X miles between NY and LA, then it takes X/(15+20) hours for the trains to collide, and bird will have travelled 25X/(15+20) = 5X/7 miles in that time.
- Imagine that you have 26 constants, labelled A through Z. Each constant is assigned a value in the following way: A = 1; the rest of the values equal their position in the alphabet (B corresponds to the second position so it equals 2, C = 3, etc.) raised to the power of the preceeding constant value. So, B = 2 ^ (A's value), or B = 2^1 = 2. C = 3^2 = 9. D = 4^9, etc., etc. Find the exact numerical value to the following equation:
(X - A) * (X - B) * (X - C) * ... * (X - Y) * (X - Z)
Answer is 0, because (X-X) is present in the product.
- You have 12 balls. All of them are identical except one, which is either heavier or lighter than the rest - it is either hollow while the rest are solid, or solid while the rest are hollow. You have a simple two-armed scale, and are permitted three weighings. Can you identify the odd ball, and determine whether it is hollow or solid.
Let the balls be numbered 1 to 12. Firstly, put 1-4 on one side and 5-8 on other side. If both are equal then one of 9-12 is odd. Then second try, weigh 9-10 vs 1-2, if equal, one of 11-12 is bad, else 9-10 is bad. Testing which one is bad can be done by (third try) weighing 11 or 9, respectively, with good ball 1. It also gives whether the odd ball is heavy or light.
- Write a routine to draw a circle (x ** 2 + y ** 2 = r ** 2) without making use of any floating point computations at all.
The basic idea is to draw one quadrant and replicate it to other four quadrants. Assuming the center is given as (x,y) and radius as r units, then start X from (x+r) down to (x) and start Y from y up to (y+r). In the iteration, keep comparing is the equation is satisfied or not within an error of one unit for x and y. If not then re-adjust X and Y.
- Given only putchar (no sprintf, itoa, etc.) write a routine putlong that prints out an unsigned long in decimal.
void putlong(unsigned long x)
{
// we know that 32 bits can have 10 digits. 2^32 = 4294967296
for (unsigned long y = 1000000000; y > 0; y /= 10) {
putchar( (x / y) + '0');
x = x % y;
}
}
- Give a one-line C expression to test whether a number is a power of 2. [No loops allowed - it's a simple test.]
if (x && !(x & (x-1)) == 0)
- Give a very good method to count the number of ones in a 32 bit number. (caution: looping through testing each bit is not a solution).
- What are the different ways to say, the value of x can be either a 0 or a 1.
Apparently the if then else solution has a jump when written out in assembly.
if (x == 0)
y=0
else
y =x
There is a logical, arithmetic and a datastructure soln to the above problem.
- I was given two lines of assembly code which found the absolute value of a number stored in two's complement form. I had to recognize what the code was doing.
Pretty simple if you know some assembly and some fundaes on number representation.
- Give a fast way to multiply a number by 7.
Multiply by 8 (left shift by 3 bits) and then subtract the number.
(x << 3) - x
- Write an efficient algo and C code to shuffle a pack of cards.. this one was a feedback process until we came up with one with no extra storage.
- A real life problem - A square picture is cut into 16 sqaures and they are shuffled. Write a program to rearrange the 16 squares to get the original big square.
- Consider the base -2 representation of numbers. (-2 instead of usual +2). Give the condition for a number represented in this form to be positive? Also, if P(A, B) is a function that takes two 0-1 strings A,B in this representation, when can we say that P(A,B) returns the sum of these two numbers?
- Given an expression tree with no parentheses in it, write the program to give equivalent infix expression with parentheses inserted where necessary.
- Given a maze with cheese at one place and a mouse at some entrance, write a program to direct the mouse to cheese correctly. (Assume there is a path). Following primitives are given: moveforward, turnright, turnleft, iswall?, ischeese?, eatcheese.
- Give me an algorithm and C code to find the subarray with the largest sum given an array containing both positive and negative integers.
- Write a function that returns the factorial of a number.
This is a typical, can-you-program warm-up question. Example 1 shows the iterative and recursive solutions. Notice that in both solutions, I check the input values and boundary conditions. Factorials of negative numbers are undefined, and the factorial of both 0 and 1 are 1. The functions in Example 1 handle these cases correctly, and they initialize all variables.
- Write a function that computes the nth number in the Fibonacci sequence.
Example 2 contains both the iterative and recursive solutions. The iterative version maintains variables to hold the last two values in the Fibonacci sequence, and uses them to compute the next value. Again, boundary conditions and inputs are checked. The 0th number in the Fibonacci sequence is defined as 0. The first number in the sequence is 1. Return -1 if a negative number is passed.
The recursive version of the Fibonacci function works correctly, but is considerably more expensive than the iterative version. There are, however, other ways to write this function recursively in C that are not as expensive. For instance, you could maintain static variables or create a struct to hold previously computed results.
- Write an implementation of strlen().
Given a char pointer, strlen() determines the number of chars in a string. The first thing that your strlen() implementation ought to do is to check your boundary conditions. Don't forget the case where the pointer you are given is pointing to an empty string. What about the case where the pointer is equal to NULL? This is a case where you should state your assumptions. In many implementations, the real strlen() doesn't check to see if the pointer is NULL, so passing a NULL pointer to strlen() would result in a segmentation fault. Making it clear to your interviewer that you are aware of both of these boundary conditions shows that you understand the problem and that you have thought about its solution carefully. Example 3 shows the correct solution.
- Switch the integer values stored in two registers without using any additional memory.
To swap the values, you can carry out the following instructions:
Reg_1 = Reg_1 + Reg_2;
Reg_2 = Reg_1 - Reg_2;
Reg_1 = Reg_1 - Reg_2;
- Given two strings S1 and S2. Delete from S2 all those characters which occur in S1 also and finally create a clean S2 with the relevant characters deleted.
- Write a small lexical analyzer - interviewer gave tokens. expressions like "a*b" etc.
- Write a routine that prints out a 2-D array in spiral order!
- How is the readers-writers problem solved? - using semaphores/ada .. etc.
- Write code for reversing a linked list.
- Write, efficient code for extracting unique elements from a sorted list of array. e.g. (1, 1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9) -> (1, 3, 5, 9).
int main()
{
int a[10]={1, 2, 4, 4, 7, 8, 9, 14, 14, 20};
int i;
for (i = 0;i<9;i++)
{
if (a[i] != a[i+1])
printf("%d\n",a[i]);
}
return 0;
}
- Given a rectangular (cuboidal for the puritans) cake with a rectangular piece removed (any size or orientation), how would you cut the remainder of the cake into two equal halves with one straight cut of a knife ?
- You're given an array containing both positive and negative integers and required to find the subarray with the largest sum (O(N) a la KBL). Write a routine in C for the above.
- Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like.[I ended up giving about 4 or 5 different solutions for this, each supposedly better than the others ].
- Write a routine to draw a circle (x ** 2 + y ** 2 = r ** 2) without making use of any floating point computations at all. [ This one had me stuck for quite some time and I first gave a solution that did have floating point computations ].
- Given only putchar (no sprintf, itoa, etc.) write a routine putlong that prints out an unsigned long in decimal. [ I gave the obvious solution of taking % 10 and / 10, which gives us the decimal value in reverse order. This requires an array since we need to print it out in the correct order. The interviewer wasn't too pleased and asked me to give a solution which didn't need the array ].
- Give a one-line C expression to test whether a number is a power of 2. [No loops allowed - it's a simple test.]
- Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.
- How many points are there on the globe where by walking one mile south, one mile east and one mile north you reach the place where you started.
- Give a very good method to count the number of ones in a 32 bit number. (caution: looping through testing each bit is not a solution).
- What are the different ways to say, the value of x can be either a 0 or a 1. Apparently the if then else solution has a jump when written out in assembly. if (x == 0) y=0 else y =x
- (a-1) xor a == 0 - What does this do?
a is a power of 2.
- How can you print singly linked list in reverse order? (it's a huge list and you cant use recursion)
- How can you find out if there is a loop in a very long list?
- A character set has 1 and 2 byte characters. One byte characters have 0 as the first bit. You just keep accumulating the characters in a buffer. Suppose at some point the user types a backspace, how can you remove the character efficiently. ( Note: You cant store the last character typed because the user can type in arbitrarily many backspaces)
- How would you reverse the bits of a number with log N arithmetic operations, where N is the number of bits in the integer (eg 32,64..)
- Whats the simples way to check if the sum of two unsigned integers has resulted in an overflow.
- Induction on i:1..n: Maintain the subarray with largest sum and suffix with largest sum and then update both after adding the i+1th element...
- Sum of the numbers or copy i into A[i] so on till conflict.
- Update deltaY while incrementing x. Have to multiply so that the deltay is not a floating pt number.
- Find the largest 10**n less than given number, then div etc.
- Infinite.
- Shivku said this question is garbled thru ages.
- reverse the pointers till you reach the end and print-and-reverse as you return.
- Have two 'threads' one at twice the speed of the other traversing the list and see if at anytime they meet.
- Scan the bytes backward till you reach one with the first bit set to 0. Now this is either a one byte character or the second byte of a two byte one. Either way it marks a Character boundary. Start from there an scan forward to find what the last character is.
- Flip adjacent bits, then flip adjacent 2 bit sets, then 4-bits and so on. Each of this swap can be done in constant time using appropriate masks and shifts.
- if (a+b) < a or (a+b) < b then overflow has occurred
- Write a function and the node data structure to visit all of the nodes in a binary tree.
- You know what a queue is .... Implement a queue class with Java. What is the cost of enqueue and dequeue? Can you improve this? What if the queue is full (I was using an looping array)? What kind of mechanism would you use to increase its size?
- Give an algorithm that calculates the distance between two text strings (only operations you can have are: delete, add, and change, one by one).
- Given the definition of a sequence (5 4 7 6 is, but 1 2 4 5 is not), write an algorithm to check if an arbitrary array is a sequence or not. Once I figured out a solution, I was asked to do a space and time complexity analysis.
- Describe a situation where concurrent access would lead to inconsistency in your application. How would you solve this problem?
- You are given a list of n numbers from 1 to n-1, with one of the numbers repeated. Devise a method to determine which number is repeated.
The sum of the numbers 1 to n-1 is (n)(n-1)/2. Add the numbers on the list, and subtract (n)(n-1)/2. The result is the number that has been repeated.
- Write an algorithm to detect loop in a linked list.
You are presented with a linked list, which may have a "loop" in it. That is, an element of the linked list may incorrectly point to a previously encountered element, which can cause an infinite loop when traversing the list. Devise an algorithm to detect whether a loop exists in a linked list. How does your answer change if you cannot change the structure of the list elements?
One possible answer is to add a flag to each element of the list. You could then traverse the list, starting at the head and tagging each element as you encounter it. If you ever encountered an element that was already tagged, you would know that you had already visited it and that there existed a loop in the linked list. What if you are not allowed to alter the structure of the elements of the linked list? The following algorithm will find the loop:
- Start with two pointers ptr1 and ptr2.
- Set ptr1 and ptr2 to the head of the linked list.
- Traverse the linked list with ptr1 moving twice as fast as ptr2 (for every two elements that ptr1 advances within the list, advance ptr2 by one element).
- Stop when ptr1 reaches the end of the list, or when ptr1 = ptr2.
- If ptr1 and ptr2 are ever equal, then there must be a loop in the linked list. If the linked list has no loops, ptr1 should reach the end of the linked list ahead of ptr2.
- Given the time, devise an algorithm to calculate the angle between the hour and minute hands of an analog clock.
The important realization for this problem is that the hour hand is always moving. In other words, at 1:30, the hour hand is halfway between 1 and 2. Once you remember that, this problem is fairly straightforward. Assuming you don't care whether the function returns the shorter or larger angle, Example 4 shows a solution to this problem.
- Devise an algorithm for detecting whether a given string is a palindrome (spelled the same way forwards and backwards). For example, "A man, a plan, a canal, Panama."
For the sake of this problem, assume that the string has been stripped of punctuation (including spaces), and has been converted to a single case. The most efficient way to detect whether a string is a palindrome is to create two pointers. Set one at the beginning of the string, and one at the end. Compare the values at those locations. If the values don't match, the string isn't a palindrome. Otherwise, move each pointer inward and repeat the comparison. Stop when the pointers are pointing to the same position in the string (if its length is an odd-number) or when the pointers have "crossed" (if the string's length is an even-number). Example 5 shows the correct solution.
- Given an eight-bit bitmap graphics file, devise an algorithm to convert the file into a two-bit ASCII approximation.
Assume that the file format is one byte for every pixel in the file, and that the approximation will produce one ASCII character of output for each pixel. This problem is easier to solve than it sounds. This is one of the tricks used in technical interview questions. Problems may be obscured or made to sound difficult. Don't be fooled! Take the time to think about the core of the problem. In this case, all you want is an algorithm for reading the values in a file and outputting characters based upon those values.
Eight-bit numbers can be in the range from 0 to 255. Two-bit numbers are in the range from 0 to 3. Basically, we want to divide the 256 numbers specified by an eight-bit number into four ranges, which can be indicated by a two-bit number. So, divide the range of 0 to 255 uniformly into four separate ranges: 0 to 63, 64 to 127, 128 to 191, and 192 to 255.
You then have to assign an ASCII character to each of those four ranges of numbers. For example, you could use "_", "~", "+", and "#". Then, the algorithm is as follows:
1. Open the file.
2. For every byte in the file:
a. Read in one byte.
b. If the value is in the range 0..63, we'll print '_'.
c. If the value is in the range 64..127, we'll print '~'.
d. If the value is in the range 128..191, we'll print '+'.
e. If the value is in the range 192..255, we'll print '#'.
3. Close the file.
- Reverse a linked list.
- Insert in a sorted list
- First some definitions for this problem: a) An ASCII character is one byte long and the most significant bit in the byte is always '0'. b) A Kanji character is two bytes long. The only characteristic of a Kanji character is that in its first byte the most significant bit is '1'. Now you are given an array of a characters (both ASCII and Kanji) and, an index into the array. The index points to the start of some character. Now you need to write a function to do a backspace (i.e. delete the character before the given index).
- Delete an element from a doubly linked list.
- Write a function to find the depth of a binary tree.
- Assuming that locks are the only reason due to which deadlocks can occur in a system. What would be a foolproof method of avoiding deadlocks in the system.
- Besides communication cost, what is the other source of inefficiency in RPC?
(answer : context switches, excessive buffer copying). How can you optimise the communication? (ans : communicate through shared memory on same machine, bypassing the kernel _ A Univ. of Wash. thesis)
- Ways of optimizing symbol table storage in compilers.
- A walk-through through the symbol table functions, lookup() implementation etc - The interv. was on the Microsoft C team.
- Given an array t[100] which contains numbers between 1..99. Return the duplicated value. Try both O(n) and O(n-square).
- Given an array of characters. How would you reverse it. ? How would you reverse it without using indexing in the array.
- Given a sequence of characters. How will you convert the lower case characters to upper case characters. ( Try using bit vector - sol given in the C lib -> typec.h)
- Give a good data structure for having n queues ( n not fixed) in a finite memory segment. You can have some data-structure separate for each queue. Try to use at least 90% of the memory space.
- Do a breadth first traversal of a tree.
- Given a list of numbers ( fixed list) Now given any other list, how can you efficiently find out if there is any element in the second list that is an element of the first list (fixed list).
- What is a balanced tree
given a linked list with the following property node2 is left child of node1, if node2 < node1 else, it is the right child.
O P
|
|
O A
|
|
O B
|
|
O C
How do you convert the above linked list to the form without disturbing the property. Write C code for that.
O P | | O B / / / O ? O ?
determine where do A and C go
- How would you find a cycle in a linked list? Try to do it in O(n) time. Try it using a constant amount of memory.
- Implement an algorithm to reverse a doubly linked list.
- A square picture is cut into 16 squares and they are shuffled. Write a program to rearrange the 16 squares to get the original big square.
- The Web can be modeled as a directed graph. Come up with a graph traversal algorithm. Make the algorithm non-recursive and breadth-first.
- How would you implement a hash table ? How do you deal with collisions?
- How would you find a cycle in a linked list? Try to do it in O(n) time. Try it using a constant amount of memory.
- Given a history of URLs, how would you determine if a particular URL had been seen before?
- Since pages can have multiple URLs pointing to them, how can you make sure you've never seen the same CONTENT before?
- Write a function to print all of the permutations of a string.
- Come up with the plan on how to traverse a graph, as well as to quickly determine if a given URL is one of the million or so you've previously seen.
- The Web can be modeled as a directed graph. Come up with a graph traversal algorithm. Make the algorithm non-recursive and breadth-first.
- Implement an algorithm to reverse a singly linked list. (with and without recursion)
- Implement an algorithm to reverse a doubly linked list.
- Implement an algorithm to insert in a sorted list.
- Delete an element from a doubly linked list.
- Write a function to copy two strings, A and B. The last few bytes of string A overlap the first few bytes of string B.
- Implement an algorithm to sort an array.
- Given a sequence of characters, how will you convert the lower case characters to upper case characters?
- Write a routine that prints out a 2-D array in spiral order.
- Count the number of set bits in a number without using a loop.
- Give me an algorithm and C code to shuffle a deck of cards, given that the cards are stored in an array of ints. Try to come up with a solution that does not require any extra space.
- Write a function that takes in a string parameter and checks to see whether or not it is an integer, and if it is then return the integer value.
- How would you print out the data in a binary tree, level by level, starting at the top?
- Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words in it.
- Write a function to find the depth of a binary tree.
- Given a list of numbers ( fixed list) Now given any other list, how can you efficiently find out if there is any element in the second list that is an element of the first list (fixed list).
- How would you implement a queue from a stack?
- Write a funtion that finds repeating characters in a string.
- Write a routine to reverse a series of numbers without using an array.
- Give me an algorithm for telling me the number I didn't give you in a given range of numbers. (Numbers are given at random)
- Write a function to check if two rectangles defined as below overlap or not.
struct rect {
int top, bot, left, right;
} r1, r2;
- Write a program to print the elements of a very long linked list in ascending order. There may be duplicates in the list. You cannot modify the list or create another one. Memory is tight, speed is not a problem.
- Write a function to reverse a singly linked list, given number of links to reverse.
- Write a function to convert an int to a string.
- Some weird problem on vector calculus with some transformation matrices being applied - need paper and pencil to describe it.
- Given ships travel between points A and B, one every hour leaving from both ends (simultaneously), how many ships are required (minimum), if the journey takes 1hr 40 mts. How many ships does each ship encounter in its journey, and at what times?
4, 3 at 20 mts, 50 mts and 80 mts.
- Write a SetPixel(x, y) function, given a pointer to the bitmap. Each pixel is represented by 1 bit. There are 640 pixels per row. In each byte, while the bits are numbered right to left, pixels are numbered left to right. Avoid multiplications and divisions to improve performance.
- How do you represent an n-ary tree? Write a program to print the nodes of such a tree in breadth first order.
Sibling and firstchild ptr.
- Write the 'tr' program of UNIX. Invoked as
tr -str1 -str2.
It reads stdin and prints it out to stdout, replacing every occurance of str1[i] with str2[i]. eg.
tr -abc -xyz
to be and not to be <- input
to ye xnd not to ye <- output
- What does the term cast refer to? Why is it used?
A Casting is a mechanism built into C that allows the programmer to force the conversion of data types. This may be needed because most C functions are very particular about the data types they process. A programmer may wish to override the default way the C compiler promotes data types.
- In arithmetic expressions, to what data type will the C compiler promote a character?
It will promote it to an integer unless otherwise directed.
- What is the difference between a statement and a block?
A statement is a single C expression terminated with a semicolon. A block is a series of statements, the group of which is enclosed in curly-braces.
- Increment the variable next three different ways.
next = next + 1;
and
next++;
and
next += 1;
- How is a comment formed in C.
Comments in C begin with a slash followed by an asterisk. Any text may then appear including newlines. The comment is finished with an asterisk followed by a slash. Example:
/* This is a comment */
- Can comments be nested?
Not in standard (K&R) C.
- From the standpoint of programming logic, what is the difference between a loop with the test at the top, and a loop where the test is at the bottom?
If the test is at the bottom, the body of the loop will always be executed at least once. When the test is at the top, the body of the loop may never be executed.
- Specify the skeletons of two C loops with the test at the top.
next = 0; /* setup */
while ( next < max) { /* test */
printf("Hello "); /* body */
next++; /* update */
}
and
for ( next = 0; next < max; next++) /* setup,test */
/* and update */
printf("Hello"); /* body */
- Specify a C loop with the test at the bottom.
next = 0; /* setup */
do {
printf("Hello"); /* body */
next++; /* update */
} while ( next < max); /* test */
- What is the switch statement?
It is C's form of multiway-conditional (a.k.a case statement in Pascal).
- What does a break statement do? Which control structures use it?
The break statement unconditionally ends the execution of the smallest enclosing while, do, for or switch statement.
- In a loop, what is the difference between a break and continue statement?
The break terminates the loop. The continue branches immediately to the test portion of the loop.
- Where may variables be defined in C?
Outside a function definition (global scope, from the point of definition downward in the source code). Inside a block before any statements other than variable declarations (local scope with respect to the block).
- What is the difference between a variable definition and a variable declaration?
A definition tells the compiler to set aside storage for the variable. A declaration makes the variable known to parts of the program that may wish to use it. A variable might be defined and declared in the same statement.
- What is the purpose of a function prototype?
A function prototype tells the compiler to expect a given function to be used in a given way. That is, it tells the compiler the nature of the parameters passed to the function (the quantity, type and order) and the nature of the value returned by the function.
- What is type checking?
The process by which the C compiler ensures that functions and operators use data of the appropriate type(s). This form of check helps ensure the semantic correctness of the program.
- To what does the term storage class refer?
This is a part of a variable declaration that tells the compiler how to interpret the variable's symbol. It does not in itself allocate storage, but it usually tells the compiler how the variable should be stored.
- List C's storage classes and what they signify.
static - Variables are defined in a nonvolatile region of memory such that they retain their contents though out the program's execution.
register - Asks the compiler to devote a processor register to this variable in order to speed the program's execution. The compiler may not comply and the variable looses it contents and identity when the function it which it is defined terminates.
extern - Tells the compiler that the variable is defined in another module.
volatile - Tells the compiler that other programs will be modifying this variable in addition to the program being compiled. For example, an I/O device might need write directly into a program or data space. Meanwhile, the program itself may never directly access the memory area in question. In such a case, we would not want the compiler to optimize-out this data area that never seems to be used by the program, yet must exist for the program to function correctly in a larger context.
- State the syntax for the printf() and scanf() functions. State their one crucial difference with respect to their parameters.
Where fmtStr tells printf() how to format the variable list that follows. var1 through varN may be variables of any base type.
scanf( fmtStr, &var1, &var2, &varN);
This routine is the input compliment to printf().
scanf() requires the address of each variable instead of the variable's value (as in printf()). This is subtle source of serious bugs.
- With respect to function parameter passing, what is the difference between call-by-value and call-by-reference? Which method does C use?
In the case of call-by-reference, a pointer reference to a variable is passed into a function instead of the actual value. The function's operations will effect the variable in a global as well as local sense. Call-by-value (C's method of parameter passing), by contrast, passes a copy of the variable's value into the function. Any changes to the variable made by function have only a local effect and do not alter the state of the variable passed into the function.
- What is a structure and a union in C?
A structure is an aggregate data type. It combines one or more base or aggregate data types into a package that may treated as a whole. A structure is like a record in other languages. A union combines two or more data types in the same area of storage. The contents of a union may be one data type at one time and another type at a different time. A union is sometimes called a trick- record.
- Define a structure for a simple name/address record.
struct nameAddr {
char name[30];
char addr[30];
char city[20];
char state[3];
char zip[5];
};
- What does the typedef keyword do?
This keyword provides a short-hand way to write variable declarations. It is not a true data typing mechanism, rather, it is syntactic "sugar coating."
- Use typedef to make a short-cut way to declare a pointer to the nameAddr structure above. Call it addrPtr.
typedef struct nameAddr *addrPtr;
- Declare a variable with addrPtr called address.
addrPtr address;
- Assuming the variable address above, how would one refer to the city portion of the record within a C expression?
address->city
- What is the difference between: #include <stdio.h> and #include "stdio.h"
They both specify a file for inclusion into the current source file. The difference is where the file stdio.h is expected to be. In the case of the brackets, the compiler will look in all the default locations. In the case of the quotes, the compiler will only look in the current directory.
- What is #ifdef used for?
It is used for condition compilation. Specifically the source code between #ifdef and #endif (or #else) is compiled if the associated symbol is defined to the compiler.
- How do you define a constant in C?
The C language itself has no provision for constants. However, its companion program, the preprocessor, can be used to make manifest constants. It does this through the use of the #define keyword.
- Why can't you nest structure definitions?
Trick question: You can nest structure definitions.
- Can you nest function definitions?
No. (You can in Pascal, a close relative to C.)
- What is a forward reference?
It is a reference to a variable or function before it is defined to the compiler. The cardinal rule of structured languages is that everything must be defined before it can be used. There are rare occasions where this is not possible. It is possible (and sometimes necessary) to define two functions in terms of each other. One will obey the cardinal rule while the other will need a forward declaration of the former in order to know of the former's existence. Confused?
- What are the following and how do they differ: int, long, float and double?
int An integer, usually +/- 215 in magnitude.
long A larger version of int, usually +/- 231 in magnitude.
float A single precision real (floating point) number. Magnitude varies.
double A double precision real number. Magnitude varies.
- Define a macro called SQR which squares a number.
#define SQR(x) (x * x)
(The parenthesis around "x * x" are extremely important because the macro may be expanded into a place where any embedded spaces could cause the compiler to misinterpret the expression. The consequences could range from a pesky syntax error to wrong answers when the program is run.). Moral: The preprocessor does not know C.
- Is it possible to take the square-root of a number in C. Is there a square-root operator in C?
Yes. There is no square-root operator; such computation is performed though the use of a function.
- Using fprintf() print a single floating point number right-justified in a field of 20 spaces, no leading zeros, and 4 decimal places. The destination should be stderr and the variable is called num.
fprintf( stderr, "%-20.4f", num);
- What is the difference between the & and && operators and the | and || operators?
& and | are bitwise AND and OR operators respectively. They are usually used to manipulate the contents of a variable on the bit level. && and || are logical AND and OR operators respectively. They are usually used in conditionals.
- What is the difference between the -> and . operators?
They both provide access to members of a structure or union. They differ in that -> is used when the variable is a pointer to a structure or union. The dot is used when the variable is itself the structure or union. The -> operator combines the pointer dereferencing operator with the member access operator; it is syntactic "sugar coating."
address->city is equivalent to (*address).city.
- What is the symbol for the modulus operator?
% (the percent symbol)
- From the standpoint of logic, what is the difference between the fragment:
if (next < max)
next++;
else
next = 0;
and the fragment:
next += (next < max)? (1):(-next);
Nothing. They are different ways to express the same logic.
- What does the following fragment do?
while((d=c=getch(),d)!=EOF&&(c!='\t'||c!=' '||c!='\b')) *buff++ = ++c;
Do the following until either the end of standard input or the variable c takes on the value of a tab, space, or backspace character: Store the character that succeeds the character stored in c into the current location pointed by buff. Then increment buff to point to the next location in memory. Meanwhile, d is assigned the same value as c and it is the value of d that is used in the comparison to EOF.
- Is C case sensitive (ie: does C differentiate between upper and lower case letters)?
Yes.
- Specify how a filestream called inFile should be opened for random reading and writing. the file's name is in fileName.
inFile = fopen( fileName, "r+");
- What does fopen() return if successful. If unsuccessful?
Upon success fopen() returns a pointer to a filestream. Otherwise it returns the value of NULL.
- What is the void data type? What is a void pointer?
The void data type is used when no other data type is appropriate. A void pointer is a pointer that may point to any kind of object at all. It is used when a pointer must be specified but its type is unknown.
- Declare a pointer called fnc which points to a function that returns an unsigned long.
unsigned long (*fnc)();
- Declare a pointer called pfnc which points to a function that returns a pointer to a structure of type nameAddr.
struct nameAddr *(*pfnc)();
- It is possible for a function to return a character, an integer, and a floating point number. Is it possible for a function to return a structure? Another function?
No. However, it is possible to return pointers to structures and functions.
- What is the difference between an lvalue and an rvalue?
The lvalue refers to the left-hand side of an assignment expression. It must always evaluate to a memory location. The rvalue represents the right-hand side of an assignment expression; it may have any meaningful combination of variables and constants.
- Given the decimal number 27, how would one express it as a hexadecimal number in C?
0x1B
- What is malloc()?
This function allocates heap storage for dynamic data structures.
- What is the difference between malloc() and calloc()?
The malloc() function allocates raw memory given a size in bytes. On the other hand, calloc() clears the requested memory to zeros before return a pointer to it. (It can also compute the request size given the size of the base data structure and the number of them desired.)
- What kind of problems was C designed to solve?
C was designed to be a "universal" assembly language. It is used for producing system software such as operation systems, compilers/interpreters, device drivers, editors, DBMS's and similar things. It is not as well suited to application programs.
- write C code for deleting an element from a linked listy traversing a linked list efficient way of elimiating duplicates from an array
- Declare a void pointer
void *ptr;
- Make the pointer aligned to a 4 byte boundary in a efficient manner
assign the pointer to a long number and the number with 11...1100 add 4 to the number
- What is a far pointer (in DOS)
- Write an efficient C code for 'tr' program. 'tr' has two command line arguments. They both are strings of same length. tr reads an input file, replaces each character in the first string with the corresponding character in the second string. eg. 'tr abc xyz' replaces all 'a's by 'x's, 'b's by 'y's and so on.
have an array of length 26.
put 'x' in array element corr to 'a'
put 'y' in array element corr to 'b'
put 'z' in array element corr to 'c'
put 'd' in array element corr to 'd'
put 'e' in array element corr to 'e'
and so on.
the code
while (!eof)
{
c = getc();
putc(array[c - 'a']);
}
- Write C code to implement strtok() 'c' library function.
- Implement strstr(), strcpy(), strtok() etc
- Reverse a string.
- Given a linked list which is sorted, how will you insert in sorted way.
- Write a function that allocates memory for a two-dimensional array of given size (parameter x & y)
- Write source code for printHex(int i) in C/C++
- Write a function that finds the last instance of a character in a string.
- What is an object in C++?
An object is a package that contains related data and instructions. The data relates to what the object represents, while the instructions define how this object relates to other objects and itself.
- What is a message?
A message is a signal from one object to another requesting that a computation take place. It is roughly equivalent to a function call in other languages.
- What is a class?
A class defines the characteristics of a certain type of object. It defines what its members will remember, the messages to which they will respond, and what form the response will take.
- What is an instance?
An individual object that is a member of some class.
- What is a super-class?
Given a class, a super-class is the basis of the class under consideration. The given class is defined as a subset (in some respects) of the super-class. Objects of the given class potentially posses all the characteristics belonging to objects of the super-class.
- What is inheritance?
Inheritance is property such that a parent (or super) class passes the characteristics of itself to children (or sub) classes that are derived from it. The sub-class has the option of modifying these characteristics in order to make a different but fundamentally related class from the super-class.
- To what does message protocol refer?
An object's message protocol is the exact form of the set of messages to which the object can respond.
- What is polymorphism?
Polymorphism refers to the ability of an object to respond in a logically identical fashion to messages of the same protocol, containing differing types of objects. Consider 1 + 5 and 1 + 5.1. In the former, the message "+ 5" is sent to an object of class integer (1). In the later, the message "+ 5.1" is sent to the same integer object. The form of the message (its protocol) is identical in both cases. What differs is the type of object on the right-hand side of these messages. The former is an integer object (5) while the later is a floating point object (5.1). The receiver (1) appears (to other objects) to respond in the same way to both messages. Internally, however, it knows that it must treat the two types of objects differently in order to obtain the same overall response.
- What are instance variables?
These represent an object's private memory. They are defined in an object's class.
- What are class variables?
These represent a class's memory which it shares with each of its instances.
- What is a method?
A method is a class's procedural response to a given message protocol. It is like the definition of a procedure in other languages.
- In C++ what is a constructor? A destructor?
A constructors and destructors are methods defined in a class that are invoked automatically when an object is created or destroyed. They are used to initialize a newly allocated object and to cleanup behind an object about to be removed.
- Compare and contrast C and C++.
Comparison: C++ is an extension to the C language. When C++ is used as a procedural language, there are only minor syntactical differences between them.
Contrast: When used as a procedural language, C++ is a better C because:
- It vigorously enforces data typing conventions.
- It allows variables to be defined where they are used.
- It allows the definition of real (semantically significant) constants.
- It allows for automatic pointer dereferencing.
- It supports call-by-reference in addition to call-by-value in functions.
- It supports tentative variable declarations (when the type and location of a variable cannot be known before hand.
As an object oriented language, C++ introduces much of the OOP paradigm while allowing a mixture of OOP and procedural styles.
- What is operator overloading?
It is the process of, and ability to redefine the way an object responds to a C++ operator symbol. This would be done in the object's class definition.
- What is cin and cout?
They are objects corresponding to a program's default input and output files.
- Contrast procedural and object oriented programming.
The procedural paradigm performs computation through a step-by-step manipulation of data items. Solving problems this way is akin to writing a recipe. ie: All the ingredients (data items) are defined. Next a series of enumerated steps (statements) are defined to transform the raw ingredients into a finished meal.
The object oriented model, in contrast, combines related data and procedural information into a single package called an object. Objects are meant to represent logically separate entities (like real world objects). Objects are grouped together (and defined by) classes. (This is analogous to user defined data types in procedural languages.) Classes may pass-on their "makeup" to classes derived from them. In this way, Objects that are of a similar yet different nature need not be defined from scratch. Computation occurs though the intercommunication of objects. Programming this way is like writing a play. First the characters are defined with their attributes and personalities. Next the dialog is written so that the personalities interact. The sum total constitutes a drama.
- How do you link a C++ program to C functions?
By using the extern "C" linkage specification around the C function declarations.
You should know about mangled function names and type-safe linkages. Then you should explain how the extern "C" linkage specification statement turns that feature off during compilation so that the linker properly links function calls to C functions. Another acceptable answer is "I don't know. We never had to do that." Merely describing what a linker does would indicate to me that you do not understand the issue that underlies the question.
- Explain the scope resolution operator.
The scope resolution operator permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.
The answer can get complicated. It should start with "colon-colon," however. (Some readers had not heard the term, "scope resolution operator," but they knew what :: means. You should know the formal names of such things so that you can understand all communication about them.) If you claim to be well into the design or use of classes that employ inheritance, you tend to address overriding virtual function overrides to explicitly call a function higher in the hierarchy. That's good knowledge to demonstrate, but address your comments specifically to global scope resolution. Describe C++'s ability to override the particular C behavior where identifiers in the global scope are always hidden by similar identifiers in a local scope.
- What are the differences between a C++ struct and C++ class?
The default member and base class access specifiers are different.
This is one of the commonly misunderstood aspects of C++. Believe it or not, many programmers think that a C++ struct is just like a C struct, while a C++ class has inheritance, access specifiers, member functions, overloaded operators, and so on. Some of them have even written books about C++. Actually, the C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base class inheritance, and a class defaults to the private access specifier and private base class inheritance. Getting this question wrong does not necessarily disqualify you because you will be in plenty of good company. Getting it right is a definite plus.
- How many ways are there to initialize an int with a constant?
Two.
There are two formats for initializers in C++ as shown in Example 1. Example 1(a) uses the traditional C notation, while Example 1(b) uses constructor notation. Many programmers do not know about the notation in Example 1(b), although they should certainly know about the first one. Many old-timer C programmers who made the switch to C++ never use the second idiom, although some wise heads of C++ profess to prefer it.
A reader wrote to tell me of two other ways, as shown in Examples 2(a) and 2(b), which made me think that maybe the answer could be extended even further to include the initialization of an int function parameter with a constant argument from the caller.
- How does throwing and catching exceptions differ from using setjmp and longjmp?
The throw operation calls the destructors for automatic objects instantiated since entry to the try block.
Exceptions are in the mainstream of C++ now, so most programmers, if they are familiar with setjmp and longjmp, should know the difference. Both idioms return a program from the nested depths of multiple function calls to a defined position higher in the program. The program stack is "unwound" so that the state of the program with respect to function calls and pushed arguments is restored as if the calls had not been made. C++ exception handling adds to that behavior the orderly calls to the destructors of automatic objects that were instantiated as the program proceeded from within the try block toward where the throw expression is evaluated.
It's okay to discuss the notational differences between the two idioms. Explain the syntax of try blocks, catch exception handlers, and throw expressions. Then specifically address what happens in a throw that does not happen in a longjmp. Your answer should reflect an understanding of the behavior described in the answer just given.
One valid reason for not knowing about exception handling is that your experience is exclusively with older C++ compilers that do not implement exception handling. I would prefer that you have at least heard of exception handling, though.
It is not unusual for C and C++ programmers to be unfamiliar with setjmp/ longjmp. Those constructs are not particularly intuitive. A C programmer who has written recursive descent parsing algorithms will certainly be familiar with setjmp/ longjmp. Others might not, and that's acceptable. In that case, you won't be able to discuss how setjmp/longjmp differs from C++ exception handling, but let the interview turn into a discussion of C++ exception handling in general. That conversation will reveal to the interviewer a lot about your overall understanding of C++.
- What is your reaction to this line of code?
delete this;
It's not a good practice.
A good programmer will insist that the statement is never to be used if the class is to be used by other programmers and instantiated as static, extern, or automatic objects. That much should be obvious.
The code has two built-in pitfalls. First, if it executes in a member function for an extern, static, or automatic object, the program will probably crash as soon as the delete statement executes. There is no portable way for an object to tell that it was instantiated on the heap, so the class cannot assert that its object is properly instantiated. Second, when an object commits suicide this way, the using program might not know about its demise. As far as the instantiating program is concerned, the object remains in scope and continues to exist even though the object did itself in. Subsequent dereferencing of the pointer can and usually does lead to disaster.
A reader pointed out that a class can ensure that its objects are instantiated on the heap by making its destructor private. This idiom necessitates a kludgy DeleteMe kind of function because the instantiator cannot call the delete operator for objects of the class. The DeleteMe function would then use "delete this."
I got a lot of mail about this issue. Many programmers believe that delete this is a valid construct. In my experience, classes that use delete this when objects are instantiated by users usually spawn bugs related to the idiom, most often when a program dereferences a pointer to an object that has already deleted itself.
- What is a default constructor?
A constructor that has no arguments or one where all the arguments have default argument values.
If you don't code a default constructor, the compiler provides one if there are no other constructors. If you are going to instantiate an array of objects of the class, the class must have a default constructor.
- What is a conversion constructor?
A constructor that accepts one argument of a different type.
The compiler uses this idiom as one way to infer conversion rules for a class. A constructor with more than one argument and with default argument values can be interpreted by the compiler as a conversion constructor when the compiler is looking for an object of the type and sees an object of the type of the constructor's first argument.
- What is the difference between a copy constructor and an overloaded assignment operator?
A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.
First, you must know that a copy constructor is one that has only one argument, which is a reference to the same type as the constructor. The compiler invokes a copy constructor wherever it needs to make a copy of the object, for example to pass an argument by value. If you do not provide a copy constructor, the compiler creates a member-by-member copy constructor for you.
You can write overloaded assignment operators that take arguments of other classes, but that behavior is usually implemented with implicit conversion constructors. If you do not provide an overloaded assignment operator for the class, the compiler creates a default member-by-member assignment operator.
This discussion is a good place to get into why classes need copy constructors and overloaded assignment operators. By discussing the requirements with respect to data member pointers that point to dynamically allocated resources, you demonstrate a good grasp of the problem.
- When should you use multiple inheritance?
There are three acceptable answers: "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way."
There are some famous C++ pundits and luminaries who disagree with that third answer, so be careful.
Let's digress to consider this issue lest your interview turn into a religious debate. Consider an Asset class, Building class, Vehicle class, and CompanyCar class. All company cars are vehicles. Some company cars are assets because the organizations own them. Others might be leased. Not all assets are vehicles. Money accounts are assets. Real-estate holdings are assets. Some real-estate holdings are buildings. Not all buildings are assets. Ad infinitum. When you diagram these relationships, it becomes apparent that multiple inheritance is an intuitive way to model this common problem domain. You should understand, however, that multiple inheritance, like a chainsaw, is a useful tool that has its perils, needs respect, and is best avoided except when nothing else will do. Stress this understanding because your interviewer might share the common bias against multiple inheritance that many object-oriented designers hold.
- What is a virtual destructor?
The simple answer is that a virtual destructor is one that is declared with the virtual attribute.
The behavior of a virtual destructor is what is important. If you destroy an object through a pointer or reference to a base class, and the base-class destructor is not virtual, the derived-class destructors are not executed, and the destruction might not be complete.
- Explain the ISA and HASA class relationships. How would you implement each in a class design?
A specialized class "is a" specialization of another class and, therefore, has the ISA relationship with the other class. An Employee ISA Person. This relationship is best implemented with inheritance. Employee is derived from Person. A class may have an instance of another class. For example, an Employee "has a" Salary, therefore the Employee class has the HASA relationship with the Salary class. This relationship is best implemented by embedding an object of the Salary class in the Employee class.
The answer to this question reveals whether you have an understanding of the fundamentals of object-oriented design, which is important to reliable class design.
There are other relationships. The USESA relationship is when one class uses the services of another. The Employee class uses an object (cout) of the ostream class to display the employee's name onscreen, for example. But if you get ISA and HASA right, you usually don't need to go any further.
- When is a template a better solution than a base class?
When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus the genericity) to the designer of the container or manager class.
Prior to templates, you had to use inheritance; your design might include a generic List container class and an application-specific Employee class. To put employees in a list, a ListedEmployee class is multiply derived (contrived) from the Employee and List classes. These solutions were unwieldy and error-prone. Templates solved that problem.
- What is the result of compiling this program in a C compiler? in a C++ compiler?
int __ = 0;
main() {
int ___ = 2;
printf("%d\n", ___ + __);
}
On GNU compiler both C and C++ give output as 2. I believe other C++ compiler will complain "syntax error", whereas C compiler will give 2.
- What is the difference between C and C++ ? Would you prefer to use one over the other ?
C is based on structured programming whereas C++ supports the object-oriented programming paradigm.Due to the advantages inherent in object-oriented programs such as modularity and reuse, C++ is preferred. However almost anything that can be built using C++ can also be built using C.
- What are the access privileges in C++ ? What is the default access level ?
The access privileges in C++ are private, public and protected. The default access level assigned to members of a class is private. Private members of a class are accessible only within the class and by friends of the class. Protected members are accessible by the class itself and it's sub-classes. Public members of a class can be accessed by anyone.
- What is data encapsulation ?
Data Encapsulation is also known as data hiding. The most important advantage of encapsulation is that it lets the programmer create an object and then provide an interface to the object that other objects can use to call the methods provided by the object. The programmer can change the internal workings of an object but this transparent to other interfacing programs as long as the interface remains unchanged.
- What is inheritance ?
Inheritance is the process of deriving classes from other classes. In such a case, the sub-class has an 'is-a' relationship with the super class. For e.g. vehicle can be a super-class and car can be a sub-class derived from vehicle. In this case a car is a vehicle. The super class 'is not a' sub-class as the sub- class is more specialized and may contain additional members as compared to the super class. The greatest advantage of inheritance is that it promotes generic design and code reuse.
- What is multiple inheritance ? What are it's advantages and disadvantages ?
Multiple Inheritance is the process whereby a sub-class can be derived from more than one super class. The advantage of multiple inheritance is that it allows a class to inherit the functionality of more than one base class thus allowing for modeling of complex relationships. The disadvantage of multiple inheritance is that it can lead to a lot of confusion when two base classes implement a method with the same name.
- What is polymorphism?
Polymorphism refers to the ability to have more than one method with the same signature in an inheritance hierarchy. The correct method is invoked at run-time based on the context (object) on which the method is invoked. Polymorphism allows for a generic use of method names while providing specialized implementations for them.
- What do the keyword static and const signify ?
When a class member is declared to be of a static type, it means that the member is not an instance variable but a class variable. Such a member is accessed using Classname.Membername (as opposed to Object.Membername). Const is a keyword used in C++ to specify that an object's value cannot be changed.
- How is memory allocated/deallocated in C ? How about C++ ?
Memory is allocated in C using malloc() and freed using free(). In C++ the new() operator is used to allocate memory to an object and the delete() operator is used to free the memory taken up by an object.
- What is UML ?
UML refers to Unified Modeling Language. It is a language used to model OO problem spaces and solutions.
- What is the difference between a shallow copy and a deep copy ?
A shallow copy simply creates a new object and inserts in it references to the members of the original object. A deep copy constructs a new object and then creates in it copies of each of the members of the original object.
- What are the differences between new and malloc?
- What is the difference between delete and delete[]?
- What are the differences between a struct in C and in C++?
- What are the advantages/disadvantages of using #define?
- What are the advantages/disadvantages of using inline and const?
- What is the difference between a pointer and a reference?
- When would you use a pointer? A reference?
- What does it mean to take the address of a reference?
- What does it mean to declare a function or variable as static?
- What is the order of initalization for data?
- What is name mangling/name decoration?
- What kind of problems does name mangling cause?
- How do you work around them?
- What is a class?
- What are the differences between a struct and a class in C++?
- What is the difference between public, private, and protected access?
- For class CFoo { }; what default methods will the compiler generate for you>?
- How can you force the compiler to not generate them?
- What is the purpose of a constructor? Destructor?
- What is a constructor initializer list?
- When must you use a constructor initializer list?
- What is a: Constructor? Destructor? Default constructor? Copy constructor? Conversion constructor?
- What does it mean to declare a... member function as virtual? member function as static? member varible as static? destructor as static?
- Can you explain the term "resource acqusition is initialization?"
- What is a "pure virtual" member function?
- What is the difference between public, private, and protected inheritance?
- What is virtual inheritance?
- What is placement new?
- What is the difference between operator new and the new operator?
- What is exception handling?
- Explain what happens when an exception is thrown in C++.
- What happens if an exception is not caught?
- What happens if an exception is throws from an object's constructor?
- What happens if an exception is throws from an object's destructor?
- What are the costs and benefits of using exceptions?
- When would you choose to return an error code rather than throw an exception?
- What is a template?
- What is partial specialization or template specialization?
- How can you force instantiation of a template?
- What is an iterator?
- What is an algorithm (in terms of the STL/C++ standard library)?
- What is std::auto_ptr?
- What is wrong with this statement? std::auto_ptr ptr(new char[10]);
- It is possible to build a C++ compiler on top of a C compiler. How would you do this?
Note: I've only asked this question once; and yes, he understood that I was asking him how cfront was put together.
- What output does the following code generate? Why? What output does it generate if you make A::Foo() a pure virtual function?
#include
class A {
public:
A() {
this->Foo();
}
virtual void Foo() {
cout << "A::Foo()" << endl;
}
};
class B : public A {
public:
B() {
this->Foo();
}
virtual void Foo() {
cout << "A::Foo()" << endl;
}
};
int main(int, char**)
{
B objectB;
}
p {return 0;
}
- What output does this program generate as shown? Why?
#include
class A {
public:
A() {
cout << "A::A()" << endl;
}
~A() {
cout << "A::~A()" << endl; throw "A::exception";
}
};
class B {
public:
B() {
cout << "B::B()" << endl; throw "B::exception";
}
~B() {
cout << "B::~B()";
}
};
int main(int, char**) {
try {
cout << "Entering try...catch block" << endl;
}
p {A objectA;
B objectB;
}
p {cout << "Exiting try...catch block" << endl;
} catch (char* ex) {
cout << ex << endl;
}
}
p {return 0;
}
- C++ ( what is virtual function ? what happens if an error occurs in constructor or destructor. Discussion on error handling, templates, unique features of C++. What is different in C++, ( compare with unix).
- I was given a c++ code and was asked to find out the bug in that. The bug was that he declared an object locally in a function and tried to return the pointer to that object. Since the object is local to the function, it no more exists after returning from the function. The pointer, therefore, is invalid outside.
- What is a mutable member?
One that can be modified by the class even when the object of the class or the member function doing the modification is const.
Understanding this requirement implies an understanding of C++ const, which many programmers do not have. I have seen large class designs that do not employ the const qualifier anywhere. Some of those designs are my own early C++ efforts. One author suggests that some programmers find const to be such a bother that it is easier to ignore const than to try to use it meaningfully. No wonder many programmers don't understand the power and implications of const. Someone who claims to have enough interest in the language and its evolution to keep pace with the ANSI deliberations should not be ignorant of const, however.
- What is an explicit constructor?
A conversion constructor declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. Its purpose is reserved explicitly for construction.
- What is the Standard Template Library?
A library of container templates approved by the ANSI committee for inclusion in the standard C++ specification.
An applicant who then launches into a discussion of the generic programming model, iterators, allocators, algorithms, and such, has a higher than average understanding of the new technology that STL brings to C++ programming.
- Describe run-time type identification.
The ability to determine at run time the type of an object by using the typeid operator or the dynamic_cast operator.
- What problem does the namespace feature solve?
Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries. The name-space feature surrounds a library's external declarations with a unique namespace that eliminates the potential for those collisions.
This solution assumes that two library vendors don't use the same namespace, of course.
- Are there any new intrinsic (built-in) data types?
Yes. The ANSI committee added the bool intrinsic type and its true and false value keywords and the wchar_t data type to support character sets wider than eight bits.
Other apparent new types (string, complex, and so forth) are implemented as classes in the Standard C++ Library rather than as intrinsic types.
- Draw a class diagram (UML) for a system. (They described the system in plain english).
- Which do you prefer, inheritance or delegation? Why?
- What is the difference between RMI and IIOP?
- http://www.javaprepare.com/quests/question.html
- What's the difference between SQL, DDL, and DML?
- What's a join? An inner join? An outer join?
- Describe HTTP.
- What's a design pattern?
- Can you explain the singleton, vistor, facade, or handle class design pattern?
- When you do an ls -l, describe in detail everything that comes up on the screen.
- Tell me three ways to find an IP address on a Unix box.
- Write a bubble sort.
- Write a linked list.
- Describe an object.
- What does object-oriented mean to you.
- Can you explain what a B tree is?
- What's the difference between UDP and TCP?
- What is ICMP?
- What's the difference between a stack and a Queue?
- Do you know anything about the protection rings in the PC architecture?
- How much hardware/Assembler/Computer Architecture experience do you have.
- Explain final, finalize, and finally. When the finalize is invoked? How does GC work? etc.
- What is your experience with Servlet and JSP?
- What is the Prototype design pattern?
- In a system that you are designing and developing, a lot of small changes are expected to be committed at the end of a method call (persisted to the DB). If you don't want to query the database frequently. what would you do?
- Give an example in which you will combine several design patterns, and explain how the system can benefit from that.
- Why would you apply design patterns (benefits)?
- What is a two-phase commit?
- What will happen if one of your web-server or appserver crashs during its execution?
- What are various problems unique to distributed databases
- Describe the file system layout in the UNIX OS
describe boot block, super block, inodes and data layout
In UNIX, are the files allocated contiguous blocks of data a) no, they might be fragmented how is the fragmented data kept track of a) describe the direct blocks and indirect blocks in UNIX file system
- what is disk interleaving
- why is disk interleaving adopted
- given a new disk, how do you determine which interleaving is the best
- give 1000 read operations with each kind of interleaving determine the best interleaving from the statistics
- draw the graph with performace on one axis and 'n' on another, where 'n' in the 'n' in n-way disk interleaving. (a tricky question, should be answered carefully)
- Design a memory management scheme.
- What sort of technique you would use to update a set of files over a network, where a server contains the master copy.
- How did you get into computer science?
- What kind of technical publications (print or online) do you read on a regular basis?
- What was the last book you read (does not have to be job related!)
- If you could recommend one resource (book, web site, etc.) to a new software developer just out of school, what would it be?
- What was the most interesting project that you worked on?
- What was the most challenging project that you worked on?
- If you could have any job in the world, what would it be?
- Tell me about your favorite class.
- Tell me about your favorite project [with lots of follow-up questions].
- Tell me about a something you did that was unsuccessful, a project or class that didn't go well.
- Do you prefer a structured or unstructured working environment.
- A chemist calls you up and says his Netscape isn't working. What's wrong and how do you find out?
- How do you prioritize multiple projects?
- Tell me about previous jobs?
- What are your greatest strengths and weaknesses?
- Tell us about yourself.
- Where would you like to be in five years?
- How do you see yourself fitting in to this company?
- Do you have any questions for me?
- Why did you leave your last job.
- Did you finance your own education?
- Are you good with people?
- Have you experience working on a group project?
- How well do you know the windows menus?
- What was the hardest program error for you to find and correct?
- What did you find hardest when working with others in a project?
- What is a tool or system that you learned on your own? i.e. not in a class room?
- As a developer, would you prefer to use application server? Why?
- How would go about finding out where to find a book in a library. (You don't know how exactly the books are organized beforehand).
- Tradeoff between time spent in testing a product and getting into the market first.
- What to test for given that there isn't enough time to test everything you want to.
- Why do u think u are smart.
- Questions on the projects listed on the Resume.
- Do you want to know any thing about the company.( Try to ask some relevant and interesting question).
- How long do u want to stay in USA and why?
- What are your geographical preference?
- What are your expectations from the job.
|
|
|
公告
我创建的群:21159852,欢迎大家加入!
( Scada,DCS,PLC,
RTU,VxWorks,
Linux,104,101,
DNP,MODBUS
......
)
导航
统计
- 随笔: 137
- 文章: 3
- 评论: 97
- 引用: 0
常用链接
留言簿(9)
随笔分类(141)
随笔档案(137)
文章分类(2)
文章档案(3)
相册
上传
最新随笔
搜索
积分与排名
最新评论
阅读排行榜
评论排行榜
|
|