Social Icons

Thursday, February 16, 2012

Data Structures Questions and Answers for Technical Interviews Part-1

Q: What are the major data structures used in the following areas : RDBMS, Network data model and Hierarchical data model.
  1. RDBMS = Array (i.e. Array of structures)
  2. Network data model = Graph
  3. Hierarchical data model = Trees

Q: What are the major data structures used in the following areas : RDBMS, Network data model and Hierarchical data model.
  1. RDBMS = Array (i.e. Array of structures)
  2. Network data model = Graph
  3. Hierarchical data model = Trees

Question: What is almost complete binary tree?.
Answer:An almost complete binary tree is a tree in which each nodethat has a right child also has a left child. Having a left child does not require a node to have a right child. Stated alternately, an almost complete binary tree is a tree where for a right child, there is always a left child, but for a left child there may not be a right child.The number of nodes in a binary tree can be found using this formula: n = 2^h Where n is the amount of nodes in the tree, and h is the height of the tree.

Given two numbers m and n, write a method to return the first number r that is
divisible by both (e.g., the least common multiple).

The Approach:

What does it mean for r to be divisible by m and n? It means that all the primes in m must go into r, and all primes in n must be in r. What if m and n have primes in common?

For example, if m is divisible by 3^5 and n is divisible by 3^7, what does this mean about r? It means r must be divisible by 3^7.

The Rule: For each prime p such that p^a \ m (e.g., m is divisible by p^a) and p^b \ n, r must be divisible by p^max(a, b)

The Algorithm:
Define q to be 1.
for each prime number p less than m and n:
find the largest a and b such that p^a \ m and p^b \ n
let q = q * p^max(a, b)
return q

Q How would you check if a binary tree is balanced?

