Sunteți pe pagina 1din 94

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

1. Introduction

2. The Basic Rules

3. Don't assume all data is given to you.

4. Think out loud.

5. Good programming practice.

6. Check all boundary conditions.

7. Work Things Into Your Conversations


8. Typical Technical Questions

9. Conclusion

Logic questions

10. 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 ?
11.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.

12. 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.
13.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.

14. 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.

15. 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.
16.A version of the "There are three persons X Y Z, one of which always
lies"..

17. 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.
18.If you are on a boat and you throw out a suitcase, Will the level of water
increase.

19. 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.
20. Man 1:1 minute to cross
21. Man 2: 2 minutes to cross
22. Man 3: 5 minutes to cross
23. Man 4: 10 minutes to cross

24. 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?

25. 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?
26. 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)

27. 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

28. Write a routine to draw a circle (x ** 2 + y ** 2 = r ** 2) without


making use of any floating point computations at all.

29. Given only putchar (no sprintf, itoa, etc.) write a routine putlong that
prints out an unsigned long in decimal.

30. Give a one-line C expression to test whether a number is a power of 2.


[No loops allowed - it's a simple test.]
31.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).

32. What are the different ways to say, the value of x can be either a 0 or a 1.
33. 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.

34. Give a fast way to multiply a number by 7.


35.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.
36.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.
37.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?
38.Given an expression tree with no parentheses in it, write the program to
give equivalent infix expression with parentheses inserted where
necessary.
39.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.
40.Give me an algorithm and C code to find the subarray with the largest
sum given an array containing both positive and negative integers.

41. Write a function that returns the factorial of a number.

42. Write a function that computes the nth number in the Fibonacci
sequence.

43. Write an implementation of strlen().


44. Switch the integer values stored in two registers without using any
additional memory.
45.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.
46.Write a small lexical analyzer - interviewer gave tokens. expressions like
"a*b" etc.
47.Write a routine that prints out a 2-D array in spiral order!
48.How is the readers-writers problem solved? - using semaphores/ada ..
etc.
49.Write code for reversing a linked list.

50. 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

51.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 ?
52.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.
53.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 ].
54.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 ].
55.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 ].
56.Give a one-line C expression to test whether a number is a power of 2.
[No loops allowed - it's a simple test.]
57.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.
58.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.
59.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).
60.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

61. (a-1) xor a == 0 - What does this do?


62.How can you print singly linked list in reverse order? (it's a huge list and
you cant use recursion)
63.How can you find out if there is a loop in a very long list?
64.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)
65.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..)
66.Whats the simples way to check if the sum of two unsigned integers has
resulted in an overflow.
67.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...
68.Sum of the numbers or copy i into A[i] so on till conflict.
69.Update deltaY while incrementing x. Have to multiply so that the deltay
is not a floating pt number.
70.Find the largest 10**n less than given number, then div etc.
71.Infinite.
72.Shivku said this question is garbled thru ages.
73.reverse the pointers till you reach the end and print-and-reverse as you
return.
74.Have two 'threads' one at twice the speed of the other traversing the list
and see if at anytime they meet.
75.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.
76.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.
77.if (a+b) < a or (a+b) < b then overflow has occurred

Data structures and algorithms questions

78.Write a function and the node data structure to visit all of the nodes in a
binary tree.
79.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?
80.Give an algorithm that calculates the distance between two text strings
(only operations you can have are: delete, add, and change, one by one).
81.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.
82.Describe a situation where concurrent access would lead to
inconsistency in your application. How would you solve this problem?

83. 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.

84. Write an algorithm to detect loop in a linked list.


85. Given the time, devise an algorithm to calculate the angle between the
hour and minute hands of an analog clock.

86. 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."

87. Given an eight-bit bitmap graphics file, devise an algorithm to convert


the file into a two-bit ASCII approximation.
88.Reverse a linked list.
89.Insert in a sorted list
90.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).
91.Delete an element from a doubly linked list.
92.Write a function to find the depth of a binary tree.
93.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.

94. Besides communication cost, what is the other source of inefficiency in


RPC?
95.Ways of optimizing symbol table storage in compilers.
96.A walk-through through the symbol table functions, lookup()
implementation etc - The interv. was on the Microsoft C team.
97.Given an array t[100] which contains numbers between 1..99. Return the
duplicated value. Try both O(n) and O(n-square).
98.Given an array of characters. How would you reverse it. ? How would
you reverse it without using indexing in the array.
99.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)
100. 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.
101. Do a breadth first traversal of a tree.
102. 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).

103. What is a balanced tree


