MFC and Design Patterns

I found this article very interesting which talks about the design patterns in MFC. Its exhaustive, detailed and is an interesting read.

The singleton pattern could well have been used in implementing CWinApp objects, which represent the application and should not be instantiated more
than once. MFC relies on the programmer to define only one static instance of a
subclass of CWinApp.



An SDI(Single Document Interface) can have multiple views which is demonstrated in this Microsoft example. A Document can have multiple views associated with it, UpdateAllViews() method is called from document to update all its views. But a View is always associated with a single document. SDI and MDI are different in terms of single or multiple documents and not views.

This article in code guru, explains the steps in creating an SDI with multiple views.

CSharp and Java

I was reading through this wikipedia article which i think is the best article to read about the differences between the C# and Java. Here are the interesting differences I found:

* By Default all the methods in Java are virtual. C# doesn't have virtual by default, in fact the virtual methods should have another keyword new or override to specify if the method is overrided or not.
* C# allows pointers (within unsafe block) but Java doesn't
* C# can have all public classes in one file, but Java needs to have a public class in a file name and the filename and classname should match.
* C# implements get set properties as part of syntax. (Java, C++ obviously doesn't have this)
* In C# switch statement can also have strings (Java, C++ doesn't allow this)
* More discussion on data type differences can be found here
* C# supports operator overloading but Java does not

More to be updated...

* Checked exceptions are special kind of exceptions in java which are mentioned in the method header. The method header should have all the exceptions its going to throw, otherwise it would be a compiler error. C# doesn't have checked exceptions.
* JNI for java allows to call non-java code from java. Similarly C# has "Platform Invoke" (P/Invoke) which enables C# to call unmanaged code. P/Invoke can be used to call WIN32 APIs but not C++ libraries.
* .NET framework has .NET-COM bridge which allows to call COM components are .NET code.

ASP, .net and C Sharp: What I have learnt

* ASP is a Microsoft internet server technology which allows the developers to write server side script inline with HTML code.
code between is executed at the server. This will also do: <script language="VBScript" runat="server">
* CLR (Common Language Runtime) is the same as Virtual Machine for Java
* ASP.NET relies on .net framework and CLR which enables uses to write code in C# and other .net languages. ASP.NET is pre compiled(ASP is not) and is faster than ASP.
* ASP.NET discourages inline code blocks although it is supported.
* C# has similar concepts that Java has although there are many differences.
* C# has automatic garbage collection (which means that the objects need not be destructed in
code)
* There are no global variables in C#, every variable should belong to a class
* Duplicate variable names are not allowed in C#(unlike C and C++ where same names are alowed in different blocks)
* C# has a concept of namespaces and assemblies. assemblies are similar to Java packages.
* C# restricts only bool to be used in if conditions (no int is allowed in if stmt)
* C# allows pointers and devs can mark the pointer code as unsafe
* C# doesnt allow multiple inheritance
* C# has partial class keyword which can be used to break up class code in different files
* Generics and parametrized types are similar to templates
* Coalesce operator ("??") returns the first operator which is not null (eg a = b??0 assigns b to a)

//Hello world example in C#
public class ExampleClass
{
public static void main()
{
System.console.WriteLine("Hello World");
}
}

Before I forget...

These are the questions I came across in documentum and VC++ when I was in a technical discussion recently:

VC++
1. What is the purpose of select method with respect to sockets?
2. What are the possible multi-threading issues in COM (STA and MTA)?
3. What are the steps for a Server socket?

Documentum:
1. What are the features in documentum 5 when compared to documentum 4i
2. What are roles and groups in documentum ?
3. Is it possible to have docbroker and content server on different machines?
4. How are files stored physically in documentum server?

Notes from my Notebook

These are the notes that I have taken while reading a lot of technical books. The below text is straight from my notes and is not in any particular sequence:

1. MFC maps are dictionaries with key and value pairs
2. CDocTemplate = Docs + Views + FrameWindows
3. Activation is finding class objects, there are three ways of activation:
1. Object Binding - CoGetClassObject
2. Creating an instance of the class - CoCreateInstance
3. Getting the persistant object - CoGetInstanceFromFile
Activation also means finding class objects, loading the COM DLL, and starting the Server process.

There are two types of Activation:
1. In-process activation
2. Out-of-process activation

4. IClassFactory will have createInstance() and LockServer() methods
5. CoCreateInstanceEx = CoGetClassObject() + CreateInstance() + Release()
6. A Moniker is a locator object which finds/creates objects. A Display name is the textual representation of a moniker.

7. Inner class method calling:
carPlane::XCar::GetMaxSpeed();
8. AddRef() -> InterlockedIncrement()
Release() -> InterlockedDecrement()
9. Aggregation is a technique of exposing a binary subcomponent to a client
10. IUnknown is the most inportant interface in COM. All interfaces should be derived from IUnknown.

What I understood from design patterns...

Design patterns are the standard (documented) solutions to the common software
design problems.

From WikiPedia:

In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn't a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.

Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved. Algorithms are not thought of as design patterns, since they solve computational problems rather than design problems.