A tree is considered balanced when the difference between the min depth and max depth does not exceed 1.
Recursive algorithms always work well on trees, so here’s some code.
int min_depth( Node * root ) {

    if( !root ) {

        return 0;


    return 1 + min( min_depth( root->left ),

                    min_depth( root->right ));


int max_depth( Node * root ) {

    if( !root ) {

        return 0;


    return 1 + max( max_depth( root->left ),

                            max_depth( root->right ));


bool is_balanced( Node * root ) {

    return ( max_depth( root ) - min_depth( root ) ) <= 1


Q: Write a C program to delete a tree (i.e, free up its nodes)

clear(struct node* pNode)
if (pNode != NULL)
delete pNode;

Q Write a C program to determine the number of elements (or size) in a tree.


int tree_size(struct node* node)  {
  if (node==NULL)
    return(tree_size(node->left) + tree_size(node->right) + 1);
  }  }

Q Write a C program to find the depth or height of a tree.

tree_height(mynode *p) {
   return(max(h1,h2)+1); }

The degree of the leaf is zero. The degree of a tree is the max of its element degrees. A binary tree of height n, h > 0, has at least h and at most (2^h -1) elements in it. The height of a binary tree that contains n, n>0, elements is at most n and atleast log(n+1) to the base 2.

Log(n+1) to the base 2 = h

n = (2^h - 1)

Q How to create a copy of a linked list? Write a C program to create a copy of a linked list.
copy_linked_lists(struct node *q, struct node **s) {
        *s=malloc(sizeof(struct node));
        copy_linked_list(q->link, &((*s)->link));
    } }

Q How to compare two linked lists? Write a C program to compare two linked lists.
int compare_linked_lists(struct node *q, struct node *r) {
    static int flag;
    if((q==NULL ) && (r==NULL))
        if(q==NULL || r==NULL)
    return(flag); }
Q If you are using C language to implement the heterogeneous linked list, what pointer type will you use?

The heterogeneous linked list contains different data types in its nodes and we need a link, pointer, to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type.

Q How would you detect a loop in a linked list? Write a C program to detect a loop in a linked list.
typedef struct node
void *data;
struct node *next;

mynode * find_loop(NODE * head)
mynode *current = head;
while(current->next != NULL)
mynode *temp = head;
while(temp->next != NULL && temp != current)
if(current->next == temp)
printf("\nFound a loop.");
return current;
temp = temp->next;
current = current->next;
return NULL;
Q How do you find the middle of a linked list? Write a C program to return the middle of a linked list
typedef struct node
int value;
struct node *next;
struct node *prev;

void add_node(struct node **head, int value);
void print_list(char *listName, struct node *head);
void getTheMiddle(mynode *head);

int main()
mynode *head;
head = (struct node *)NULL;
add_node(&head, 1);
add_node(&head, 10);
add_node(&head, 5);
add_node(&head, 70);
add_node(&head, 9);
add_node(&head, -99);
add_node(&head, 0);
add_node(&head, 555);
add_node(&head, 55);
print_list("myList", head);

void getTheMiddle(mynode *head)
mynode *p = head;
mynode *q = head;
while((q->next)!=NULL && (q->next->next)!=NULL)
p=(p!=(mynode *)NULL?p->next:(mynode *)NULL);
q=(q!=(mynode *)NULL?q->next:(mynode *)NULL);
q=(q!=(mynode *)NULL?q->next:(mynode *)NULL);
printf("The middle element is [%d]",p->value);

void add_node(struct node **head, int value)
mynode *temp, *cur;
temp = (mynode *)malloc(sizeof(mynode));
if(*head == NULL)

void print_list(char *listName, struct node *head)


mynode *temp;

printf("\n[%s] -> ", listName);



Q . How do you reverse a linked list without using any C pointers?
 One way is to reverse the data in the nodes without changing the pointers themselves. One can also create a new linked list which is the reverse of the original linked list. A simple C program can do that for you. Please note that you would still use the "next" pointer fields to traverse through the linked list (So in effect, you are using the pointers, but you are not changing them when reversing the linked list).

Q: How to declare a structure of a linked list?
   struct node
int value;
struct node *next;
 }; typedef struct node *mynode;

What is SQL GROUP BY Clause

The SQL GROUP BY Clause is used along with the group functions to retrieve data grouped according to one or more columns.
For Example: If you want to know the total amount of salary spent on each department, the query would be:
SELECT dept, SUM (salary)
FROM employee
GROUP BY dept;

The output would be like:
dept salary
---------------- --------------
Electrical 25000
Electronics 55000
Aeronautics 35000
InfoTech 30000
NOTE: The group by clause should contain all the columns in the select list expect those used along with the group functions.
SELECT location, dept, SUM (salary)
FROM employee
GROUP BY location, dept;

The output would be like:
location dept salary
------------- --------------- -----------
Bangalore Electrical 25000
Bangalore Electronics 55000
Mysore Aeronautics 35000
Mangalore InfoTech 30000

What is SQL Having Clause?

Having clause is used to filter data based on the group functions. This is similar to WHERE condition but is used with group functions. Group functions cannot be used in WHERE Clause but can be used in HAVING clause.
For Example: If you want to select the department that has total salary paid for its employees more than 25000, the sql query would be like;
SELECT dept, SUM (salary)
FROM employee
HAVING SUM (salary) > 25000

The output would be like:
dept salary
------------- -------------
Electronics 55000
Aeronautics 35000
InfoTech 30000
When WHERE, GROUP BY and HAVING clauses are used together in a SELECT statement, the WHERE clause is processed first, then the rows that are returned after the WHERE clause is executed are grouped based on the GROUP BY clause. Finally, any conditions on the group functions in the HAVING clause are applied to the grouped rows before the final output is displayed.

What is an Index in SQL?

SQL Index

An index is a physical structure containing pointers to the data. Indices are created in an existing table to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes; they are just used to speed up queries. Effective indexes are one of the best ways to improve performance in a database application. A table scan happens when there is no index available to help a query. In a table scan, the SQL Server examines every row in the table to satisfy the query results. Table scans are sometimes unavoidable, but on large tables, scans have a terrific impact on performance. 

Index in sql is created on existing tables to retrieve the rows quickly.
When there are thousands of records in a table, retrieving information will take a long time. Therefore indexes are created on columns which are accessed frequently, so that the information can be retrieved quickly. Indexes can be created on a single column or a group of columns. When a index is created, it first sorts the data and then it assigns a ROWID for each row.
Syntax to create Index:
CREATE INDEX index_name
ON table_name (column_name1,column_name2...);

Syntax to create SQL unique Index:

ON table_name (column_name1,column_name2...);

  • index_name is the name of the INDEX.
  • table_name is the name of the table to which the indexed column belongs.
  • column_name1, column_name2.. is the list of columns which make up the INDEX.
In Oracle there are two types of SQL index namely, implicit and explicit.

Implicit Indexes:

They are created when a column is explicity defined with PRIMARY KEY, UNIQUE KEY Constraint.

Explicit Indexes:

They are created using the "create index.. " syntax.
1) Even though sql indexes are created to access the rows in the table quickly, they slow down DML operations like INSERT, UPDATE, DELETE on the table, because the indexes and tables both are updated along when a DML operation is performed. So use indexes only on columns which are used to search the table frequently.
2) Is is not required to create indexes on table which have less data.
3) In oracle database you can define up to sixteen (16) columns in an INDEX.