104. 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.
105. Implement an algorithm to reverse a doubly linked list.
106. 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.
107. The Web can be modeled as a directed graph. Come up with a
graph traversal algorithm. Make the algorithm non-recursive and
breadth-first.
108. How would you implement a hash table ? How do you deal with
collisions?
109. 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.
110. Given a history of URLs, how would you determine if a particular
URL had been seen before?
111. Since pages can have multiple URLs pointing to them, how can
you make sure you've never seen the same CONTENT before?
112. Write a function to print all of the permutations of a string.
113. 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.
114. The Web can be modeled as a directed graph. Come up with a
graph traversal algorithm. Make the algorithm non-recursive and
breadth-first.
115. Implement an algorithm to reverse a singly linked list. (with and
without recursion)
116. Implement an algorithm to reverse a doubly linked list.
117. Implement an algorithm to insert in a sorted list.
118. Delete an element from a doubly linked list.
119. 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.
120. Implement an algorithm to sort an array.
121. Given a sequence of characters, how will you convert the lower
case characters to upper case characters?
122. Write a routine that prints out a 2-D array in spiral order.
123. Count the number of set bits in a number without using a loop.
124. 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.
125. 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.
126. How would you print out the data in a binary tree, level by level,
starting at the top?
127. Given an array of characters which form a sentence of words, give
an efficient algorithm to reverse the order of the words in it.
128. Write a function to find the depth of a binary tree.
129. 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).
130. How would you implement a queue from a stack?
131. Write a funtion that finds repeating characters in a string.
132. Write a routine to reverse a series of numbers without using an
array.
133. 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

134. Write a function to check if two rectangles defined as below


overlap or not.
135. struct rect {
136. int top, bot, left, right;
137. } r1, r2;
138. 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.
139. Write a function to reverse a singly linked list, given number of
links to reverse.
140. Write a function to convert an int to a string.
141. Some weird problem on vector calculus with some transformation
matrices being applied - need paper and pencil to describe it.

142. 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?
143. 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.

144. How do you represent an n-ary tree? Write a program to print the
nodes of such a tree in breadth first order.
145. 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

146. What does the term cast refer to? Why is it used?
147. In arithmetic expressions, to what data type will the C compiler
promote a character?

148. What is the difference between a statement and a block?

149. Increment the variable next three different ways.

150. How is a comment formed in C.

151. Can comments be nested?

152. 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?

153. Specify the skeletons of two C loops with the test at the top.

154. Specify a C loop with the test at the bottom.

155. What is the switch statement?

156. What does a break statement do? Which control structures use it?
157. In a loop, what is the difference between a break and continue
statement?

158. Where may variables be defined in C?

159. What is the difference between a variable definition and a variable


declaration?

160. What is the purpose of a function prototype?

161. What is type checking?

162. To what does the term storage class refer?

163. List C's storage classes and what they signify.

164. State the syntax for the printf() and scanf() functions. State their
one crucial difference with respect to their parameters.

165. With respect to function parameter passing, what is the difference


between call-by-value and call-by-reference? Which method does C use?

166. What is a structure and a union in C?


167. Define a structure for a simple name/address record.

168. What does the typedef keyword do?

169. Use typedef to make a short-cut way to declare a pointer to the


nameAddr structure above. Call it addrPtr.

170. Declare a variable with addrPtr called address.

171. Assuming the variable address above, how would one refer to the
city portion of the record within a C expression?

172. What is the difference between: #include <stdio.h> and #include


"stdio.h"

173. What is #ifdef used for?

174. How do you define a constant in C?

175. Why can't you nest structure definitions?

176. Can you nest function definitions?


177. What is a forward reference?

178. What are the following and how do they differ: int, long, float and
double?

179. Define a macro called SQR which squares a number.

180. Is it possible to take the square-root of a number in C. Is there a


square-root operator in C?

181. 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.

182. What is the difference between the & and && operators and the |
and || operators?

183. What is the difference between the -> and . operators?

184. What is the symbol for the modulus operator?

185. From the standpoint of logic, what is the difference between the
fragment:
186. if (next < max)
187. next++;
188. else
189. next = 0;
and the fragment:
next += (next < max)? (1):(-next);

190. What does the following fragment do?


while((d=c=getch(),d)!=EOF&&(c!='\t'||c!=' '||c!='\b')) *buff++ =
++c;

191. Is C case sensitive (ie: does C differentiate between upper and


lower case letters)?

192. Specify how a filestream called inFile should be opened for


random reading and writing. the file's name is in fileName.

193. What does fopen() return if successful. If unsuccessful?

194. What is the void data type? What is a void pointer?

195. Declare a pointer called fnc which points to a function that returns
an unsigned long.

196. Declare a pointer called pfnc which points to a function that


returns a pointer to a structure of type nameAddr.
197. 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?