Anti-patterns, also referred to as pitfalls, are classes of commonly-reinvented bad solutions to problems. They are studied, as a category, in order that they may be avoided in the future, and that instances of them may be recognized when investigating non-working systems.


There are three types of design patterns:

1. Creational Patterns: Design patters which talk about the creation of objects are classes.

2. Structural Patterns: Design patterns which talk about the the composition of classes and objects.

3. Behavioral Patterns: Design Patterns which talk about the communication between the class objects.

There are many design patterns which fall in to one of the above categories, few of them are discussed below:

Creational Patterns:
1. Abstract Factory Pattern: In Abstract factory patterns, a group of factories are encapsulated into a single class. A factory is actually a class which instantiates an object.

From Wikipedia:

Use of this pattern makes it possible to interchange concrete classes without changing the code that uses them, even at runtime. However, employment of this pattern, as with similar
design patterns, incurs the risk of unnecessary complexity and extra work in the initial writing of code.


Code example:



class GUIFactory()
{
getFactory()
{
if (getfromregistry()=="OSX")
return (new OSXFactory());
else
return (new WinFactory());
}

//virtual so that the derived classes and override
virtual void createButton()=0;
};

class WinFactory: public GUIFactory
{
public Button createButton()
{
return(new Winbutton());
}
};

class OSXFactory: public GUIFactory
{
public Button createButton()
{
return (new OSXbutton());
}
};

//button classes
class WinButton:public Button
{
void paint()
{
cout<<"default paint procedure";
}
};

class OSXButton:public Button
{
void paint()
{
cout<<"OSX Paint procedure";
}
};

//Button class declaration and definition omitted here
void main()
{
GUIFactory obj1 =
GUIFactory.getFactory(); //instantiates the WinButton or OSXButton accordingly

Button abtn = obj1.createButton(); //creates appropriate button
abtn.paint();
}


2. Singleton pattern: Singleton pattern is perhaps most famous among the design patterns. This pattern ensures that the only one instance is created by the class. If another request id made, the existing instance is returned by the class. A Singleton class will have the class contructor as private or protected so that constrctor cannot be called directly. A Singleton will have an Instance() method which actually takes care of instancing the class.

There are many ways to create a singleton, here is the one of the ways to create a singleton class:


class Singleton
{
private:
Singleton(); //constructor is private
//inner class
static class SingletonHolder()
{
private:
static Singleton instance = new Singleton();
//static variable initialised with instance of outer class

};
public:
static Singleton getInstance() //static method which can be called directly to get instance
{
return SingletonHolder.instance(); //get the static variable of inner class
}
};

Here is perhaps the simplest way to create a singleton:

class Singleton
{
private:
Singleton(); //constructor is private
static Singleton test = new Singleton();
public:
static Singleton getInstance() //static method which can be called directly to get instance
{
if(test == NULL)
return new Singleton();
else
return test;
}
};


Documentum Concepts

DFC code for Logging In:
IDfLoginInfo logininfo = new DfLoginInfo();
logininfo.setUserName("pravar");
logininfo.setPassword("pravar");

IDfClient client = DfClient.getLocalClient();
IDfSession session = client.newSession("myDocBase",logininfo);

Creating a new document:
IDfDocument doc = (IDfDocument) session.newObject("dm_document");

Executing a DQL query using DFC:
StringBuffer sb = new StringBuffer();
sb.append("Select * from dm_document where object_name='hello'");
IDfQuery query = new DfQuery();
query.setDQL(sb.toString());
IDfCollection coll = query.execute();
while(coll.next)
{
...
}
coll.close();

Data Dictionary: Data Dictionary is a the information that server stores in repository about the object types and attributes. This data dictionary can be used by the client applications.

Rendition: A rendition is a representation of a document that differs from the original document only in its format or some aspect of the format.

Components of a Workflow:

DCTM FAQs continued...

Here are the answers to the FAQs (of previous post) on the top of head:

1. What is Documentum all about?
A: Documentum is a Content Management System and has a product suite which caters to different needs of storing and managing content of all types.

2. What do you know about Documentum?
A: I have been working on the Docuementum development for last 2.5 yrs and I have worked on Documentum Desktop Client and DFC (interacted with Documentum Server).

3. What are all the products you have worked?
A: Documentum Server, Documentum Desktop, Webtop, DA, DFC.

4. What are your roles & responsibilities?
A: Fixing bugs and delivering patches to DTC customers. Interacting with DCTM developers and offshore teams. DTC release.

5. How will you do customization using WDK?
A: ??

6. How will you customize a page that shows only my custom type?
A: ??

7. How will you differentiate repeating fields and single value fields
A: Repeating fields have multiple values and single fields have only one value

8. What is workflow?
A: A Workflow formalizes the business process. Any business process such as job approval, engineering development or insurance claims can be modeled into a workflow.

9. What is BOF framework?
A: BOF (Business Objects Framework) is a functionality which allows dctm developers to customize DFC programmatically.

10. What is the object type for workflow?
A: dm_workflow

