You are on page 1of 73

amazon

String reversal in place


String reversal in place

An array consists of elements where each element appears an even number of times. Only 1 element appears odd number of times. Find that number

Question: There is an integer array consisting positive numbers only. Find maximum possible sum of elements such that there are no 2 consecutive elements present in the sum.

If given array is (6, 4, 2, 8, 1), the answer will be 14 (8+6). This is the maximum sum we can obtain without taking two consecutive elements.

There is an integer array consisting positive and negative integers. Find maximum positive difference S defined as:

S = a[i] - a[j] where i>j and S > 0


Stock prices are given to you at various time intervals. p1, p2, p3,... you are allowed to buy and sell only once each. So write a program to find the index where you would buy and where you would sell to maximize profit

here is a huge file containing billions of integers. Find maximum 20 integers form that file.

Maintain a MIN heap of 20 elements and iterate through given data each time a no is greater then min in heap replace min with that number Worst case compl -- m*log20

Vowel removal in a string inplace

Preorder post order

What is the angle between the minute and hour hands on a clock?
The angle between the two hands changes constantly at the rate of 5.5 per minute. This formula finds the angle between the two hands for a given time (h:m) taking the absolue value as shown: |5.5m - 30h| //( 6*m-(30*h+30*m/60)) If the result is greater than 180, subtract it from 360 to get the included angle.

fibonnacci
Fibonnaci in logn complexity

array map [0...n] = { 0 => 0, 1 => 1 } fib( n ) if ( map( n ) is cached ) return map( n ) return map( n ) = fib( n - 1 ) + fib( n - 2 )

fib( n ) array map [0...n] = { 0 => 0, 1 => 1 } for ( i from 2 to n ) map[i] = map[i-1] + map[i-2] return map[ n ]

In mathematics, the Fibonacci numbers are the numbers in the following integer sequence: Recursive Fibonnaci O(2^n); Iterative Fibonnacci O(n); because the number of binary operations required to find fib(n) roughly doubles each time n increases by 1.

At a bus-station, you have time-table for buses arrival and departure. You need to find the minimum number of platforms so that all the buses can be accommodated as per their schedule.

public static bool IsPalindrome(int n) { for (int i = 0; i < 16; i++) { if (((n >> i) & 1) != ((n >> (31 - i)) & 1)) { return false; } } return true; }

How to check if the binary representation of an integer is a palindrome?

Card game with classes

Given a value v, in a BST find the next value in order.


1. Find the value in by traversing and then when the value is found (in log2(n) traverses atmost), 2. Check if rightNode is not null if not then traverse the rightNode->left->left->left... until left !=NULL the last value before null is the next one in order For Ex: in wikipedia in the figure, given the value '3' find the next in order. So when we reach 3 we go to right i.e. 6. then traverse left branches only. the last left non-null node is '4'. That is the next one in order. http://en.wikipedia.org/wiki/File:Binary_search_tree.s vg

Class Destructor (contd)


Delete the tree in a "bottom-up" fashion Postorder traversal is appropriate for this !!
TreeType::~TreeType()
{

Destroy(root);
}

void Destroy(TreeNode<ItemType>*& tree)


{

if(tree != NULL) { Destroy(tree->left); Destroy(tree->right); delete tree;


} }

Describe the thread states in Java


New, Runnable, Not Runnable, Dead. What is the name of the Java garbage collection algorithm? Reference counting Tracing collectors Mark-sweep collectors Copying collectors Heap compaction Mark-compact collectors

Extract email address


Extract email addresses from a line with Grep
grep -o [[:alnum:]+\.\_\-]*@[[:alnum:]+\.\_\-]*

Justify whether a binary tree is a BST.


perform inorder on the tree..if it results into a sorted sequence..the tree was a BST

Create the necessary classes when you are asked to model the card game.
Class of card, deck and appropriate instance variables and operation

Given k number of sorted arrays, describe an algorithm to merge them into one array with each element remain sorted. Analyze the complexity.

Given an ordered circular array of integers, find an element. Meaning the array is ordered, but the lowest element is not at the first index.

Intersection and union of arrays

Height of a binary tree