198. What is the difference between an lvalue and an rvalue?

199. Given the decimal number 27, how would one express it as a
hexadecimal number in C?

200. What is malloc()?

201. What is the difference between malloc() and calloc()?

202. What kind of problems was C designed to solve?


203. write C code for deleting an element from a linked listy traversing
a linked list efficient way of elimiating duplicates from an array

204. Declare a void pointer

205. Make the pointer aligned to a 4 byte boundary in a efficient


manner
206. What is a far pointer (in DOS)

207. 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.
208. Write C code to implement strtok() 'c' library function.
209. Implement strstr(), strcpy(), strtok() etc
210. Reverse a string.
211. Given a linked list which is sorted, how will you insert in sorted
way.
212. Write a function that allocates memory for a two-dimensional
array of given size (parameter x & y)
213. Write source code for printHex(int i) in C/C++
214. Write a function that finds the last instance of a character in a
string.

C++ syntax, semantics and concepts questions

215. What is an object in C++?

216. What is a message?

217. What is a class?

218. What is an instance?

219. What is a super-class?

220. What is inheritance?


221. To what does message protocol refer?

222. What is polymorphism?

223. What are instance variables?

224. What are class variables?

225. What is a method?

226. In C++ what is a constructor? A destructor?

227. Compare and contrast C and C++.

228. What is operator overloading?

229. What is cin and cout?

230. Contrast procedural and object oriented programming.

231. How do you link a C++ program to C functions?


232. Explain the scope resolution operator.

233. What are the differences between a C++ struct and C++ class?

234. How many ways are there to initialize an int with a constant?

235. How does throwing and catching exceptions differ from using
setjmp and longjmp?

236. What is your reaction to this line of code?


delete this;

237. What is a default constructor?

238. What is a conversion constructor?

239. What is the difference between a copy constructor and an


overloaded assignment operator?

240. When should you use multiple inheritance?

241. What is a virtual destructor?


242. Explain the ISA and HASA class relationships. How would you
implement each in a class design?

243. When is a template a better solution than a base class?

244. What is the result of compiling this program in a C compiler? in a


C++ compiler?
245. int __ = 0;
246. main() {
247. int ___ = 2;
248. printf("%d\n", ___ + __);
249. }

250. What is the difference between C and C++ ? Would you prefer to
use one over the other ?

251. What are the access privileges in C++ ? What is the default access
level ?

252. What is data encapsulation ?

253. What is inheritance ?

254. What is multiple inheritance ? What are it's advantages and


disadvantages ?
255. What is polymorphism?

256. What do the keyword static and const signify ?

257. How is memory allocated/deallocated in C ? How about C++ ?

258. What is UML ?

259. What is the difference between a shallow copy and a deep copy ?
260. What are the differences between new and malloc?
261. What is the difference between delete and delete[]?
262. What are the differences between a struct in C and in C++?
263. What are the advantages/disadvantages of using #define?
264. What are the advantages/disadvantages of using inline and const?
265. What is the difference between a pointer and a reference?
266. When would you use a pointer? A reference?
267. What does it mean to take the address of a reference?
268. What does it mean to declare a function or variable as static?
269. What is the order of initalization for data?
270. What is name mangling/name decoration?
271. What kind of problems does name mangling cause?
272. How do you work around them?
273. What is a class?
274. What are the differences between a struct and a class in C++?
275. What is the difference between public, private, and protected
access?
276. For class CFoo { }; what default methods will the compiler
generate for you>?
277. How can you force the compiler to not generate them?
278. What is the purpose of a constructor? Destructor?
279. What is a constructor initializer list?
280. When must you use a constructor initializer list?
281. What is a: Constructor? Destructor? Default constructor? Copy
constructor? Conversion constructor?
282. What does it mean to declare a... member function as virtual?
member function as static? member varible as static? destructor as static?
283. Can you explain the term "resource acqusition is initialization?"
284. What is a "pure virtual" member function?
285. What is the difference between public, private, and protected
inheritance?
286. What is virtual inheritance?
287. What is placement new?
288. What is the difference between operator new and the new
operator?
289. What is exception handling?
290. Explain what happens when an exception is thrown in C++.
291. What happens if an exception is not caught?
292. What happens if an exception is throws from an object's
constructor?
293. What happens if an exception is throws from an object's
destructor?
294. What are the costs and benefits of using exceptions?
295. When would you choose to return an error code rather than throw
an exception?
296. What is a template?
297. What is partial specialization or template specialization?
298. How can you force instantiation of a template?
299. What is an iterator?
300. What is an algorithm (in terms of the STL/C++ standard library)?
301. What is std::auto_ptr?
302. What is wrong with this statement? std::auto_ptr ptr(new
char[10]);