11. What is the WDK architecture?
A:??
12. what about security in Documentum
A: Security in documentum is enforced by permission levels, ACLs and groups/roles
13. what is the diff between super user and administrator
A: A superuser is a user with higher permission levels than other users. An administrator also have high level of permissions but he will be able to do the administrative tasks such as configuring the docbase, scheduling the jobs, managing the sessions etc.
14. what are all the permissions related to document objects
A: The basic permissions
1. NONE
2. BROWSE
3. READ
4. RELATE
5. VERSION
6. WRITE
7. DELETE
Extended permissions:
1. Change Ownership, Change location, change permission, delete object, execute procedure.

15. what do u mean extended permissions
A:Extended permissions are the permissions stated above and they are not heirarchical.

16. What is dfc & dmcl, differenctiate both.
A: DFC is DCTM foundation class framework which is a set of Java classes to interact with DCTM server. DMCL is the inherent language understood by the server.

Questions from CTS
1. Explain WDK architecture.
A:??
2. Differences between iAPI and DQL
A: iAPI is a set of commands that are given to the server. DQL is the DCTM query language to query the docbase like a database.
3. Under what scenarios will you use iAPI
A: iAPI is used to create objects, check-in and checkout, DQL cannot be used for that purpose.
iAPI is basically used when no other client is available with server
iAPI is also used to cross check the operations performed by the user code.
4. What is a Permission Template?
A: A Permisssion template is an ACL which assigns a set of permissions to a set of users.
5. How do you configure publishing to various locale web sites?
A: ??
6. How will you customize check-in component so that it shows a specific custom attribute while checking in.
A: ??
7. How will you implement the following scenario?
• There is an English site to which we also need a German site. The translation is done by a third party. He sends the file to a person of the organization and they look at it and approve the page before it comes on the German site.

A:??
8. What is docapp and Documentum Application Installer?
A: A docapp is a documentum application which can be installed by documetum app installer. A DOcapp can contain a set of custom objects, attributes, lifecycles and customized forms that can manipulate the docbase.
9. Have you customized DFC?
A: No, but I know that it can be done by the BOF. SBOs or TBOs can be written which are actually a java code which override DFC method to customize their functionality.
10. How do you install a WDK for customizing?
A: ??
11. Do you interact with Documentum clients?
A: Yes
21. What are SBO and TBO?
A: SBO (Service based object) and TBO (Type Based Object) are part of BOF (Business Object Framework). TBOs are most commonsly used, they are a set of java classes to customise the actions on a custom type. For example, a TBO can validate a custom attribute to see if it is unique before a check in is done on the object.An SBO on the other hand is a global BO which is can do a custom general action not specific to any object type.
An example of SBO would be an object which checks for the uniqueness of any attribute of a type.

Documentum FAQs

Got these set of questions from a friend:

DCTM FAQs

1. What is Documentum all about?
2. What do you know about Documentum?
3. What are all the products you have worked?
4. What are your roles& responsibilities?
5. How will you do customization using WDK?
6. How will you customize a page that shows only my custom type?
7. How will you differentiate repeating fields and single value fields
8. What is workflow?
9. What is BOF framework?
10. What is the object type for workflow?
11. What is the WDK architecture?
12. what about security in Documentum
13. what is the diff between super user and administrator
14. what are all the permissions related to document objects
15. what do u mean extended permissions
16. What is dfc& dmcl, differenctiate both.


Questions from CTS
1. Explain WDK architecture.
2. Differences between iAPI and DQL
3. Under what scenarios will you use iAPI
4. What is a Permission Template?
5. How do you configure publishing to various locale web sites?
6. How will you customize check-in component so that it shows a specific custom attribute while checking in.
7. How will you implement the following scenario?
• There is an English site to which we also need a German site. The translation is done by a third party. He sends the file to a person of the organization and they look at it and approve the page before it comes on the German site.
8. What is docapp and Documentum Application Installer?
9. Have you customized DFC?
10. How do you install a WDK for customizing?
11. Do you interact with Documentum clients?

WDK

1. Explain WDK architecture and how it functions on an App Server
2. What are Components?
3. What are Actions?
4. What is a container and why do you need one?
5. What is ACL?
6. What is an alias set and when do you need an alias set?
7. What are the WDK services you are aware of and which are the ones you have used?
8. How do you call a component from an action?
9. Different ways to nest calls between components.
10. Tell me the 2 different ways to create a session from WDK layer
11. You have a component and from that you go to another component and then return to first component. How do you make sure that the state of the first component is maintained properly?
12. How do you create a new DCTM tag?
13. How many Java files are needed to define a DCTM tags and what are they? Name the functions in each of these classes.
14. Difference between Read and Relate permission.
15. What is the default permission of a document created?
16. What is folder security?
17. What is the object type that saves lifecycle information?
18. How do you create new users?
19. What is preference service?
20. What is authentication service and how do you call the same?
21. What are SBO and TBO?

Documentum Websites

Wikid4d.com This is the home of the Documentum 4 Dummies Project. Created to provide foundational knowledge about the Documentum technology platform and associated Documentum products.