Wednesday, February 15, 2012

Handling Text box for only positive Integers No and showing error message in silverlight Using MVVM

Following is the property that can be bind to text box, and handles the text box to enter only integer values, and converting to positive Integer value if any negative Integer value will entered in text box.

private String strPageSize = "";

public String PageSize
 get { return strPageSize; 

     Regex myRange = new Regex(@"^-{0,1}\d+$");
     if (!myRange.IsMatch(value))
       throw new Exception("Numbers are allowed only");
     strPageSize = (Math.Abs(Convert.ToDecimal(value))).ToString();

What is a Trigger?

A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE) occurs. Triggers are stored in and managed by the DBMS. Triggers are used to maintain the referential integrity of data by changing the data in a systematic fashion. A trigger cannot be called or executed; DBMS automatically fires the trigger as a result of a data modification to the associated table. Triggers can be considered to be similar to stored procedures in that both consist of procedural logic that is stored at the database level. Stored procedures, however, are not event-drive and are not attached to a specific table as triggers are. Stored procedures are explicitly executed by invoking a CALL to the procedure while triggers are implicitly executed. In addition, triggers can also execute stored procedures.
Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself; so when the trigger is fired because of data modification, it can also cause another data modification, thereby firing another trigger. A trigger that contains data modification logic within itself is called a nested trigger.

Types of Triggers:
There are two types of Triggers.
1)      DML Trigger
There are two types of DML Triggers
1.Instead of Trigger
Instead of Triggers are fired in place of the triggering action such as an insert, update, or delete.
2. After Trigger
After triggers execute following the triggering action, such as an insert, update, or delete.
2)      DDL Trigger
This type of trigger is fired against Drop Table, Create Table, Alter Table or Login events. DDL Triggers are always After Triggers.

How to alter modification in database by system admin himself?
How to prevent accidents due to fat fingers? (Accidental execution of code)
How to display message to contact another developers when another developer tries to modify object another developer working on?
It was interesting conversation. Answer to all the questions is correct assignment of permissions and (when permissions are not an issue) Server and Database Level DDL Triggers. If developers have their own login to SQL Server and it does not have permissions to drop or create objects this will not be issue at all. However, there are still risk of System Admin himself making accidental mistakes. The solution to this will be use Server and Database Level DDL Triggers.
DDL is abbreviation of Data Definition Level. DDL contains schema of the database object. It was always dream of all DBA, when change in mission critical schema of the database or server is attempted it is prevented immediately informing DBA and users automatically. DDL Trigger can now make this dream true. Definition of DDL Trigger (from BOL) is DDL Triggers are a special kind of trigger that fire in response to Data Definition Language (DDL) statements. They can be used to perform administrative tasks in the database such as auditing and regulating database operations.
DML is abbreviation of Data Manipulation Level. DML contains the actual data which is stored in the database schema. UPDATE, INSERT, DELETE, SELECT are clause are used to manipulate database. There is following different between DML and DDL triggers.
  • DDL triggers do not support INSTEAD OF feature DML triggers.
  • DDL triggers do not have feature of inserted and deleted tables like DML triggers as it does not participate in database manipulations.
Following example demonstrates how DDL trigger can be used to prevent dropping stored procedure.
Step 1 :
First create any sample stored procedure.
USE AdventureWorks;
SELECT 1 test;
Step 2 :
Create DDL trigger which will prevent dropping the stored procedure.
USE AdventureWorks
CREATE TRIGGER PreventDropSP             
ON DATABASE            
PRINT 'Dropping Procedure is not allowed. DDL Trigger is preventing this from happening. To drop 
stored procedure run following script.Script : DISABLE TRIGGER PreventDropSP ON DATABASE; 
Step 3 :
Now test above trigger by attempting to drop the stored procedure.
USE AdventureWorks
This should throw following message along with error code 3609 :
Dropping Procedure is not allowed.
DDL Trigger is preventing this from happening.
To drop stored procedure run following script.
Script :
Msg 3609, Level 16, State 2, Line 1
The transaction ended in the trigger. The batch has been aborted.
Step 4 :
Now DISABLE above trigger and it will let you successfully drop the stored procedure previously attempted to drop. Once it is dropped enable trigger again to prevent future accidents.
USE AdventureWorks
List of all the DDL events (DROP_PROCEDURE in example above) to use with DDL Trigger are listed on MSDN.

