网上有不少Microsoft的测试题,引来不少的眼光。在这里把所有的测试题加以整理,再附上答案。(个别题目答案有多种,文本仅代表作者的思路)每道题的后面会给出一个时间。这个时间是作者做出该题所用的时间。(注意,这不是什么标准时间,相信所有浏览本试卷的朋友都会在某一道或多道题上找到灵感,迅速解题的) !
一.最基本题型(说明:此类题型比较简单)
1.烧一根不均匀的绳,从头烧到尾总共需要1个小时。现在有若干条材质相同的绳子,问如何用烧绳的方法来计时一个小时十五分钟呢?(这道题我当初想了一个小时)
2.你有一桶果冻,其中有黄色、绿色、红色三种,闭上眼睛抓取同种颜色的两个。抓取多少个就可以确定你肯定有两个同一颜色的果冻?(5秒-1分钟)
3.如果你有无穷多的水,一个3公升的提捅,一个5公升的提捅,两只提捅形状上下都不均匀,问你如何才能准确称出4公升的水?(40秒-3分钟)
4.一个岔路口分别通向诚实国和说谎国。来了两个人,已知一个是诚实国的,另一个是说谎国的。诚实国永远说实话,说谎国永远说谎话。现在你要去说谎国,但不知道应该走哪条路,需要问这两个人。请问应该怎么问?(20秒-2分钟)
5.12个球一个天平,现知道只有一个和其它的重量不同,问怎样称才能用三次就找到那个球。13个呢?(注意此题并未说明那个球的重量是轻是重,所以需要仔细考虑)(5分钟-1小时) _
6.在9个点上画10条直线,要求每条直线上至少有三个点?(3分钟-20分钟)
.在一天的24小时之中,时钟的时针、分针和秒针完全重合在一起的时候有几次?都分别是什么时间?你怎样算出来的?(5分钟-15分钟)
二.没有答案型(说明:这些题显然不是考你智力。而考的是你的反应能力。这种题大多数没有答案,但是要看你的反应喽!)
1.为什么下水道的盖子是圆的?
2.中国有多少辆汽车?
3.将汽车钥匙插入车门,向哪个方向旋转就可以打开车锁?
4.如果你要去掉中国的34个省(含自治区、直辖市和港澳特区及台湾省)中的任何一个,你会去掉哪一个,为什么?
5.多少个加油站才能满足中国的所有汽车?
6.想象你站在镜子前,请问,为什么镜子中的影象可以颠倒左右,却不能颠倒上下?
7.为什么在任何旅馆里,你打开热水,热水都会瞬间倾泻而出?
8.你怎样将Excel的用法解释给你的奶奶听?
9.你怎样重新改进和设计一个ATM银行自动取款机?
10.如果你不得不重新学习一种新的计算机语言,你打算怎样着手来开始?
如果你的生涯规划中打算在5年内受到奖励,那获取该项奖励的动机是什么?观众是谁?
如果微软告诉你,我们打算投资五百万美元来启动你的投资计划,你将开始什么样商业计划?为什么?
13.如果你能够将全世界的电脑厂商集合在一个办公室里,然后告诉他们将被强迫做一件事,那件事将是什么?
三.难题(说明:这类题有一定难度,如果得不到答案,也不能说明什么。如果你想到了解题思路,那么答案马上就能出来。如果想不到思路,那么……就别想解出来了。)
你让工人为你工作7天,回报是一根金条,这个金条平分成相连的7段,你必须在每天结束的时候给他们一段金条。如果只允许你两次把金条弄断,你如何给你的工人付费?
2.有一辆火车以每小时15公里的速度离开北京直奔广州,同时另一辆火车每小时20公里的速度从广州开往北京。如果有一只鸟,以30公里每小时的速度和两辆火车同时启动,从北京出发,碰到另一辆车后就向相反的方向返回去飞,就这样依次在两辆火车之间来回地飞,直到两辆火车相遇。请问,这只鸟共飞行了多长的距离? .
3.你有四个装药丸的罐子,每个药丸都有一定的重量,被污染的药丸是没被污染的药丸的重量+1。只称量一次,如何判断哪个罐子的药被污染了?
4.门外三个开关分别对应室内三盏灯,线路良好,在门外控制开关时候不能看到室内灯的情况,现在只允许进门一次,确定开关和灯的对应关系?
5.人民币为什么只有1、2、5、10的面值?
6.你有两个罐子以及50个红色弹球和50个蓝色弹球,随机选出一个罐子, 随机选出一个弹球放入罐子,怎么给出红色弹球最大的选中机会?在你的计划里,得到红球的几率是多少?
u四.超难题(说明:如果你是第一次看到这种题,并且以前从来没有见过类似的题型,并且能够在半个小时之内做出答案。只能说明你的智力超常……)
第一题 . 五个海盗抢到了100颗宝石,每一颗都一样大小和价值连城。他们决定这么分:
抽签决定自己的号码(1、2、3、4、5)
首先,由1号提出分配方案,然后大家表决,当且仅当超过半数的人同意时,按照他的方案进行分配,否则将被扔进大海喂鲨鱼
如果1号死后,再由2号提出分配方案,然后剩下的4人进行表决,当且仅当超过半数的人同意时,按照他的方案进行分配,否则将被扔入大海喂鲨鱼
^依此类推
条件:每个海盗都是很聪明的人,都能很理智地做出判断,从而做出选择。
问题:第一个海盗提出怎样的分配方案才能使自己的收益最大化?
第二题 . 一道关于飞机加油的问题,已知:
每个飞机只有一个油箱, '
飞机之间可以相互加油(注意是相互,没有加油机)
一箱油可供一架飞机绕地球飞半圈,
问题:
为使至少一架飞机绕地球一圈回到起飞时的飞机场,至少需要出动几架飞机?(所有飞机从同一机场起飞,而且必须安全返回机场,不允许中途降落,中间没有飞机场)
五.主观题(说明:在以后的工作过程中,我们可定会犯这样那样的错误。既然错误已经酿成,损失在所难免,我们只能想办法把损失减少到最小。如果能巧妙地回答出这些问题,再发生错误的情况下。能让客户有最少的抱怨,公司有最少的损失。)
1.某手机厂家由于设计失误,有可能造成电池寿命比原来设计的寿命短一半(不是冲放电时间),解决方案就是免费更换电池或给50元购买该厂家新手机的折换券。请给所有已购买的用户写信告诉解决方案。
"2.一高层领导在参观某博物馆时,向博物馆馆员小王要了一块明代的城砖作为纪念,按国家规定,任何人不得将博物馆收藏品变为私有。博物馆馆长需要如何写信给这位领导,将城砖取回。
3.营业员小姐由于工作失误,将2万元的笔记本电脑以1.2万元错卖给李先生,王小姐的经理怎么写信给李先生试图将钱要回来?
六.算法题(说明:这些题就不是什么花样了,考的是你的基础知识怎么样。再聪明而没有实学的人都将会被这些题所淘汰。)
1.链表和数组的区别在哪里?
2.编写实现链表排序的一种算法。说明为什么你会选择用这样的方法?
3.编写实现数组排序的一种算法。说明为什么你会选择用这样的方法?
4.请编写能直接实现strstr()函数功能的代码。
5.编写反转字符串的程序,要求优化速度、优化空间。
6.在链表里如何发现循环链接? .
7.给出洗牌的一个算法,并将洗好的牌存储在一个整形数组里。
8.写一个函数,检查字符是否是整数,如果是,返回其整数值。(或者:怎样只用4行代码编写出一个从字符串到长整形的函数?)
9.给出一个函数来输出一个字符串的所有排列。
.请编写实现malloc()内存分配函数功能一样的代码。
给出一个函数来复制两个字符串A和B。字符串A的后几个字节和字符串B的前几个字节重叠。
12.怎样编写一个程序,把一个有序整数数组放到二叉树中?
13.怎样从顶部开始逐层打印二叉树结点数据?请编程。
14.怎样把一个链表掉个顺序(也就是反序,注意链表的边界条件并考虑空链表)?
答案
[解答与提示] 一.最基本题型
1.一要一头烧,一根从两头烧,再有一根做参照,两头烧完的记下位置(即烧到这里要半小时),把参照的那根从标记位置处剪开,取其中一段A。
一头烧的那根烧完后(就是一个小时后),把A从两头开始烧,烧完后即为十五分钟,加起来共一小时十五分钟。
2.4个。
3.大桶装满水,倒入小桶,大桶剩下2公升水。小桶水倒掉,大桶剩2公升水倒入小桶中,大桶再装满后,倒入小桶至小桶满,大桶即剩4公升
4.如果参加过类似于奥林匹克数学班的,都应做过这些题。问他你的国家怎么走,他肯定指向的是诚实国。
5.12个时可以找出那个是重还是轻,13个时只能找出是哪个球,轻重不知。
把球编为①②③④⑤⑥⑦⑧⑨⑩⑾⑿。(13个时编号为⒀)
第一次称:先把①②③④与⑤⑥⑦⑧放天平两边,
㈠如相等,说明特别球在剩下4个球中。
把①⑨与⑩⑾作第二次称量,
⒈如相等,说明⑿特别,把①与⑿作第三次称量即可判断是⑿是重还是轻
⒉如①⑨<⑩⑾说明要么是⑩⑾中有一个重的,要么⑨是轻的。
把⑩与⑾作第三次称量,如相等说明⑨轻,不等可找出谁是重球。
⒊如①⑨>⑩⑾说明要么是⑩⑾中有一个轻的,要么⑨是重的。
把⑩与⑾作第三次称量,如相等说明⑨重,不等可找出谁是轻球。
㈡如左边<右边,说明左边有轻的或右边有重的
把①②⑤与③④⑥做第二次称量 '
⒈如相等,说明⑦⑧中有一个重,把①与⑦作第三次称量即可判断是⑦与⑧中谁是重球
⒉如①②⑤<③④⑥说明要么是①②中有一个轻的,要么⑥是重的。
把①与②作第三次称量,如相等说明⑥重,不等可找出谁是轻球。
⒊如①②⑤>③④⑥说明要么是⑤是轻的,要么③④中有一个是重的。 .
把③与④作第三次称量,如相等说明⑤轻,不等可找出谁是重球。
㈢如左边>右边,参照㈡相反进行。
当13个球时,第㈠步以后如下进行。
把①⑨与⑩⑾作第二次称量,
⒈如相等,说明⑿⒀特别,把①与⑿作第三次称量即可判断是⑿还是⒀特别,但判断不了轻重了。
⒉不等的情况参见第㈠步的⒉⒊
6. 见下面的点 10条线的情况是 123 456 789 148 159 247 258 269 357 368
① ② ③
④⑤⑥
⑦ ⑧ ⑨
注意是24小时不是12小时。
首先考察时针与分针的情况,很容易看出分针转一圈与时针只重合一次,就是一小时一次。但11时与0时的分钟区内共享一个重合点,所只
二.没有答案型
1.圆井盖掉不下去
2.一千万
3.顺时针方向。
4.
5.十万个
6.答案是"This feature is by design." 如果考官要求给出更加合理的解释,就对他说:"如果您对此问题有更多疑问,请与它的供应商(或者与它的发明人)联系"。 答案是眼睛是左右长着的。
7.如果不倾泻而出,这家旅馆将没有人去住。
8.告诉她这是最先进的东西,她不需要动手,我来帮她做就可以。
9.我想斯皮尔伯格来回答这道题是在合适不过得了。
10.我觉得回放飞网呆上半个月比较合适。 '
11.这题我没有任何想法,因为没有工作经验,所以完全没听明白他问的是什么!
12.做微软的OEM,这样能够更好的服务微软。
13.把主机箱集成在一个液晶显示器中! 只准开发我们认证的驱动!
三.难题
1.切两刀,分为1/7、2/7、4/7三段。第一天给1/7;第二天给2/7,要回1/7;第三天给1/7 ;第四天给4/7 要回1/7+2/7;第五天给1/7;第六天给2/7,要会1/7;第七天给1/7
2.北京到广州距离的30/35。
3.依次从四个罐子中取出1、2、3、4个药丸,设第一丸子应重为X,称得的重量是10X+t,t是几就是第几个罐子污染了。
4.先开一个,开很长时间。然后关掉,再开另一个。出去看,亮着的那个不用说。剩下的两个不亮的,按照灯泡的温度来进行判断。
5.可以用三张以内组成任何面额。
6.不清楚。可能是50%。
四.超难题
设5个人分别是①②③④⑤
假设前面的都扔海里了,由④来分,无论他怎么分(包括全给⑤),都面临被否决扔海里的危险。
所以,当③来分时,④⑤一个不给,全由③独吞,④为了避免被扔海里的危险,也要同意,③的方案成立
那么,在②分时,③是肯定要反对的,要赢得④⑤的同意,必须多给一个,否则有可能否决(对④⑤来说,反正③来分时还是0,你不多给一个就否决),所以②的分配方案一定是:②98 ③0 ④1 ⑤1 # A.
回到①来的分配,由于②肯定反对,为了赢得③④⑤的同意,必须在②分配方案的基础上给他们加一个,由于只需再争取两票,③④⑤中可以
排除争取一个,从收益来说,排除④⑤中的一个即可,那么①的分配方案为:①97 ③1 ④(或⑤)1 其它都不给!
二) 如果机场本身不可以加油的话 那么最少需要4架
3架同时起飞,到1/6圈时,两架飞机把各自油箱中的1/3加给另外一架,这两架剩的油正好可以原路飞回,被加油机可以飞到5/6圈处。
第4架飞机在环球飞机飞到4/6圈时起飞去接应,两飞机在5/6圈处相遇,环球机刚好用完油,加油机把1/3的油给环球机,两飞机刚好都能飞回
五.主观题
1.告诉用户我公司为答谢广大顾客长时间以来的厚爱,顾客可以持原电池免费更换使用寿命为原电池一倍的新型电池。或者可以持购买发票,获得50元购买该厂家新手机的折换券。
2.信件如下:
"xxx领导:您好!
我馆近期将展出一批珍贵文物,让更多的人能够真正的体会到中华民族文明的悠久、灿烂。我们希望能将您所拥有的明代的城砖展出。并且我们将在博物馆内设置专栏,宣传您对中华民族悠久文化的保存所作出的巨大贡献,让更多的华夏子孙看到,并且亲身体验到华夏文明的悠久历史,从而加强中华民族的凝聚力!"
!解释:
领导看过这封信以后,如果不拿出城砖。那么也就说明他不想让更多的人看到中华民族的灿烂文明,不想让中华民族有更强的凝聚力。自然也就会拿出城砖。如果领导问到何时展出完毕,可以告诉他博物馆希望永久展出这些物品,领导自然也就无话可说了。
3.信件如下:
3 尊敬的顾客,您好!
由于工作人员的失误,误将一台样品机卖给您。为了您能够更好的使用我公司的产品,我公司决定为您免费更换同等价位的笔记本一台。并且我们有性价比更加优越的xxxII 型笔记本电脑,售价20000元人民币。如果您此时购买,我们将会以19000元的优惠价格售出。"
六.算法题
请参考数据结构和计算机算法类书籍,作者就不再抄书了。
附(1):烧绳子类问题总结:
一般给出的绳子都是不均匀的。如果一根为一小时,那么半个小时的计算方法是从两头烧。十五分钟的计算方法是从两头烧,同时从中间任何一个地方开始烧,这样这根绳子就有四个燃烧点,时间自然是一个燃烧点的四分之一。如果计算十分钟的时间,那么就让绳子有六个燃烧点,方法就不用说了吧!
附(2):天平称球问题解答以及总结:
将球分为a b c d; e f g h; i j k l 三组。
第一次称量,比较 abcd efgh
情形一:
两者重量相等,此时说明答案在ijkl中。
称量ij,
如果相等,说明答案在kl中。拿k与a比较,如果相等,答案为l;如果不等,答案为k。 '
如果不等,说明答案在ij中。拿i与a比较,如果相等,答案为j;如果不等,答案为i。
情形二:
abcd轻。
在efgh中取出fgh,替换掉abcd中的bcd。 在ijkl中取出jkl,补充到原来fgh的位置。
_如果afgh轻,说明答案为a或e。称量ab,如果相等,答案为e;如果不等,答案为a。
如果afgh重,说明答案在fgh中。称量fg,如果相等,答案为h;如果不等,重者为答案。
如果一样重,答案在bcd中。称量bc,如果相等,答案为d;如果不等,轻者为答案。
情形三:
abcd重。
在efgh中取出fgh,替换掉abcd中的bcd。 在ijkl中取出jkl,补充到原来fgh的位置。
如果afgh重,答案为a或e。称量ab,如果相等,答案为e;如果不等,答案为a。 ^
如果afgh轻,答案在fgh中。称量fg,如果相等,答案为h;如果不等,轻者为所求。
如果一样重,答案在bcd中。称量bc,如果相等,答案为d;如果不等,重者为答案。
至于13个球的称法,至今本人仍没想出来。望高手赐教。
总结:(转载)
天平称重,有两个托盘比较轻重,加上托盘外面,也就是每次称重有3个结果,就是ln3/ln2比特信息。n个球要知道其中一个不同的球,如果知道那个不同重量的球是轻还是重,找出来的话那就是n个结果中的一种,就是有ln(n)/ln2比特信息,如果不知道轻重,找出来就是2n(n个球中的一个,轻或者重,所以是2n)个结果中的一种,那就是ln(2n)/ln2比特信息。
假设我们要称k次,根据信息理论,那显然两种情况就分别有:
1. k*ln3/ln2>=ln(n)/ln2 (k>=1) 解得k>=ln(n)/ln3
2. k*ln3/ln2>=ln(2n)/ln2 (k>1) 解得k>=ln(2n)/ln3
这是得到下限,可以很轻易证明满足条件的最小正整数k就是所求。比如称3次知道轻重可以从3^3=27个球中找出不同的球出来,如果不知道轻重就只能从(3^3-1)/2=13个球中找出不同的球出来。
Algorithms and Programming
1. 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 ?
2. You’re given an array containing both positive and negative integers and required to find the sub-array with the largest sum (O(N) a la KBL). Write a routine in C for the above.
3. 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 ].
4. 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 ].
5. 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 ].
6. Give a one-line C expression to test whether a number is a power of 2. [No loops allowed - it's a simple test.]
7. 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.
8. 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.
9. Give a very good method to count the number of ones in a “n” (e.g. 32) bit number.
ANS. Given below are simple solutions, find a solution that does it in log (n) steps.
Iterative
function iterativecount (unsigned int n)
begin
int count=0;
while (n)
begin
count += n & 0×1 ;
n >>= 1;
end
return count;
end
Sparse Count
function sparsecount (unsigned int n)
begin
int count=0;
while (n)
begin
count++;
n &= (n-1);
end
return count ;
end
10. What are the different ways to implement a condition where 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=a else y=b There is a logical, arithmetic and a data structure solution to the above problem.
11. Reverse a linked list.
12. Insert in a sorted list
13. 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.
14. 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.
15. Give a fast way to multiply a number by 7.
16. 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).
17. Linked list manipulation.
18. Tradeoff between time spent in testing a product and getting into the market first.
19. What to test for given that there isn’t enough time to test everything you want to.
20. 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).
21. Delete an element from a doubly linked list.
22. Write a function to find the depth of a binary tree.
23. 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.
24. 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.
25. Reverse a linked list.
Ans: Possible answers -
iterative loop
curr->next = prev;
prev = curr;
curr = next;
next = curr->next
endloop
recursive reverse(ptr)
if (ptr->next == NULL)
return ptr;
temp = reverse(ptr->next);
temp->next = ptr;
return ptr;
end
26. Write a small lexical analyzer - interviewer gave tokens. expressions like “a*b” etc.
27. Besides communication cost, what is the other source of inefficiency in RPC? (answer : context switches, excessive buffer copying). How can you optimize the communication? (ans : communicate through shared memory on same machine, bypassing the kernel _ A Univ. of Wash. thesis)
28. Write a routine that prints out a 2-D array in spiral order!
29. How is the readers-writers problem solved? - using semaphores/ada .. etc.
30. Ways of optimizing symbol table storage in compilers.
31. A walk-through through the symbol table functions, lookup() implementation etc. - The interviewer was on the Microsoft C team.
32. A version of the “There are three persons X Y Z, one of which always lies”.. etc..
33. 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.
34. Write an efficient algorithm 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.
35. The if (x == 0) y = 0 etc..
36. Some more bitwise optimization at assembly level
37. Some general questions on Lex, Yacc etc.
38. Given an array t[100] which contains numbers between 1..99. Return the duplicated value. Try both O(n) and O(n-square).
39. Given an array of characters. How would you reverse it. ? How would you reverse it without using indexing in the array.
40. Given a sequence of characters. How will you convert the lower case characters to upper case characters. ( Try using bit vector - solutions given in the C lib -typec.h)
41. Fundamentals of RPC.
42. Given a linked list which is sorted. How will u insert in sorted way.
43. Given a linked list How will you reverse it.
44. 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.
45. Do a breadth first traversal of a tree.
46. Write code for reversing a linked list.
47. 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).
48. Given an array of integers, find the contiguous sub-array with the largest sum.
ANS. Can be done in O(n) time and O(1) extra space. Scan array from 1 to n. Remember the best sub-array seen so far and the best sub-array ending in i.
49. Given an array of length N containing integers between 1 and N, determine if it contains any duplicates.
ANS. [Is there an O(n) time solution that uses only O(1) extra space and does not destroy the original array?]
50. Sort an array of size n containing integers between 1 and K, given a temporary scratch integer array of size K.
ANS. Compute cumulative counts of integers in the auxiliary array. Now scan the original array, rotating cycles! [Can someone word this more nicely?]
* 51. An array of size k contains integers between 1 and n. You are given an additional scratch array of size n. Compress the original array by removing duplicates in it. What if k << n?
ANS. Can be done in O(k) time i.e. without initializing the auxiliary array!
52. An array of integers. The sum of the array is known not to overflow an integer. Compute the sum. What if we know that integers are in 2’s complement form?
ANS. If numbers are in 2’s complement, an ordinary looking loop like for(i=total=0;i< n;total+=array[i++]); will do. No need to check for overflows!
53. An array of characters. Reverse the order of words in it.
ANS. Write a routine to reverse a character array. Now call it for the given array and for each word in it.
* 54. An array of integers of size n. Generate a random permutation of the array, given a function rand_n() that returns an integer between 1 and n, both inclusive, with equal probability. What is the expected time of your algorithm?
ANS. “Expected time” should ring a bell. To compute a random permutation, use the standard algorithm of scanning array from n downto 1, swapping i-th element with a uniformly random element <= i-th. To compute a uniformly random integer between 1 and k (k < n), call rand_n() repeatedly until it returns a value in the desired range.
55. An array of pointers to (very long) strings. Find pointers to the (lexicographically) smallest and largest strings.
ANS. Scan array in pairs. Remember largest-so-far and smallest-so-far. Compare the larger of the two strings in the current pair with largest-so-far to update it. And the smaller of the current pair with the smallest-so-far to update it. For a total of <= 3n/2 strcmp() calls. That’s also the lower bound.
56. Write a program to remove duplicates from a sorted array.
ANS. int remove_duplicates(int * p, int size)
{
int current, insert = 1;
for (current=1; current < size; current++)
if (p[current] != p[insert-1])
{
p[insert] = p[current];
current++;
insert++;
} else
current++;
return insert;
}
57. 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).
58. 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).
59. Given 3 lines of assembly code : find it is doing. IT was to find absolute value.
60. If you are on a boat and you throw out a suitcase, Will the level of water increase.
61. Print an integer using only putchar. Try doing it without using extra storage.
62. Write C code for (a) deleting an element from a linked list (b) traversing a linked list
63. What are various problems unique to distributed databases
64. Declare a void pointer ANS. void *ptr;
65. Make the pointer aligned to a 4 byte boundary in a efficient manner ANS. Assign the pointer to a long number and the number with 11…1100 add 4 to the number
66. What is a far pointer (in DOS)
67. What is a balanced tree
68. Given a linked list with the following property node2 is left child of node1, if node2 < node1 else, it is the right child.
O P
|
|
O A
|
|
O B
|
|
O C
How do you convert the above linked list to the form without disturbing the property. Write C code for that.
O P
|
|
O B
/ \
/ \
/ \
O ? O ?
determine where do A and C go
69. Describe the file system layout in the UNIX OS
ANS. describe boot block, super block, inodes and data layout
70. In UNIX, are the files allocated contiguous blocks of data
ANS. no, they might be fragmented
How is the fragmented data kept track of
ANS. Describe the direct blocks and indirect blocks in UNIX file system
71. 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. ANS.
a) have an array of length 26.
put ‘x’ in array element corr to ‘a’
put ‘y’ in array element corr to ‘b’
put ‘z’ in array element corr to ‘c’
put ‘d’ in array element corr to ‘d’
put ‘e’ in array element corr to ‘e’
and so on.
the code
while (!eof)
{
c = getc();
putc(array[c - 'a']);
}
72. what is disk interleaving
73. why is disk interleaving adopted
74. given a new disk, how do you determine which interleaving is the best a) give 1000 read operations with each kind of interleaving determine the best interleaving from the statistics
75. draw the graph with performance on one axis and ‘n’ on another, where ‘n’ in the ‘n’ in n-way disk interleaving. (a tricky question, should be answered carefully)
76. I was 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.
77. A real life problem - 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.
78.
int *a;
char *c;
*(a) = 20;
*c = *a;
printf(”%c”,*c);
what is the output?
79. Write a program to find whether a given m/c is big-endian or little-endian!
80. What is a volatile variable?
81. What is the scope of a static function in C ?
82. What is the difference between “malloc” and “calloc”?
83. struct n { int data; struct n* next}node;
node *c,*t;
c->data = 10;
t->next = null;
*c = *t;
what is the effect of the last statement?
84. If you’re familiar with the ? operator x ? y : z
you want to implement that in a function: int cond(int x, int y, int z); using only ~, !, ^, &, +, |, <<, >> no if statements, or loops or anything else, just those operators, and the function should correctly return y or z based on the value of x. You may use constants, but only 8 bit constants. You can cast all you want. You’re not supposed to use extra variables, but in the end, it won’t really matter, using vars just makes things cleaner. You should be able to reduce your solution to a single line in the end though that requires no extra vars.
85. You have an abstract computer, so just forget everything you know about computers, this one only does what I’m about to tell you it does. You can use as many variables as you need, there are no negative numbers, all numbers are integers. You do not know the size of the integers, they could be infinitely large, so you can’t count on truncating at any point. There are NO comparisons allowed, no if statements or anything like that. There are only four operations you can do on a variable.
1) You can set a variable to 0.
2) You can set a variable = another variable.
3) You can increment a variable (only by 1), and it’s a post increment.
4) You can loop. So, if you were to say loop(v1) and v1 = 10, your loop would execute 10 times, but the value in v1 wouldn’t change so the first line in the loop can change value of v1 without changing the number of times you loop.
You need to do 3 things.
1) Write a function that decrements by 1.
2) Write a function that subtracts one variable from another.
3) Write a function that divides one variable by another.
4) See if you can implement all 3 using at most 4 variables. Meaning, you’re not making function calls now, you’re making macros. And at most you can have 4 variables. The restriction really only applies to divide, the other 2 are easy to do with 4 vars or less. Division on the other hand is dependent on the other 2 functions, so, if subtract requires 3 variables, then divide only has 1 variable left unchanged after a call to subtract. Basically, just make your function calls to decrement and subtract so you pass your vars in by reference, and you can’t declare any new variables in a function, what you pass in is all it gets.
Linked lists
* 86. Under what circumstances can one delete an element from a singly linked list in constant time?
ANS. If the list is circular and there are no references to the nodes in the list from anywhere else! Just copy the contents of the next node and delete the next node. If the list is not circular, we can delete any but the last node using this idea. In that case, mark the last node as dummy!
* 87. Given a singly linked list, determine whether it contains a loop or not.
ANS. (a) Start reversing the list. If you reach the head, gotcha! there is a loop!
But this changes the list. So, reverse the list again.
(b) Maintain two pointers, initially pointing to the head. Advance one of them one node at a time. And the other one, two nodes at a time. If the latter overtakes the former at any time, there is a loop!
p1 = p2 = head;
do {
p1 = p1->next;
p2 = p2->next->next;
} while (p1 != p2);
88. Given a singly linked list, print out its contents in reverse order. Can you do it without using any extra space?
ANS. Start reversing the list. Do this again, printing the contents.
89. Given a binary tree with nodes, print out the values in pre-order/in-order/post-order without using any extra space.
90. Reverse a singly linked list recursively. The function prototype is node * reverse (node *) ;
ANS.
node * reverse (node * n)
{
node * m ;
if (! (n && n -> next))
return n ;
m = reverse (n -> next) ;
n -> next -> next = n ;
n -> next = NULL ;
return m ;
}
91. Given a singly linked list, find the middle of the list.
HINT. Use the single and double pointer jumping. Maintain two pointers, initially pointing to the head. Advance one of them one node at a time. And the other one, two nodes at a time. When the double reaches the end, the single is in the middle. This is not asymptotically faster but seems to take less steps than going through the list twice.
Bit-manipulation
92. Reverse the bits of an unsigned integer.
ANS.
#define reverse(x) \
(x=x>>16|(0×0000ffff&x)<<16, \
x=(0xff00ff00&x)>>8|(0×00ff00ff&x)<<8, \
x=(0xf0f0f0f0&x)>>4|(0×0f0f0f0f&x)<<4, \
x=(0xcccccccc&x)>>2|(0×33333333&x)<<2, \
x=(0xaaaaaaaa&x)>>1|(0×55555555&x)<<1)
* 93. Compute the number of ones in an unsigned integer.
ANS.
#define count_ones(x) \
(x=(0xaaaaaaaa&x)>>1+(0×55555555&x), \
x=(0xcccccccc&x)>>2+(0×33333333&x), \
x=(0xf0f0f0f0&x)>>4+(0×0f0f0f0f&x), \
x=(0xff00ff00&x)>>8+(0×00ff00ff&x), \
x=x>>16+(0×0000ffff&x))
94. Compute the discrete log of an unsigned integer.
ANS.
#define discrete_log(h) \
(h=(h>>1)|(h>>2), \
h|=(h>>2), \
h|=(h>>4), \
h|=(h>>8), \
h|=(h>>16), \
h=(0xaaaaaaaa&h)>>1+(0×55555555&h), \
h=(0xcccccccc&h)>>2+(0×33333333&h), \
h=(0xf0f0f0f0&h)>>4+(0×0f0f0f0f&h), \
h=(0xff00ff00&h)>>8+(0×00ff00ff&h), \
h=(h>>16)+(0×0000ffff&h))
If I understand it right, log2(2) =1, log2(3)=1, log2(4)=2….. But this macro does not work out log2(0) which does not exist! How do you think it should be handled?
* 95. How do we test most simply if an unsigned integer is a power of two?
ANS. #define power_of_two(x) \ ((x)&&(~(x&(x-1))))
96. Set the highest significant bit of an unsigned integer to zero.
ANS. (from Denis Zabavchik) Set the highest significant bit of an unsigned integer to zero
#define zero_most_significant(h) \
(h&=(h>>1)|(h>>2), \
h|=(h>>2), \
h|=(h>>4), \
h|=(h>>8), \
h|=(h>>16))
97. Let f(k) = y where k is the y-th number in the increasing sequence of non-negative integers with the same number of ones in its binary representation as y, e.g. f(0) = 1, f(1) = 1, f(2) = 2, f(3) = 1, f(4) = 3, f(5) = 2, f(6) = 3 and so on. Given k >= 0, compute f(k).
Others
98. 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)
99. What is the simples way to check if the sum of two unsigned integers has resulted in an overflow.
100. How do you represent an n-ary tree? Write a program to print the nodes of such a tree in breadth first order.
101. 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 with str2.
e.g. tr -abc -xyz
to be and not to be <- input
to ye xnd not to ye <- output