dmdeveloper.com/a resource for Documentum developers and system administrators.

Reversing a linked list

Reversing is a singly linked list is very interesting piece of code and I think it is one of the important datastructure questions asked in interviews. I saw this very interesting discussion here
and this peice of code looks good to me:

Node *Reverse (Node *p)
{
Node *pr = NULL;
while (p != NULL)
{
Node *tmp = p->next;
p->next = pr;
pr = p;
p = tmp;
}
return pr;
}

The logic is to reverse the pointers. There is also a recursive solution to this problem but i guess the above solution is the best bet. If its a doubly linked list, swapping the next and prev pointers and changing the tail as head would be the solution.

CPP Datastructure Questions

I got this document from one of my collegue, it has interesting and very complex (interview) questions on datastructures. I'm pasting the document here as it is:

Q1: How would you find a cycle in a linked list? Try to do it in O(n) time. Try it using constant amount of memory.

A1: p2 is guaranteed to reach the end of the list before p1 and every link will be tested by the while condition so no chance of access violation. Also, incrementing p2 by 2 and p1 by 1 is the fastest way of finding the cycle. In general if p1 is incremented by 'n' and p2 by 'm', ('n' not == 'm'), then if we number the nodes in the cycle from 0 to k-1 (k is the number of nodes in the cycle), then p1 will take values given by i*n (mod k) and p2 will take values i*m (mod k). These will collide every n*m iterations. Clearly, n*m is smallest for n==1 and m==2.


bool
HasCycle(Node *pHeadNode)
{
Node
*p1, *p2;
p1 =
p2 = pHeadNode;
while (p2 && p2->Next) {
p1 = p1->Next;
p2 = p2->Next->Next;
if(p1 == p2)
return true;
}
return false;
}




Q2: Given a history of URLs, how would you determine if a particular URL had been seen before?

A2: Hash Table is the most efficient way to do this. You can use several hashing algorithms. For example, checksum of a link can be used as a key for hashing. This will ensure o(1) order provided good checksum algorithm is used which is always unique. Whenever page loads we can parse all URL's from the page and take their checksum and compare them w/ the hashtable. Whichever links matches are displayed in some different color.

Hashtable is the correct answer, but a constant order algo. sounds too fantastic. URLs are by themselves unique and so hash function should not add to the redundancy by being unique. O/w it becomes nothing but a linear sort of search, while binary can do better.

Though URLs are not inherently alphabetically ordered, one might think of ordering them that way, or making the hash function that utilizes this. This will entail a combined binary + linear search which sounds optimal and is open to complexity calculations. A good data structure can be a hash table pointing to a binary tree (an array pointing to a binary tree).

Q3: Since pages can have multiple URLs pointing to them, how can you make sure you've never seen the same CONTENT before?

A3: Keep a list (or a binary tree) of hashes (using MD5, SHA1 or similar hash/digest algorithm) of pages you've visited. Then just compare digest of current page to the hashes in the tree.

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

A4: Use prim's algorithm; Kruskal's algorithm is faster than Prim's. For checking for an already seen url, use dictionary search tree. It is the most efficient i.e. O(1) for whatever number of urls you have in the database.

Q5: The Web can be modeled as a directed graph. Come up with a graph traversal algorithm. Make the algorithm non-recursive and breadth-first.

Q6: Write a function to print the Fibonacci numbers


int fib (int n)
{
assert(n>=1);
return (n<=2 ? 1: (fib(n-1) + fib(n-2)));
}
 
 
int fibonacci (int n)
{
if (n <= 2) return 1; 
int current, one_back 1, two_back = 1;
for(int i = 3; i <= n; i++) {
current = one_back + two_back;
one_back = two_back;
two_back = current;
} /*the end of for loop */
return current;
}
 




Q7: Write a function to print all of the permutations of a string.


map<string,int> map_StrInt;
void PermuteString(char* str, int n)
{
char ch = str[n-1];
for(int i = 0; i < n; i++) 
{
swap(str[i], str[n-1]);
PermuteString(str, n-1);
swap(str[i], str[n-1]);
}
 
if(n == 1) map_StrInt[string(str)]++;
}




Q8: Design a memory management scheme.

Q9: Give a one-line C expression to test whether a number is a power of 2. Now implement it without using loops.

A9:


x = ((x > 0) & !(x & x - 1));





Q10: How can I swap two integers in a single line statement?

A10: Use xor operator to accomplish this: a ^= b ^= a ^= b;

Q11: Implement an algorithm to sort a linked list.

A11: The merge sort algorithm:


#include <cassert>
typedef struct MNode *PNODE;
struct MNode
{
int Key;
struct MNode *Next;
};
 
 
PNODE Merge(PNODE p, PNODE q)
{
assert(p);
assert(q);
PNODE pHead;
if(p->Key < q->Key)
{
pHead = p, p = p->Next;
}
else
{
pHead = q, q = q->Next;
}
PNODE r = pHead;
while (p && q)
{
if(p->Key < q->Key)
{
r->Next = p, r = r->Next, p = p->Next;
}
else
{
r->Next = q, r = r->Next, q = q->Next;
}
}
if(!p) r->Next = q;
if(!q) r->Next = p;
return pHead;
}
 
 
PNODE Partition(PNODE pNode)
{
PNODE p1 = pNode;
PNODE p2 = pNode->Next->Next;
while (p2 && p2->Next)
{
p2 = p2->Next->Next;
p1 = p1->Next;
}
PNODE pSav = p1->Next;
p1->Next = NULL;
return pSav;
}
 