An integer is represented in binary as a sequence of 0's and 1's. Write a function that returns the number of 1's in the binary representation of a given integer.

unsigned int v; // count the number of bits set in v unsigned int c; // c accumulates the total bits set in v for (c = 0; v; c++) { v &= v - 1; // clear the least significant bit set }

Regex for US zip code


/(^\d{5}$)|(^\d{5}-\d{4}$)/

Without using any high level language methods (such as indexOf()) write a function that takes two strings (A and B) and checks to see if B is in A, if it is return the index that B starts at

How would you implement a priority queue?


Like a sorted linked list sorted on the priority. http://en.wikipedia.org/wiki/Priority_queue

Partition an array in such way zeros to be moved on the left side of the array, other numbers on the right side of the array. Extra storage not allowed, only in-place.

int j = 0; for (int i = 0; i < vec.length; ++i) { if (vec[i] == 0) { if (i > j) { vec[i] = vec[j]; vec[j] = 0; } j++; }

How would you test a search engine ?


1.) Response Time. 2.) Number of servers the engine is using to retrieve data for the search. 3.) Throughput 4.) Simulate search engine using several multithreaded searches.

Distribute hash table


Responsibility for maintaining the mapping from keys to values is distributed among the nodes. Any participating node can efficiently retrieve the value associated with a given key Decentralization: the nodes collectively form the system without any central coordination. Scalability: the system should function efficiently even with thousands or millions of nodes. Fault tolerance: the system should be reliable (in some sense) even with nodes continuously joining, leaving, and failing.

Cycles in a graph
The cycle detection algorithm for trees can easily be modified to work for graphs. The key is that in a DFS of an acyclic graph, a node whose descendants have all been visited can be seen again without implying a cycle. However, if a node is seen a second time before all of its descendants have been visited, then there must be a cycle. Can you see why this is? Suppose there is a cycle containing node A. Then this means that A must be reachable from one of its descendants. So when the DFS is visiting that descendant, it will see A again, before it has finished visiting all of A s descendants. So there is a cycle. In order to detect cycles, we use a modified depth first search called a colored DFS. All nodes are initially marked white. When a node is encountered, it is marked grey, and when its descendants are completely visited, it is marked black. If a grey node is ever encountered, then there is a cycle.

DFS BFS of a graph


http://www.youtube.com/watch?v=or9xlA3YY zo DfS stack BfS queue

Preorder Traversal with a Stack

Preorder traversal without recursion


Push the root onto the stack. While the stack is not empty
pop the stack and visit it push its two children
14 43
Stack

84

13

33

97

53

99

72

64
38

14 84 13 53 16 99 72 43 33 64 97 51 25

Post order without recursion

Level order traversal without recursion

front() back() push_back() pop_front()

Level order with recursion http://geeksforgeeks.org/?p=2686

Height of a tree

Tree traversal inorder

Binary search tree insertion


Check if the root is null add it as node Same procedure as binary search. Deletion There are three possible cases to consider: Deleting a leaf (node with no children): Deleting a leaf is easy, as we can simply remove it from the tree. Deleting a node with one child: Remove the node and replace it with its child. Deleting a node with two children: Call the node to be deleted N. Do not delete N. Instead, choose either its in-order successor node or its in-order predecessor node, R. Replace the value of N with the value of R, then delete R. As with all binary trees, a node's in-order successor is the left-most child of its right subtree, and a node's in-order predecessor is the right-most child of its left subtree. In either case, this node will have zero or one children. Delete it according to one of the two simpler cases above.

Consistently using the in-order successor or the inorder predecessor for every instance of the two-child case can lead to an unbalanced tree, so good implementations add inconsistency to this selection.

Deadlock
A deadlock is a situation wherein two or more competing actions are each waiting for the other to finish, and thus neither ever does. It is often seen in a paradox like the "chicken or the egg". "a lock having no keys"

Swap binary tree

Merge two binary search tree


take each element from a tree and insert it into the other... Complexity of this method being O(n1 * log(n2)).. Flattening a BST into a sorted list is O(N)
It's just "in-order" iteration on the whole tree. Doing it for both is O(n1+n2)

Merging two sorted lists is into one sorted list is O(n1+n2).