303. It is possible to build a C++ compiler on top of a C compiler. How


would you do this?

304. What output does the following code generate? Why? What
output does it generate if you make A::Foo() a pure virtual function?
305. What output does this program generate as shown? Why?
306. 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).
307. 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

308. What is a mutable member?

309. What is an explicit constructor?

310. What is the Standard Template Library?

311. Describe run-time type identification.

312. What problem does the namespace feature solve?

313. Are there any new intrinsic (built-in) data types?

Design
314. Draw a class diagram (UML) for a system. (They described the
system in plain english).
315. Which do you prefer, inheritance or delegation? Why?
316. What is the difference between RMI and IIOP?

Java questions

317. http://www.javaprepare.com/quests/question.html

Misc. Questions (Design pattern, HTTP, OOP, SQL)

318. What's the difference between SQL, DDL, and DML?


319. What's a join? An inner join? An outer join?
320. Describe HTTP.
321. What's a design pattern?
322. Can you explain the singleton, vistor, facade, or handle class
design pattern?
323. When you do an ls -l, describe in detail everything that comes up
on the screen.
324. Tell me three ways to find an IP address on a Unix box.
325. Write a bubble sort.
326. Write a linked list.
327. Describe an object.
328. What does object-oriented mean to you.
329. Can you explain what a B tree is?
330. What's the difference between UDP and TCP?
331. What is ICMP?
332. What's the difference between a stack and a Queue?
333. Do you know anything about the protection rings in the PC
architecture?
334. How much hardware/Assembler/Computer Architecture
experience do you have.
335. Explain final, finalize, and finally. When the finalize is invoked?
How does GC work? etc.
336. What is your experience with Servlet and JSP?
337. What is the Prototype design pattern?
338. 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?
339. Give an example in which you will combine several design
patterns, and explain how the system can benefit from that.
340. Why would you apply design patterns (benefits)?
341. What is a two-phase commit?
342. What will happen if one of your web-server or appserver crashs
during its execution?
343. What are various problems unique to distributed databases

344. Describe the file system layout in the UNIX OS


345. what is disk interleaving
346. why is disk interleaving adopted
347. given a new disk, how do you determine which interleaving is the
best
348. give 1000 read operations with each kind of interleaving
determine the best interleaving from the statistics
349. 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)
350. Design a memory management scheme.
351. 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

352. How did you get into computer science?


353. What kind of technical publications (print or online) do you read
on a regular basis?
354. What was the last book you read (does not have to be job related!)
355. If you could recommend one resource (book, web site, etc.) to a
new software developer just out of school, what would it be?
356. What was the most interesting project that you worked on?
357. What was the most challenging project that you worked on?
358. If you could have any job in the world, what would it be?
359. Tell me about your favorite class.
360. Tell me about your favorite project [with lots of follow-up
questions].
361. Tell me about a something you did that was unsuccessful, a
project or class that didn't go well.
362. Do you prefer a structured or unstructured working environment.
363. A chemist calls you up and says his Netscape isn't working.
What's wrong and how do you find out?
364. How do you prioritize multiple projects?
365. Tell me about previous jobs?
366. What are your greatest strengths and weaknesses?
367. Tell us about yourself.
368. Where would you like to be in five years?
369. How do you see yourself fitting in to this company?
370. Do you have any questions for me?
371. Why did you leave your last job.
372. Did you finance your own education?
373. Are you good with people?
374. Have you experience working on a group project?
375. How well do you know the windows menus?
376. What was the hardest program error for you to find and correct?
377. What did you find hardest when working with others in a project?
378. What is a tool or system that you learned on your own? i.e. not in
a class room?
379. As a developer, would you prefer to use application server? Why?
380. 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).
381. Tradeoff between time spent in testing a product and getting into
the market first.
382. What to test for given that there isn't enough time to test
everything you want to.
383. Why do u think u are smart.
384. Questions on the projects listed on the Resume.
385. Do you want to know any thing about the company.( Try to ask
some relevant and interesting question).
386. How long do u want to stay in USA and why?
387. What are your geographical preference?
388. What are your expectations from the job.

Questions and Answers


Useful tips

1. 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.

2. 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.

3. 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.

4. 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.
5. 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.

6. 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.

7. 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ésumé 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.

8. 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.

9. 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.

Logic questions

10.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.

11.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.

12.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...

13.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.

14.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)

15.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.

16.A version of the "There are three persons X Y Z, one of which


always lies"..

17.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.

18.If you are on a boat and you throw out a suitcase, Will the level of
water increase.

19.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.
20. Man 1:1 minute to cross
21. Man 2: 2 minutes to cross
22. Man 3: 5 minutes to cross
23. 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.