PNODE Merge_Sort(PNODE p)
{
if(!p || !p->Next) return p;
PNODE q = Partition(p);
p = Merge_Sort(p);
q = Merge_Sort(q);
p = Merge(p, q);
return p;
}
 
 





Q12:Implement strstr(), strcat(), strtok(), strrchr, and strcmp



char* strstr (const char *str1, const char *str2)
{
char *cp = (char *)str1;
char *endp = cp + (strlen(cp) - strlen(str2));
while (*cp & (cp <= endp))
{
char *s1 = cp;
char *s2 = (char *)str2;
while ( *s1 & *s2 && (*s1 == *s2) )
    s1++, s2++;
if (!(*s2)) return(cp); // success!
cp++; // bump pointer to next char
}
return(NULL);
}
 
 
 
 
char *strcat (char * dst, const char * src)
{
char *cp = dst;
while (*cp) cp++; // find end of dst
while (*cp++ = *src++); // Copy src to end of dst
return (dst); // return dst
}
 
 
char *strcpy (char * dst, const char * src)
{
char* cp = dst;
while (*cp++ = *src++); // Copy src over dst
return(dst);
}
 
 
char *strtok (char *string, const char *control)
{
char *str;
const char *ctrl = control;
char map[32];
int count;
static char *nextoken;
/* Clear control map */
for(count = 0; count < 32; count++)
map[count] = 0;
//Set bits in delimiter table
do{
map[*ctrl >> 3] |= (1 << (*ctrl & 7));
}
while (*ctrl++);
//Initialize str. If string is NULL, set str to the saved pointer
//(i.e., continue breaking tokens out of the string from the last strtok call)
if(string)
str= string;
else
 
str = nextoken;
//Find beginning of token (skip over leading delimiters). Note that there is
//no token iff this loop sets str to point to the terminal null (*str =='\0')
while (*str && (map[*str >> 3] & (1 << (*str & 7))))
str++;
string = str;
//Find the end of the token. If it is not the end of the string, put a null there.
for( ; *str ; str++)
if(map[*str >> 3] & (1 << (*str & 7)))
{
*str++ = '\0';
break;
}
//Update nextoken
nextoken = str;
//Determine if a token has been found.
if(string == str)
return NULL;
else
return string;
}
 
int strcmp(const char *src, const char* dst)
{
int ret = 0;
while (!(ret = (*src - *dst)) & *dst);
++src, ++dst;
if (ret < 0)
ret = -1;
else
ret = 1;
return ret;
}
 
 
char *strrev (char *string)
{
char *start = (char *)string;
char *left = (char *)string;
while (*string++); // find end of string
string -= 2;
while (left < string)
{
char ch = *left;
*left++ = *string;
*string-- = ch;
}
return start;
}
 
 
char* strrchr (const char *string, int ch)
{
char *start = (char *)string;
while (*string--); // find end of string
 
// search forward front
while (--string != start && *string != (char)ch); 
 
if(*string == (char)ch) // char found ?
return (char *)string;
 
else
 
return (NULL);
}
 
 
 
 
 
 



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



void Insert(PNODE &pHead, PNODE pThing)
{
if(pHead == 0)
   pHead = pThing;
else
{
bool fComesFirst = true;
PNODE pCurrent = pHead;
PNODE pPrevious;
while (pCurrent)
{
if (pThing->Key < pCurrent->Key)
break;
pPrevious = pCurrent;
pCurrent = pCurrent->Next;
fComesFirst = false;
}
if(fComesFirst)
  pHead = pThing;
else
  pPrevious->Next = pThing;
pThing->Next = pCurrent;
}
}





Q14: Give me an algorithm and C code to find the subarray with the largest sum given an array containing both positive and negative integers.

