Professional Documents
Culture Documents
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:
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
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; }
Destroy(root);
}
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.
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 }
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
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++; }
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.
84
13
33
97
53
99
72
64
38
14 84 13 53 16 99 72 43 33 64 97 51 25
Height of a tree
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"
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?
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.
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.)
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.