24.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.

25.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.

26.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.

27.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.

Programming questions that require thinking

28.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.

29.Given only putchar (no sprintf, itoa, etc.) write a routine putlong
that prints out an unsigned long in decimal.
30. void putlong(unsigned long x)
31. {
32. // we know that 32 bits can have 10 digits. 2^32 = 4294967296
33. for (unsigned long y = 1000000000; y > 0; y /= 10) {
34. putchar( (x / y) + '0');
35. x = x % y;
36. }
37. }

38.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)

39.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).

40.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.

41.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.

42.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

43.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.

44.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.

45.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?

46.Given an expression tree with no parentheses in it, write the


program to give equivalent infix expression with parentheses
inserted where necessary.

47.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.

48.Give me an algorithm and C code to find the subarray with the


largest sum given an array containing both positive and negative
integers.

49.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.

50.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.

51.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.

52.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;

53.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.

54.Write a small lexical analyzer - interviewer gave tokens. expressions


like "a*b" etc.
55.Write a routine that prints out a 2-D array in spiral order!

56.How is the readers-writers problem solved? - using


semaphores/ada .. etc.

57.Write code for reversing a linked list.

58.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).
59. int main()
60. {
61. int a[10]={1, 2, 4, 4, 7, 8, 9, 14, 14, 20};
62. int i;
63. for (i = 0;i<9;i++)
64. {
65. if (a[i] != a[i+1])
66. printf("%d\n",a[i]);
67. }
68. return 0;
69. }

Microsoft question

70.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 ?

71.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.
72.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 ].

73.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 ].

74.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 ].

75.Give a one-line C expression to test whether a number is a power of


2. [No loops allowed - it's a simple test.]

76.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.

77.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.
78.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).

79.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

80.(a-1) xor a == 0 - What does this do?

a is a power of 2.

81.How can you print singly linked list in reverse order? (it's a huge list
and you cant use recursion)

82.How can you find out if there is a loop in a very long list?

83.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)

84.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..)
85.Whats the simples way to check if the sum of two unsigned integers
has resulted in an overflow.

86.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...

87.Sum of the numbers or copy i into A[i] so on till conflict.

88.Update deltaY while incrementing x. Have to multiply so that the


deltay is not a floating pt number.

89.Find the largest 10**n less than given number, then div etc.

90.Infinite.

91.Shivku said this question is garbled thru ages.

92.reverse the pointers till you reach the end and print-and-reverse as
you return.

93.Have two 'threads' one at twice the speed of the other traversing the
list and see if at anytime they meet.
94.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.

95.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.

96.if (a+b) < a or (a+b) < b then overflow has occurred

Data structures and algorithms questions

97.Write a function and the node data structure to visit all of the nodes
in a binary tree.

98.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?

99.Give an algorithm that calculates the distance between two text


strings (only operations you can have are: delete, add, and change,
one by one).
100. 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.

101. Describe a situation where concurrent access would lead to


inconsistency in your application. How would you solve this
problem?

102. 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.

103. 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:

1. Start with two pointers ptr1 and ptr2.


2. Set ptr1 and ptr2 to the head of the linked list.
3. 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).
4. Stop when ptr1 reaches the end of the list, or when ptr1 = ptr2.
5. 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.

104. 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.

105. 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.

106. 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.

107. Reverse a linked list.

108. Insert in a sorted list

109. 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).

110. Delete an element from a doubly linked list.

111. Write a function to find the depth of a binary tree.

112. 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.

113. 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)

114. Ways of optimizing symbol table storage in compilers.

115. A walk-through through the symbol table functions, lookup()


implementation etc - The interv. was on the Microsoft C team.

116. Given an array t[100] which contains numbers between 1..99.


Return the duplicated value. Try both O(n) and O(n-square).
117. Given an array of characters. How would you reverse it. ?
How would you reverse it without using indexing in the array.

118. 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)

119. 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.

120. Do a breadth first traversal of a tree.

121. 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).

122. 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.

OP||OB///O?O?

determine where do A and C go

123. 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.

124. Implement an algorithm to reverse a doubly linked list.

125. 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.

126. The Web can be modeled as a directed graph. Come up with a


graph traversal algorithm. Make the algorithm non-recursive and
breadth-first.

127. How would you implement a hash table ? How do you deal
with collisions?

128. 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.

129. Given a history of URLs, how would you determine if a


particular URL had been seen before?
130. Since pages can have multiple URLs pointing to them, how
can you make sure you've never seen the same CONTENT before?

131. Write a function to print all of the permutations of a string.

132. 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.

133. The Web can be modeled as a directed graph. Come up with a


graph traversal algorithm. Make the algorithm non-recursive and
breadth-first.