/* Give me an algorithm and C code to find the subarray with the largest sum given an array containing both positive and negative integers.

For each position i in the array we can find out the sub array ending exactly at that position and having the largest sum. At the beginning for the first element the only possible sub array it that one containing the first element so initially the largest amount is a[1]. (For algorithm sake let assume that the array is 1-indexed). Following the principle of dynamic programming it will be proved that the best sub array( with the largest sum) ending in position i+1 is somehow related to best sub array ending in position i.

Let be k the starting index of the best sub array ending in position i and S the sum of this sub array. Let be t an index strictly less than k. The sum from the index t to i+1 is T + S + a[i+1] where T is the sum of elements from t to k-1 indexes. Because of the properties of index k T+S <= S otherwise k will not point to best sub array ending in i so each sub array starting in t


Similarly , let choose an index t between k+1 and i. The sum from index t to i+1 is T+a[i+1], where is the sum of elements between t and i positions. Again T < S according to the optimality of k index so the best sub array ending in i+1 is that one starting from k and that has S+a[i+1] as sum of array elements. But there is one more situation to analyse. If S is less then zero is obvious that S+a[i+1] < a[i+1] so in this case the best sub array ending in i+1 position is exactly the sub array containing only that element. In fact this situation direct you to start a new sub array that will be candidate for the best sub array of the entire array.

In conclusion the information to be kept while going through the array only once (O(n)) is the best sub array ending in the current position and best sub array found for the entire array until the current step.(if it necessary also the starting and ending position for these sub array can be kept). After the processing of the last element the algorithm will have determined the sub array having the largest sum.

Note: The algorithm works fine even there is no negative number in the array and it will produce of course as the largest sum the sum of all array elements.

Algorithm: arr is the array of n integer; the function will return the largest sum and the limits of the sub array producing that value */



#include <iostream>
using namespace std;
int GetLargestSubArray(int* arr, int n, int &iBeginRet, int
&iEndRet)
{
int iBeginSaved=0, iEndSaved=0; // the start/end positions of the saved sub array
int iBegin, iEnd; // the start/end positions of the current sub array
int nSumSaved=0, nSum=0; // the sums of whole saved largest and current sub arrays
int i = 0; // index to loop in the array
if(0 == n) // Nothing to analyze, return invalid array indexes
{
iEndRet = iBeginRet = -1;
return 0;
}
nSumSaved = nSum = arr[i];
for(i = 2; i < n; i++)
{
/*Compute the current largest sum */
if(nSum<0)
{
nSum = arr[i];
iBegin = iEnd = i;
}
else
{
nSum += arr[i];
iEnd= i;
}
if(nSum > nSumSaved)
{
nSumSaved = nSum;
iBeginSaved = iBegin;
iEndSaved = iEnd;
}
}
iBeginRet = iBeginSaved;
iEndRet = iEndSaved;
return nSumSaved;
}





Q15: Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it.

A15: I'll try to do it in O(N) w/o using any additional memory. The key is to use content of the array as index into array, checking in O(1) if that number has been seen already.



bool HasDups(int * a, int N)
{
bool fHasDup = false;
for(int i = 0; i < N; i++) {
int index = a[i] % N;
if(a[index] > N) {
fHasDup = true;
break;
}
a[index] += N;
}
//restore the array
for(int j = 0; j < i; j++)
if(a[j] > N) a[j] %= N;
return fHasDup;
}
 




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

Q17: Implement an algorithm to reverse a singly linked list. (with and without
recursion)


Node*RevSList(Node *pCur, Node *pRev) {
if(!pCur) return pRev;
Node*pNext = pCur->Next;
pCur->Next = pRev;
pRev= pCur;
return (RevSList(pNext, pRev));
}
Node* RevSList(Node *pCur) {
Node*pRev = NULL;
while (pCur)
{
Node*pNext = pCur->Next;
pCur->Next = pRev;
pRev= pCur;
pCur= pNext;
}
return pRev;
}
 



Q18:Implement an algorithm to reverse a doubly linked list.


Node *RevDList(Node *pCur)
{
if(!pCur) return pCur;
pSav= pCur->Next;
pCur->Next = pCur->Prev;
pCur->Prev = pSav;
if(!pSav) return pCur;
return RevDList(pSav);
}
Node*RevDList(Node *pCur)
{
while (pCur)
{
Node*pSav = pCur->Next;
pCur->Next = pCur->Prev;
pCur->Prev = pSav;
if(!pSav) return pCur;
pCur= pSav; 
}
return pCur;
}





Q19: Delete an element from a doubly linked list.



Node* DelDLLNode(Node *pNode)
{
if(!pNode) return pNode;
if(pNode->Next) pNode->Prev->Next =pNode->Next;
 
 
if(pNode->Prev) pNode->Next->Prev =pNode->Prev;
 
 
return pNode; // delete it if it's heap-based.
}
 




Q20: Implement an algorithm to sort an array.

Q21: Given a sequence of characters, how will you convert the lower case characters to upper case characters?

Q22: Count the number of set bits in a number without using a loop.



#define reverse(x) \
(x=x>>16 | (0x0000ffff&x)<<16, \
x=(0xff00ff00&x)>>8|(0x00ff00ff&x)<<8,\
x=(0xf0f0f0f0&x)>>4|(0x0f0f0f0f&x)<<4,\
x=(0xcccccccc&x)>>2|(0x33333333&x)<<2,\
x=(0xaaaaaaaa&x)>>1|(0x55555555&x)<<1)
 
#define count_ones(x) \
(x=((0xaaaaaaaa&x)>>1)+(0x55555555&x), \
x=((0xcccccccc&x)>>2)+(0x33333333&x), \
x=((0xf0f0f0f0&x)>>4)+(0x0f0f0f0f&x), \
x=((0xff00ff00&x)>>8)+(0x00ff00ff&x), \
x=(x>>16) + (0x0000ffff&x))



Q23: Give mean 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.