Keep pointers to the heads of both lists Pick the smaller head and advance its pointer This is how the merge of merge-sort works

Creating a perfectly balanced BST from a sorted list is O(N)


The value at the middle would be the root, and recurse. In our case the sorted list is of size n1+n2. so O(n1+n2) The resulting tree would be the conceptual BST of binary searching the list

Three steps of O(n1+n2) result in O(n1+n2) For n1 and n2 of the same order of magnitude, that's better than O(n1 * log(n2))

How can I find the common ancestor of two nodes in a binary tree?

Binary search treehttp://geeksforgeeks.org/?p=1029


Algorithm: The main idea of the solution is While traversing Binary Search Tree from top to bottom, the first node n we encounter with value between n1 and n2, i.e., n1 < n < n2 is the Lowest or Least Common Ancestor(LCA) of n1 and n2 (where n1 < n2). So just traverse the BST in pre-order, if you find a node with value in between n1 and n2 then n is the LCA, if it's value is greater than both n1 and n2 then our LCA lies on left side of the node, if it's value is smaller than both n1 and n2 then LCA lies on right side.

Defining Objects with Classes


http://msdn.microsoft.com/enus/beginner/ff715357.aspx The code which describes all of the object s properties and methods is called a class. We can think of a Class as the blueprint, and an Object as an instance (or specific example) of that Class such as the house down the street.

Classes and objects are separate but related concepts. Every object belongs to a class and every class contains one or more related objects. A Class is static. The attributes of a class don't change. An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime the attributes of the object may undergo significant change. A class is a general concept while objects are the specific and real instances that embody that concept.

Singleton pattern
Suppose we have to use a single object of a class throughout the lifetime of an application The Singletons are often used to control access to resources such as database connections or sockets. Suppose we have a license for only one connection for our database. A Singleton connection object makes sure that only one connection can be made at any time.

There are lots of different ways to implement the Singleton Pattern. But by using a private constructor and a static method to create and return an instance of the class is a popular way for implementing Singleton Pattern. The UML representation of a Singleton Pattern is shown below. http://www.codeproject.com/KB/cpp/singleto nrvs.aspx

In computer programming, the strategy pattern (also known as the policy pattern) is a particular software design pattern, whereby algorithms can be selected at runtime.

The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.

For instance, a class that performs validation on incoming data may use a strategy pattern to select a validation algorithm based on the type of data, the source of the data, or other discriminating factors. These factors are not known for each case until runtime, and may require radically different validation to be performed. The validation strategies, encapsulated separately from the validating object, may be used by other validating objects in different areas of the system (or even different systems) without code duplication.

Visitor pattern
In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure it operates on. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures. Thus, using the visitor pattern allows to conform with the open/closed principle.

Model view controller


Model-View-Controller is a fundamental design pattern for the separation of user interface logic from business logic.

It is important to note that both the view and the controller depend on the model. However, the models depends on neither the view nor the controller. This is one the key benefits of the separation. This separation allows the model to be built and tested independent of the visual presentation. The model is used to manage information and notify observers when that information changes.

The view renders the model into a form suitable for interaction, typically a user interface element. Multiple views can exist for a single model for different purposes. A viewport typically has a one to one correspondence with a display surface and knows how to render to it. The controller receives input and initiates a response by making calls on model objects. A controller accepts input from the user and instructs the model and viewport to perform actions based on that input.

chess

http://www.cs.geneseo.edu/~bald win/sc/note-ch2.html
Objects. The pieces are clear examples of objects. (Chess masters and the board may also be seen as objects, although they don t embody the concept as clearly as pieces do.) Pieces have all the key characteristics of objects, namely Behavior, since pieces move in specific ways in response to the directions they receive from chess masters State, for example position on the board, or in-play vs captured status Distinct identities, made tangible by the fact that each piece is represented by a distinct person. Messages. The directions that the chess masters give to the pieces are messages. Most of these directions convey the basic command move, albeit with a much more flexible syntax than messages in programming languages, or even pseudocodes. The fact that the directions are delivered verbally allows students to perceive the act of sending a message, and provides an analogy for message delivery inside a program.