What is a Stored Procedure?

A stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. And when the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database.
e.g. sp_helpdb, sp_renamedb, sp_depends etc.

What is Third Normal Form and what is its advantage?

Third Normal Form (3NF) is most preferable normal form in RDBMS. Normalization is the process of designing a data model to efficiently store data in a database. The rules of 3NF are mentioned here

  • Make a separate table for each set of related attributes, and give each table a primary key.
  • If an attribute depends on only part of a multi-valued key, remove it to a separate table
  • If attributes do not contribute to a description of the key, remove them to a separate table.
Normalization is very close to concept of object oriented schema’s and it stores one data at only one place by removing all the redundant data. It also helps to draw the schema easier. Normalization comes at the cost of performance.

Reference : Pinal Dave ( ,

Tuesday, February 14, 2012

General Questions on SQL SERVER

DBMS – Data Base Management System
RDBMS – Relational Data Base Management System or Relational DBMS
A DBMS has to be persistent, that is it should be accessible when the program created the data ceases to exist or even the application that created the data restarted. A DBMS also has to provide some uniform methods independent of a specific application for accessing the information that is stored.
RDBMS adds the additional condition that the system supports a tabular structure for the data, with enforced relationships between the tables. This excludes the databases that don’t support a tabular structure or don’t enforce relationships between tables.
DBMS does not impose any constraints or security with regard to data manipulation it is user or the programmer responsibility to ensure the ACID PROPERTY of the database whereas the RDBMS is more with this regards because RDBMS defines the integrity constraint for the purpose of holding ACID PROPERTY. RDBMS may be or may not be Client Server Database System.
Examples :
DBMS – File System, XML
RDBMS – SQL Server, Oracle
Reference : Pinal Dave (

What are the Properties of the Relational Tables?

Relational tables have the following six properties:
  • Values are atomic.
  • Column values are of the same kind.
  • Each row is unique.
  • The sequence of columns is insignificant.
  • The sequence of rows is insignificant.
  • Each column must have a unique name.

What is Normalization?

Database normalization is a data design and organization process applied to data structures based on rules that help building relational databases. In relational database design, the process of organizing data to minimize redundancy is called normalization. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables. The objective is to isolate data so that additions, deletions, and modifications of a field can be made in just one table and then propagated through the rest of the database via the defined relationships.

What is De-normalization?

De-normalization is the process of attempting to optimize the performance of a database by adding redundant data. It is sometimes necessary because current DBMSs implement the relational model poorly. A true relational DBMS would allow for a fully normalized database at the logical level, while providing physical storage of data that is tuned for high performance. De-normalization is a technique to move from higher to lower normal forms of database modeling in order to speed up database access.

How is ACID property related to Database?

ACID (an acronym for Atomicity Consistency Isolation Durability) is a concept that Database Professionals generally look for while evaluating databases and application architectures. For a reliable database, all this four attributes should be achieved.
Atomicity is an all-or-none proposition.
Consistency guarantees that a transaction never leaves your database in a half-finished state.
Isolation keeps transactions separated from each other until they are finished.

What are the Different Normalization Forms?

1NF: Eliminate Repeating Groups
Make a separate table for each set of related attributes, and give each table a primary key. Each field contains at most one value from its attribute domain.
2NF: Eliminate Redundant Data
If an attribute depends on only part of a multi-valued key, then remove it to a separate table.
3NF: Eliminate Columns Not Dependent On Key
Third Normal Form (3NF) is most preferable normal form in RDBMS. Normalization is the process of designing a data model to efficiently store data in a database. The rules of 3NF are mentioned here
  • Make a separate table for each set of related attributes, and give each table a primary key.
  • If an attribute depends on only part of a multi-valued key, remove it to a separate table
  • If attributes do not contribute to a description of the key, remove them to a separate table.
Normalization is very close to concept of object oriented schema’s and it stores one data at only one place by removing all the redundant data. It also helps to draw the schema easier. Normalization comes at the cost of performance.
BCNF: Boyce-Codd Normal Form
If there are non-trivial dependencies between candidate key attributes, then separate them out into distinct tables.
4NF: Isolate Independent Multiple Relationships
No table may contain two or more 1:n or n:m relationships that are not directly related.
5NF: Isolate Semantically Related Multiple Relationships
There may be practical constrains on information that justify separating logically related many-to-many relationships.
ONF: Optimal Normal Form
A model limited to only simple (elemental) facts, as expressed in Object Role Model notation.
DKNF: Domain-Key Normal Form
A model free from all modification anomalies is said to be in DKNF.
Remember, these normalization guidelines are cumulative. For a database to be in 3NF, it must first fulfill all the criteria of a 2NF and 1NF database.

Reference: Pinal Dave (


Difference between Stored procedure and functions

1) can be used with Select statement
2) Not returning output parameter but returns Table variables
3) You can join UDF
4) Cannot be used to change server configuration
5) Cannot be used with XML FOR clause
6) Cannot have transaction within function