for(Src = 0; Src < N; Src++)
{
Dest= rand() % N; // All N positions equally likely
Swap(X[Src], X[Dest]);
}



At first glance, it would appear that this algorithm generates all permutations with equal probability. On examination, though, one can see that this will generate NN arrangements of elements---each of the N iterations of the loop positions a value among the N available positions. It is known, though, that there are only N! possible permutations of N elements: for each permutation there are multiple ways to generate that permutation---on average, NN/N! ways.



for(Src = 0; Src < N; Src++)
{
Dest= rand() % N; // All N positions equally likely
Swap(X[Src], X[Dest]);
}



Examination of the structureof this loop shows that it will generate N! arrangements of elements. All permutations are equally likely, aside from the very minor deviation from uniform distribution by selecting a random value between 0 and Dest as (rand()
% (Dest+1)).

Q24: How would you print out the data in a binary tree, level by level,
starting at the top?

Q25: Do a breadth first traversal of a tree.



typedef int VertexType;
typedef class Vertex *LPVertex;
class Vertex
{
int index;
int weight;
LPVertex next;
public:
int GetIndex();
bool Visited();
Vertex &Visit();
Vertex &Mark();
Vertex *GetNext();
};
 
 
enum { kMaxVertices = 7 };
typedef LPVertex HeaderArray[kMaxVertices];
HeaderArray adjacencyList;
 
 
void BreathFirstSearch (HeaderArray adjacencyList, LPVertex pv)
{
queue Q;
pv->Visit().Mark();
Q.push(pv);
while (!Q.empty())
{
pv = Q.front(); Q.pop();
pv =adjacencyList[pv->GetIndex()];
for(; pv; pv = pv->GetNext())
if(!pv->Visited())
{
pv->Visit().Mark();
Q.push (pv);
}
}
}
 
 
void DepthFirstSearch (HeaderArray adjacencyList, LPVertex pv)
{
stack S;
pv->Visit().Mark();
S.push(pv);
while (!S.empty())
{
pv =S.top();
pv =adjacencyList[pv->GetIndex()];
for(; pv; pv = pv->GetNext())
if(!pv->Visited())
{
pv->Visit().Mark();
S.push(pv);
}
S.pop();
}
}
 




Q26: Write a routine to draw a circle given a center coordiante (x,y) and a radius (r) without making use of any floating point computations.



Q27: Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words in it.


char
*ReverseWords (char *string)
{
char*start = strrev(string);
char*left;
char*right;
char ch;
while (*string)
{
while (*string == ' ' & *string)
string++;
left= string;
while (*string != ' ' & *string)
string++;
right = string-1;
while (left < right)
{
ch =*left;
*left++ = *right;
*right-- = ch;
}
}
return start;
}




Q28: Implement a TIC-TAC-TOE game assuming Computer as one of the player. Optimize it for fast computer play time and space. Do some analysis on memory and processing requirements.

Q29: Write a function to find the depth of a binary tree.


long findDepth(Node *pNode)
{
if(!pNode) return 0; 
long depthLeft = findDepth(pNode->Left);
long depthRight = findDepth(pNode->Right);
return (depthLeft>depthRight ? ++depthLeft:
++depthRight);
}



Q30: You aregiven two strings: S1 and S2. Delete from S2 all those characters which occur in S1 also and create a clean S2 with the relevant characters deleted.


char *strtokrem (char *string, const char *control)
{
char*start = string;
char*str = string;
const char *ctrl = control;
char map[32];
int count;
/*Clear control map */
for(count = 0; count < 32; count++)
map[count] = 0;
//Set bits in delimiter table
do
{
map[*ctrl >> 3] |= (1 << (*ctrl & 7));
}
while (*ctrl++);
//Remove each token whenever it matches
while (*str)
if(map[*str >> 3] & (1 << (*str & 7)))
{
for(char *pch = str; *pch; pch++)
*pch= *(pch+1);
}
else
str++;
return start;
}
 
 
 




Q31: Write a small lexical analyzer for expressions like "a*b" etc.



bool is_astarb(char* string)
{
//expressions: b, ab, aab, aaab, ...
bool bRet = false;
while (*string == 'a')
++string;
 
if(*string == 'b')
bRet= (*++string == '\0');
return bRet;
}
 
 



Q32: Given an array t[100] which contains numbers between 1 and 99. Return the duplicated value. Try both O(n) and O(n-square).

Q33: Write efficient code for extracting unique elements from a sorted list of
array.


void PrintUniqueElements(int rgNumb[], int cNumb)
{
assert(cNumb>0);
int iSav;
cout << (iSav = rgNumb[0]) << "\t";
for (int i = 1; i < cNumb; i++)
if (iSav != rgNumb[i])
cout<< (iSav = rgNumb[i]) << "\t";
}





Q34: 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).

Q35: Print an integer using only putchar. Try doing it without using extra
storage.


void putDigits(int val)
{
if(val < 0) { cout << "-"; val = -val; }
stack<int> S;
S.push(val);
while (!S.empty())
{
val= S.top(); S.pop();
if(val >= 10)
{
S.push(val%10);
S.push(val/10);
}
else
cout.put(val+'0');
}
}