Parameters. The move command that chess masters send to pieces is supplemented with information on which square a piece is to move to. Conveying supplemental information is exactly what parameters to messages do. As with the messages themselves, the format for parameters is far less rigid in mini-chess than in programs or pseudocode, but the fundamental concept is the same in both contexts. Classes and Subclasses. The set of all pieces is a class, characterized by handling the move message and by having state related to position or in-play/captured status. If students consider the chess masters or board to be objects, then these objects represent additional, very different, classes. In any case, since different kinds of piece respond to move messages differently, pawns, knights, kings, and queens each represent a different subclass of piece.

Inheritance. Pawns, knights, kings, and queens inherit the state information that all pieces have. They also inherit the move message interface, although not its implementation. Preconditions. Chess has precise rules about when a move is legal. For example, you cannot make a move that exposes your own king to capture, most pieces cannot move through a square occupied by another piece, etc. These rules are preconditions for the move message. Postconditions. Each move has a number of consequences at the very least, the moved piece s position changes, and possibly an opposing piece gets captured, the opposing king is placed in check, etc. These consequences are postconditions of the move message. Some of these postconditions are conditional, i.e., they are only established some of the time. This can lead to discussion beyond what is in the book about how to specify such postconditions (is the condition part of the postcondition, as in and any opposing piece that was on the square this piece moved to is removed from play? Is it clearer to use multiple precondition/postcondition pairs, as in precondition 1: there are no pieces on the squares this piece moves over or stops on; postcondition 1: this piece is on the new square; precondition 2: there are no pieces on the squares this piece moves over but an opposing piece is on the square on which this piece stops; postcondition 2: this piece is on the new square and the opposing piece is removed from play? ) This is a discussion that probably won t produce definite conclusions, but it does provide an opportunity to talk about which (if any) style the instructor prefers, when one style might be better than others, etc.

Object oriented design. An interesting example of alternative class hierarchies sometimes arises while discussing mini-chess: should the immediate subclasses of piece be pawn, knight, queen, and king, or should they be black piece and white piece, with sub-subclasses black pawn, white pawn, black knight, etc? In the former case, should there be black and white sub-subclasses of pawn, knight, queen, and king? Such issues of class design are really beyond the scope of Algorithms and Data Structures: The Science of Computing, but if someone raises them they offer an opportunity to preview software engineering issues that more advanced courses may explore. (To offer an answer to the question, although probably not the only defensible one, the interfaces and behaviors of differently colored pieces are really identical, so it makes sense for color to be a publicly readable part of a piece s state, but not to be reflected in classes.)

What is the difference between an object and a class?


Classes and objects are separate but related concepts. Every object belongs to a class and every class contains one or more related objects. A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don't change. The class to which an object belongs is also (usually) static. If a particular object belongs to a certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed. An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change.

Abstract vs interface
A class can implement any number of interfaces but a subclass can at most use only one abstract class. An abstract class can have non-abstract Methods(concrete methods) while in case of Interface all the methods has to be abstract. An abstract class can declare or use any variables while an interface is not allowed to do so.

An abstract class can have constructor declaration while an interface can not do so. An abstract Class is allowed to have all access modifiers for all of its member declaration while in interface we can not declare any access modifier(including public) as all the members of interface are implicitly public. http://www.csharpcorner.com/UploadFile/prasoonk/Abstra ctClassvsInterface06102009051117AM/Abstra ctClassvsInterface.aspx

) Design a furniture management system. You will have have to design class Furniture, WoodChair, SteelChair, WoodTable, SteelTable, etc. Each furniture has material(s) -- wood, steel, cotton. You have to design functions: applyFire(), applyWeight(), etc. Make your system easy to extend in order to include more materials and more subclasses like Futon. http://www.careercup.com/question?id=387978 Decorator pattern
abstract Class Furniture { //functions; } class WoodChair :public Furniture this is a typical bridge pattern { //function impl } class SteelTable :public Furniture { //function impl } ... ... abstract class FurnitureDecorator : public Furniture { //func } class Wood : public FurnitureDecorator { Furniture decorating_furniture; //func imp using the functions of decorating_furniture; }

scenario. period.

You might also like