134. Implement an algorithm to reverse a singly linked list. (with


and without recursion)

135. Implement an algorithm to reverse a doubly linked list.

136. Implement an algorithm to insert in a sorted list.

137. Delete an element from a doubly linked list.


138. 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.

139. Implement an algorithm to sort an array.

140. Given a sequence of characters, how will you convert the


lower case characters to upper case characters?

141. Write a routine that prints out a 2-D array in spiral order.

142. Count the number of set bits in a number without using a


loop.

143. 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.

144. 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.

145. How would you print out the data in a binary tree, level by
level, starting at the top?
146. Given an array of characters which form a sentence of words,
give an efficient algorithm to reverse the order of the words in it.

147. Write a function to find the depth of a binary tree.

148. 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).

149. How would you implement a queue from a stack?

150. Write a funtion that finds repeating characters in a string.

151. Write a routine to reverse a series of numbers without using


an array.

152. 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

153. Write a function to check if two rectangles defined as below


overlap or not.
154. struct rect {
155. int top, bot, left, right;
156. } r1, r2;
157. 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.

158. Write a function to reverse a singly linked list, given number


of links to reverse.

159. Write a function to convert an int to a string.

160. Some weird problem on vector calculus with some


transformation matrices being applied - need paper and pencil to
describe it.

161. 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.

162. 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.
163. 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.

164. 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

165. 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.

166. In arithmetic expressions, to what data type will the C


compiler promote a character?

It will promote it to an integer unless otherwise directed.

167. 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.

168. Increment the variable next three different ways.


169. next = next + 1;
170. and
171. next++;
172. and
173. next += 1;

174. 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 */

175. Can comments be nested?

Not in standard (K&R) C.

176. 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.

177. Specify the skeletons of two C loops with the test at the top.
178. next = 0; /* setup */
179.
180. while ( next < max) { /* test */
181. printf("Hello "); /* body */
182. next++; /* update */
183. }
184.
185. and
186.
187. for ( next = 0; next < max; next++) /* setup,test */
188. /* and update */
189. printf("Hello"); /* body */

190. Specify a C loop with the test at the bottom.


191. next = 0; /* setup */
192.
193. do {
194. printf("Hello"); /* body */
195. next++; /* update */
196. } while ( next < max); /* test */

197. What is the switch statement?

It is C's form of multiway-conditional (a.k.a case statement in Pascal).

198. 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.

199. 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.

200. 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).

201. 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.

202. 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.

203. 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.

204. 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.

205. 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.

206. 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.

207. 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.

208. 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.

209. Define a structure for a simple name/address record.


210. struct nameAddr {
211. char name[30];
212. char addr[30];
213. char city[20];
214. char state[3];
215. char zip[5];
216. };

217. 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."
218. Use typedef to make a short-cut way to declare a pointer to
the nameAddr structure above. Call it addrPtr.

typedef struct nameAddr *addrPtr;

219. Declare a variable with addrPtr called address.

addrPtr address;

220. Assuming the variable address above, how would one refer to
the city portion of the record within a C expression?

address->city

221. 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.

222. 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.

223. 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.

224. Why can't you nest structure definitions?

Trick question: You can nest structure definitions.

225. Can you nest function definitions?


No. (You can in Pascal, a close relative to C.)

226. 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?

227. 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.

228. 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.

229. 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.

230. 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);

231. 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.

232. 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.

233. What is the symbol for the modulus operator?

% (the percent symbol)

234. From the standpoint of logic, what is the difference between


the fragment:
235. if (next < max)
236. next++;
237. else
238. next = 0;

and the fragment:


next += (next < max)? (1):(-next);

Nothing. They are different ways to express the same logic.

239. 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.

240. Is C case sensitive (ie: does C differentiate between upper and


lower case letters)?

Yes.

241. 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+");

242. What does fopen() return if successful. If unsuccessful?

Upon success fopen() returns a pointer to a filestream. Otherwise it


returns the value of NULL.

243. 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.

244. Declare a pointer called fnc which points to a function that


returns an unsigned long.

unsigned long (*fnc)();

245. Declare a pointer called pfnc which points to a function that


returns a pointer to a structure of type nameAddr.

struct nameAddr *(*pfnc)();


246. 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.

247. 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.

248. Given the decimal number 27, how would one express it as a
hexadecimal number in C?

0x1B

249. What is malloc()?

This function allocates heap storage for dynamic data structures.

250. 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.)

251. 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.

252. write C code for deleting an element from a linked listy


traversing a linked list efficient way of elimiating duplicates from an
array
253. Declare a void pointer

void *ptr;

254. 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

255. What is a far pointer (in DOS)