Stored Procedure
1) have to use EXEC or EXECUTE
2) return output parameter
3) can create table but won’t return Table Variables
4) you can not join SP
5) can be used to change server configuration
6) can be used with XML FOR Clause
7) can have transaction within SP

Differences between stored procedures and triggers in databases?

Stored procedures are compiled collection of programs or SQL statements that live in the database. A stored procedure can access and modify data present in many tables. Also a stored procedure is not associated with any particular database object. But triggers are event-driven special procedures which are attached to a specific database object say a table. Stored procedures are not automatically run and they have to be called explicitly by the user. But triggers get executed when the particular event associated with the event gets fired. For example in case of a database having say 200 users and the last modified timestamp need to be updated every time the database is accessed and changed. To ensure this one may have a trigger in the insert or update event. So that whenever any insert or update event of the table gets fired the corresponding trigger gets activated and updates the last modified timestamp column or field with the current time. Thus the main difference between stored procedure and trigger is that in case of stored procedure the program logic is executed on the database server explicitly under eth user’s request but in case of triggers event-driven procedures attached to database object namely table gets fired automatically when the event gets fired.

What are the difference between DDL, DML and DCL commands?


Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples:
  • CREATE - to create objects in the database
  • ALTER - alters the structure of the database
  • DROP - delete objects from the database
  • TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
  • COMMENT - add comments to the data dictionary
  • RENAME - rename an object


Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:
  • SELECT - retrieve data from the a database
  • INSERT - insert data into a table
  • UPDATE - updates existing data within a table
  • DELETE - deletes all records from a table, the space for the records remain
  • MERGE - UPSERT operation (insert or update)
  • CALL - call a PL/SQL or Java subprogram
  • EXPLAIN PLAN - explain access path to data
  • LOCK TABLE - control concurrency


Data Control Language (DCL) statements. Some examples:
  • GRANT - gives user's access privileges to database
  • REVOKE - withdraw access privileges given with the GRANT command


Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.
  • COMMIT - save work done
  • SAVEPOINT - identify a point in a transaction to which you can later roll back
  • ROLLBACK - restore database to original since the last COMMIT
  • SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use

Converting Your DataTable into List<T>Using Linq Query

This example will help you converting your DataTable into List<T>, this topic is specially helpful for development in silverlight, as DataTables doesnot exist in it, so we need to have to convert DataTable into List<T> or ObservableCollection<T>.

Suppose following is your DataTable
DataTable dtExample = new DataTable("Example");

The process of converting above DataTable completes in three steps.
Step1: Make a class having properties with respect to your DataTable Columns, In the Example Table there are three Columns
>> RollNo
>> Name
>> class
So You have to Make the following Class
public class Employees
        public String RollNo { get ;  set ;}
        public String Name{ get ;  set ;}
        public String Class{ get ;  set ;}

Step2: Make a Function of return type of your above class, that will convert a DataTable Row in List<T> Row, This function will be called in Linq Query in Third Step
private Employees GetEmpDataTableRow(DataRow dr)
     Employees oEmp = new Employees();
     oEmp.RollNo = dr["RollNo"].ToString();
     oEmp.Name = dr["Name"].ToString();
     oEmp.Class = dr["Class"].ToString();
     return oEmp ;
Step3: In the last you are able to convert your DataTable dtExample into List<Employees&gt. go through the Third Step
List<Employees> LstEmployees = new List<Employees>();
LstEmployees = new List<Employees>(
               (from dRow in dtExample.AsEnumerable()
                select (GetEmpDataTableRow(dRow)))

Now LstEmployees is your List of Type List<Employees>, which is converted from DataTable dtExample Hope this will help you and work for you, You can contact in case of any confusion. Thanks for my colleague Mr. Jamal Khan who helped in the above solution

Sample text

Sample Text