Q36: Write a function that allocates memory for a two-dimensional array of given size(parameter x & y).

Q37: Write source code for printHex(int i) in C/C++


void putHex(int val)
{
if(val < 0) {
printf("-");
val= -val;
}
if(val >= 0 & val < 16) {
printf("%c", val > 9 ? (val-10)+'A' :val+'0');
return;
}
putHex(val/16);
printf("%c", val%16 > 9 ? (val%16-10)+'A' :val%16+'0');
}





Q38: What sort of technique you would use to update a set of files over a network, where a server contains the master copy.

Q39: How do you handle deadlock on a table that is fed with a live serial feed?

Q40: Do the class/structure description for a Hash table, and write the source
code for the insert function.

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

Q42: What would you suspect if users report they are seeing someone else'sdata on their customized pages?

A42: Overflow; If we're talking about ASP, JSP, CFML that sort of thing, I would suspect unsynchronized access to session data in a multi-threaded Servlet, JavaBean or COM object -- i.e., a non-threadsafe bug in the server application.

Q43: How would you do conditional compilation?

A43: The #if directive, with the #elif, #else, and #endif directives, controls compilation of portions of a source file. If the expression you write (after the #if) has a nonzero value, the line group immediately following the #if
directive is retained in the translation unit. Plus, #ifdef and #ifndef identifier.

Q44: Write an algorithm to draw a 3D pie chart?

Q45: Prove that Dijkstra's MST algorithm indeed finds the overall MST.

A45: The two common MST algorithms are by Kruskal and Prim. Djikstra gave us
an algorithm for shortest path, not MST.

Q46: How would you implement a queue from a
stack?


stack stk1, stk2;
void push(element e)
{
push.stk1(e);
}
element pop()
{
if(stk2.empty())
while(!stk1.empty())
stk2.push(stk1.pop());
return stk2.pop();
}




Q47: Write a funtion that finds repeating characters in a string.

Q48: Write a routine to reverse a series of numbers without using an array.


int iReverse (int iNum)
{
int iRev =0;
while(iNum !=0)
{
iRev = iRev * 10 + iNum % 10;
iNum /= 10;
}
return iRev;
}





Q49: Write a function to find the nth item from the end of a linked list in a single pass.

A49: I would think keeping a gap of "n" between fptr and sptr would do. Then, advance both together till fptr->next (fptr is the one in front) = NULL.

Aren't you traversing the list twice - once with fptr and the second time with sptr. I think you should maintain an queue of pointers. Keep pushing a pointer into the queue and whenever the size of the queue becomes greater than n, remove a pointer at the head of the queue. When you reach the end of the list. The element at the head of the queue gives a pointer to the nth element from the end.



#include <queue>
PNODE GetNthLastElement (PNODE pCur, unsigned nOffset)
{
queue<PNODE> Q;
for(; pCur && Q.size() < nOffset; Q.push(pCur), pCur = pCur->Next);
if (Q.size() < nOffset) return NULL;
while (pCur){
Q.pop();
Q.push(pCur);
pCur= pCur->Next;
}
return (Q.front());
}





Q50: 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).

Q51: Write a random number generator in a specified range.


#include <algorithm>
int random_range(int lowest_number, int highest_number)
{
if(lowest_number > highest_number)
{
swap(lowest_number,highest_number);
}
int range = highest_number - lowest_number + 1;
return lowest_number + int(range * rand()/(RAND_MAX + 1.0));
}





Q52: Delete a node from a single linked list.


#include <algorithm>
int random_range(int lowest_number, int highest_number)
{
if(lowest_number > highest_number)
{
swap(lowest_number,highest_number);
}
int range = highest_number - lowest_number + 1;
return lowest_number + int(range * rand()/(RAND_MAX + 1.0));
}





Q53: Say you have three integers between 0 - 9. You have the equation: A! + B! + C! = ABC (where ABS is a three digit numbers, not A * B * C). Find A, B, and C that satisfies this equation.


1! + 4! + 5! = 145





Q54: Give 2 nodes in a tree, how do you find the common root of the nodes?

Q99: Write a small lexical analyzer for expressions like a(b|c)d*e+.


enum State {
s0 =0, s1, s2, s3, // states
m0 = 0, m1, m2, m3, acc, err // actions: matches, accept or error
};
 
 
State DecisionTable[4][6] = {
// a b c d e other // input
m1,err,err,err,err,err, // s0
err,m2, m2,err,err,err, // s1
err,err,err, m2, m3,err, // s2
acc,acc,acc,acc, m3,acc // s3
};
 
 
State IsAcceptable (char *&theIStream)
{
State stateCur = s0, State theDecision = err;
do
{
char theChar = *theIStream++;
int theInput = (theChar - 'a') % 6;
theDecision = DecisionTable[stateCur][theInput];
switch (theDecision)
{
default:
stateCur = theDecision;
break;
case err:
case acc: 
; //do nothing
}
}
while (theDecision != err & theDecision != acc);
return theDecision;
}