256. 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.
257. have an array of length 26.
258. put 'x' in array element corr to 'a'
259. put 'y' in array element corr to 'b'
260. put 'z' in array element corr to 'c'
261. put 'd' in array element corr to 'd'
262. put 'e' in array element corr to 'e'
263. and so on.

the code
while (!eof)
{
c = getc();
putc(array[c - 'a']);
}

264. Write C code to implement strtok() 'c' library function.

265. Implement strstr(), strcpy(), strtok() etc


266. Reverse a string.

267. Given a linked list which is sorted, how will you insert in
sorted way.

268. Write a function that allocates memory for a two-dimensional


array of given size (parameter x & y)

269. Write source code for printHex(int i) in C/C++

270. Write a function that finds the last instance of a character in a


string.

C++ syntax, semantics and concepts questions

271. 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.

272. 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.

273. 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.

274. What is an instance?

An individual object that is a member of some class.

275. 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.

276. 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.

277. 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.

278. 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.

279. What are instance variables?

These represent an object's private memory. They are defined in an


object's class.

280. What are class variables?

These represent a class's memory which it shares with each of its


instances.

281. 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.

282. 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.

283. 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:

o It vigorously enforces data typing conventions.


o It allows variables to be defined where they are used.
o It allows the definition of real (semantically significant) constants.
o It allows for automatic pointer dereferencing.
o It supports call-by-reference in addition to call-by-value in
functions.
o 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.

2. 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.

3. What is cin and cout?

They are objects corresponding to a program's default input and output


files.

4. 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.

5. 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.

6. 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.

7. 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.

8. 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.

9. 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++.

10. 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.
11. 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.

12. 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.

13. 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.

14. 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.

15. 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.

16. 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.

17. 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.

18. What is the result of compiling this program in a C compiler?


in a C++ compiler?
19. int __ = 0;
20. main() {
21. int ___ = 2;
22. printf("%d\n", ___ + __);
23. }
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.

24. 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.

25. 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.

26. 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.

27. 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.
28. 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.

29. 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.

30. 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.

31. 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.

32. What is UML ?

UML refers to Unified Modeling Language. It is a language used to


model OO problem spaces and solutions.

33. 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.

34. What are the differences between new and malloc?

35. What is the difference between delete and delete[]?

36. What are the differences between a struct in C and in C++?

37. What are the advantages/disadvantages of using #define?

38. What are the advantages/disadvantages of using inline and


const?

39. What is the difference between a pointer and a reference?

40. When would you use a pointer? A reference?

41. What does it mean to take the address of a reference?

42. What does it mean to declare a function or variable as static?


43. What is the order of initalization for data?

44. What is name mangling/name decoration?

45. What kind of problems does name mangling cause?

46. How do you work around them?

47. What is a class?

48. What are the differences between a struct and a class in C++?

49. What is the difference between public, private, and protected


access?

50. For class CFoo { }; what default methods will the compiler
generate for you>?

51. How can you force the compiler to not generate them?
52. What is the purpose of a constructor? Destructor?

53. What is a constructor initializer list?

54. When must you use a constructor initializer list?

55. What is a: Constructor? Destructor? Default constructor?


Copy constructor? Conversion constructor?

56. What does it mean to declare a... member function as virtual?


member function as static? member varible as static? destructor as
static?

57. Can you explain the term "resource acqusition is


initialization?"

58. What is a "pure virtual" member function?

59. What is the difference between public, private, and protected


inheritance?

60. What is virtual inheritance?


61. What is placement new?

62. What is the difference between operator new and the new
operator?

63. What is exception handling?

64. Explain what happens when an exception is thrown in C++.

65. What happens if an exception is not caught?

66. What happens if an exception is throws from an object's


constructor?

67. What happens if an exception is throws from an object's


destructor?

68. What are the costs and benefits of using exceptions?

69. When would you choose to return an error code rather than
throw an exception?
70. What is a template?

71. What is partial specialization or template specialization?

72. How can you force instantiation of a template?

73. What is an iterator?

74. What is an algorithm (in terms of the STL/C++ standard


library)?

75. What is std::auto_ptr?

76. What is wrong with this statement? std::auto_ptr ptr(new


char[10]);

77. 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.

78. What output does the following code generate? Why? What
output does it generate if you make A::Foo() a pure virtual
function?
79. #include
80. class A {
81. public:
82. A() {
83. this->Foo();
84. }
85. virtual void Foo() {
86. cout << "A::Foo()" << endl;
87. }
88. };
89. class B : public A {
90. public:
91. B() {
92. this->Foo();
93. }
94. virtual void Foo() {
95. cout << "A::Foo()" << endl;
96. }
97. };
98. int main(int, char**)
99. {
100. B objectB;
101. }
102.
103. p {return 0;
104. }

105. What output does this program generate as shown? Why?


106. #include
107. class A {
108. public:
109. A() {
110. cout << "A::A()" << endl;
111. }
112. ~A() {
113. cout << "A::~A()" << endl; throw "A::exception";
114. }
115. };
116. class B {
117. public:
118. B() {
119. cout << "B::B()" << endl; throw "B::exception";
120. }
121. ~B() {
122. cout << "B::~B()";
123. }
124. };
125. int main(int, char**) {
126. try {
127. cout << "Entering try...catch block" << endl;
128. }
129.
130. p {A objectA;
131. B objectB;
132. }
133.
134. p {cout << "Exiting try...catch block" << endl;
135. } catch (char* ex) {
136. cout << ex << endl;
137. }
138. }
139.
140. p {return 0;
141. }

142. 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).

143. 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

144. 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.

145. 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.

146. 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.

147. 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.

148. 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.

149. 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.

Design

150. Draw a class diagram (UML) for a system. (They described


the system in plain english).

151. Which do you prefer, inheritance or delegation? Why?

152. What is the difference between RMI and IIOP?

Java questions

153. http://www.javaprepare.com/quests/question.html

Misc. Questions (Design pattern, HTTP, OOP, SQL)

154. What's the difference between SQL, DDL, and DML?

155. What's a join? An inner join? An outer join?

156. Describe HTTP.

157. What's a design pattern?


158. Can you explain the singleton, vistor, facade, or handle class
design pattern?

159. When you do an ls -l, describe in detail everything that comes


up on the screen.

160. Tell me three ways to find an IP address on a Unix box.

161. Write a bubble sort.

162. Write a linked list.

163. Describe an object.

164. What does object-oriented mean to you.

165. Can you explain what a B tree is?

166. What's the difference between UDP and TCP?


167. What is ICMP?

168. What's the difference between a stack and a Queue?

169. Do you know anything about the protection rings in the PC


architecture?

170. How much hardware/Assembler/Computer Architecture


experience do you have.

171. Explain final, finalize, and finally. When the finalize is


invoked? How does GC work? etc.

172. What is your experience with Servlet and JSP?

173. What is the Prototype design pattern?

174. 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?

175. Give an example in which you will combine several design


patterns, and explain how the system can benefit from that.
176. Why would you apply design patterns (benefits)?

177. What is a two-phase commit?

178. What will happen if one of your web-server or appserver


crashs during its execution?

179. What are various problems unique to distributed databases

180. 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

181. what is disk interleaving

182. why is disk interleaving adopted

183. given a new disk, how do you determine which interleaving is


the best
184. give 1000 read operations with each kind of interleaving
determine the best interleaving from the statistics

185. 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)

186. Design a memory management scheme.

187. 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

188. How did you get into computer science?

189. What kind of technical publications (print or online) do you


read on a regular basis?

190. What was the last book you read (does not have to be job
related!)

191. If you could recommend one resource (book, web site, etc.) to
a new software developer just out of school, what would it be?
192. What was the most interesting project that you worked on?

193. What was the most challenging project that you worked on?

194. If you could have any job in the world, what would it be?

195. Tell me about your favorite class.

196. Tell me about your favorite project [with lots of follow-up


questions].

197. Tell me about a something you did that was unsuccessful, a


project or class that didn't go well.

198. Do you prefer a structured or unstructured working


environment.

199. A chemist calls you up and says his Netscape isn't working.
What's wrong and how do you find out?

200. How do you prioritize multiple projects?


201. Tell me about previous jobs?

202. What are your greatest strengths and weaknesses?

203. Tell us about yourself.

204. Where would you like to be in five years?

205. How do you see yourself fitting in to this company?

206. Do you have any questions for me?

207. Why did you leave your last job.

208. Did you finance your own education?

209. Are you good with people?

210. Have you experience working on a group project?


211. How well do you know the windows menus?

212. What was the hardest program error for you to find and
correct?

213. What did you find hardest when working with others in a
project?

214. What is a tool or system that you learned on your own? i.e.
not in a class room?

215. As a developer, would you prefer to use application server?


Why?

216. 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).

217. Tradeoff between time spent in testing a product and getting


into the market first.

218. What to test for given that there isn't enough time to test
everything you want to.
219. Why do u think u are smart.

220. Questions on the projects listed on the Resume.

221. Do you want to know any thing about the company.( Try to
ask some relevant and interesting question).

222. How long do u want to stay in USA and why?

223. What are your geographical preference?

224. What are your expectations from the job.

Interview Questions
If you would like to contribute to the list or send feedback, please email Kundan Singh.

S-ar putea să vă placă și