LINQ Interview Questions and Answers – 1

Q1.  What is LINQ and why to use it?
Ans. LINQ stands for “Language Integrated Query” and pronounced as “LINK”. LINQ was introduced with .NET Framework 3.5 including Visual Studio 2008, C# 3.0 and VB.NET 2008 (VB 9.0). It enables you to query the data from the various data sources like SQL databases, XML documents, ADO.NET Datasets, Web services and any other objects such as Collections, Generics etc. by using a SQL Query like syntax with .NET framework languages like C# and VB.NET.

Why LINQ
LINQ has full type checking at compile-time and IntelliSense support in Visual Studio, since it used the .NET framework languages like C# and VB.NET. This powerful feature helps you to avoid run-time errors.

LINQ also provides a uniform programming model (i.e. common query syntax) to query various data sources. Hence you don’t need to learn the different ways to query different data sources.

Q2.  Which namespace is necessary to use LINQ?
Ans. System.Linq namespace is necessary for writing LINQ queries and to implement it.

Q3.  What are different flavors of LINQ?
Ans. There are following three flavors of LINQ:

1) LINQ to Objects
It enables you to query any in-memory object like as array, collection and generics types. It offers a new way to query objects with many powerful features like filtering, ordering and grouping with minimum code.

2) LINQ to ADO.NET
LINQ to ADO.NET is used to query data from different databases like as SQL Server, Oracle, and others. Further, it can be divided into three flavours:-

I.  LINQ to SQL (DLINQ)
It is specifically designed to work with only SQL Server database. It is an object-relational mapping (ORM) framework that allows 1-1 mapping of SQL Server database to .NET Classes. These classes are automatically created by the wizard based on database table and we can use these classes immediately.

II.  LINQ to Datasets
It is an easy and faster way to query data cached in a Dataset object. This allows you to do further data manipulation operations (like searching, filtering, sorting) on Dataset using LINQ Syntax. It can be used to query and manipulate any database (like Oracle, MySQL, DB2 etc.) that can be query with ADO.NET.

III.  LINQ to Entities
In many ways, it looks like LINQ to SQL. It is an object-relational mapping (ORM) framework that allows 1-1 mapping , 1-many mapping and many-many mapping of a database to .NET Classes. Unlike LINQ to SQL, it can be used to query any database (like Oracle, MySQL, and DB2 etc.) including SQL Server. Now, it is called ADO.NET Entity Framework.

3)  LINQ to XML (XLINQ)
This allows you to do different operations on XML data source like  querying or reading, modifying, manipulating, and saving changes to XML documents.  System.Xml.Linq namespace contains classes for LINQ to XML.

4) Parallel LINQ (PLINQ)
PLINQ was introduced with .NET Framework 4.0. It is a parallel implementation of LINQ to Objects. PLINQ use the power of parallel programming which targets the Task Parallel Library. PLINQ helps you to write a LINQ query which will be execute simultaneously or parallel on different processors.

Q4.  What are advantages of LINQ?
Ans. There are following advantages of using LINQ:

  1. It provides a uniform programming model (i.e. common query syntax) to query data sources (like SQL databases, XML documents, ADO.NET Datasets, Various Web services and any other objects such as Collections, Generics etc.)
  2. It has full type checking at compile-time and IntelliSense support in Visual Studio. This powerful feature helps you to avoid run-time errors.
  3. It supports various powerful features like filtering, ordering and grouping with minimum code.
  4. Its Query can be reused.
  5. It also allows debugging through .NET debugger.

Q5.  What are disadvantages of LINQ?
Ans. There are following disadvantages of using LINQ:

  1. LINQ is not good to write complex queries like SQL.
  2. LINQ doesn’t take the full advantage of SQL features like cached execution plan for stored procedure.
  3. Performance is degraded if you don’t write the LINQ query correctly.
  4. If you have done some changes in your query, you have to recompile it and redeploy its dll to the server.

ASP.NET MVC Interview Questions and Answers – 1

Q1. What is MVC?
Ans. MVC stands for Model-View-Controller. It is a software design pattern which was introduced in 1970s.
Also, MVC pattern forces a separation of concerns, it means domain model and controller logic are decoupled from user interface (view). As a result maintenance and testing of the application become simpler and easier.

Q2. Explain MVC design pattern?
Ans. MVC design pattern splits an application into three main aspects: Model, View and Controller

Model – The Model represents a set of classes that describe the business logic i.e. business model as well as data access operations i.e. data model. It also defines business rules for data means how the data can be changed and manipulated.

View – The View represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the data that is received from the controller as the result. This also transforms the model(s) into UI.

Controller – The Controller is responsible to process incoming requests. It receives input from users via the View, then process the user’s data with the help of Model and passing the results back to the View. Typically, it acts as the coordinator between the View and the Model.

Q3. What is Domain Driven Design and Development?
Ans. Domain-Driven Design (DDD) is a collection of principles and patterns that help developers to take design decisions to develop elegant systems for different domains. It is not a technology or methodology.
The main components of DDD are: Entity, Value Object, Aggregate, Service and Repository.

Entity– An object that has an identity- it is unique within the system, like Customer, Employee etc.
Value Object– An object that has no identity within the system like Rate, State etc.
Note: A value object can become an entity depending on the situation.

Aggregate: An aggregate root is a special kind of entity that consumers refer to directly. All consumers of the aggregate root are called as aggregate. The aggregate root guarantees the consistency of changes being made within the aggregate.
Service- A service is a way of dealing with actions, operations and activities within your application.
Repository– A repository is responsible to store and to retrieve your data. It is not a concern how and where data will be persist. So, it can be SQL server, oracle, xml, text file or anything else. Repository is not a Data Access Layer but it refers to a location for storage, often for safety or preservation.
For more info refer this link http://msdn.microsoft.com/en-us/magazine/dd419654.aspx

Q4. What is MVP pattern?
Ans. This pattern is similar to MVC pattern in which controller has been replaced by the presenter. This design pattern splits an application into three main aspects: Model, View and Presenter.

Model – The Model represents a set of classes that describes the business logic and data. It also defines business rules for data means how the data can be changed and manipulated.

View – The View represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the data that is received from the presenter as the result. This also transforms the model(s) into UI.

Presenter – The Presenter is responsible for handling all UI events on behalf of the view. This receive input from users via the View, then process the user’s data with the help of Model and passing the results back to the View. Unlike view and controller, view and presenter are completely decoupled from each other’s and communicate to each other’s by an interface. Also, presenter does not manage the incoming request traffic as controller.

This pattern is commonly used with ASP.NET Web Forms applications which require to create automated unit tests for their code-behind pages. This is also used with windows forms.

2015-10-08_123907
Key Points about MVP Pattern

  1. User interacts with the View.
  2. There is one-to-one relationship between View and Presenter means one View is mapped to only one Presenter.
  3. View has a reference to Presenter but View has not reference to Model.
  4. Provides two way communication between View and Presenter.

Q5. What is MVVM pattern?
Ans. MVVM stands for Model-View-View Model. This pattern supports two-way data binding between view and View model. This enables automatic propagation of changes, within the state of view model to the View. Typically, the view model uses the observer pattern to notify changes in the view model to model.

Model – The Model represents a set of classes that describes the business logic and data. It also defines business rules for data means how the data can be changed and manipulated.

View – The View represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the data that is received from the controller as the result. This also transforms the model(s) into UI.

View Model – The View Model is responsible for exposing methods, commands, and other properties that helps to maintain the state of the view, manipulate the model as the result of actions on the view, and trigger events in the view itself.

Overview of Data Structures

This section provides an overview, in the form of a table, of the major data storage structures discussed in this book. This is a bird’s-eye view of a landscape that we’ll be covering later at ground level, so don’t be alarmed if it looks a bit mysterious.

Data Structure Advantages Disadvantages
Array Quick insertion, very fast access if index known. Slow search, slow deletion, fixed size.
Ordered array Quicker search than unsorted array. Slow insertion and deletion, fixed size.
Stack Provides last-in, first-out access. Slow access to other items.
Queue Provides first-in, first-out access. Slow access to other items.
Linked list Quick insertion, quick deletion. Slow search.
Binary tree Quick search, insertion, deletion (if tree remains balanced). Deletion algorithm is complex.
Red-black tree Quick search, insertion, deletion. Tree always balanced. Complex.
2-3-4 tree Quick search, insertion, deletion. Tree always balanced. Similar trees good for disk storage. Complex.
Hash table Very fast access if key known. Fast insertion. Slow deletion, access slow if key not known, inefficient memory usage.

Binary Search Tree Validity

Write a function to determine whether a given binary tree of distinct integers is a
valid binary search tree. Assume that each node contains a pointer to its left child, a
pointer to its right child, and an integer, but not a pointer to its parent. You may use
any language you like.
Good Answer: Note that it’s not enough to write a recursive function that just checks
if the left and right nodes of each node are less than and greater than the current
node (and calls that recursively). You need to make sure that all the nodes of the
subtree starting at your current node are within the valid range of values allowed by
the current node’s ancestors. Therefore you can solve this recursively by writing a
helper function that accepts a current node, the smallest allowed value, and the
largest allowed value for that subtree. An example of this is the following (in Java):

   1: boolean isValid(Node root) {

   2: return isValidHelper(root, Integer.MIN_VALUE,

   3: Integer.MAX_VALUE);

   4: }

   5: boolean isValidHelper(Node curr, int min, int max) {

   6: if (curr.left != null) {

   7: if (curr.left.value < min ||

   8: !isValidHelper(curr.left, min, curr.value))

   9: return false;

  10: }

  11: if (curr.right != null) {

  12: if (curr.right.value > max ||

  13: !isValidHelper(curr.right, curr.value, max))

  14: return false;

  15: }

  16: return true;

  17: }

The running time of this algorithm is O(n).

Implement IndexOf method without Framework

Array.IndexOf searches an array. It acts upon an array of any type in the C# language. It locates the offset of the value searched for. The IndexOf method on Array, in both its generic form and its LastIndexOf form, is useful in many program contexts.

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:  

   6: namespace IndexOF

   7: {

   8:     class Program

   9:     {

  10:  

  11:         private static int IndexOf(char[] chars1, char[] chars2)

  12:         {

  13:             if (chars1.Length < chars2.Length)

  14:                 return -1;

  15:  

  16:             int found = -1;

  17:             int j = 0;

  18:  

  19:             for (int i = 0; i < chars1.Length; i++)

  20:             {

  21:                 if (chars1[i] == chars2[j])

  22:                 {

  23:                     if (j == 0)

  24:                         found = i;

  25:  

  26:                     j++;

  27:                     if (j >= chars2.Length)

  28:                         return found;

  29:                 }

  30:                 else

  31:                 {

  32:                     j = 0;

  33:  

  34:                     if (found >= 0)

  35:                         i = found;

  36:                     found = -1;

  37:                 }

  38:             }

  39:             

  40:             return -1;

  41:         }

  42:  

  43:         static void Main(string[] args)

  44:         {

  45:             char[] arr1 = { 'v', 'a', 'b', 'c', 'd', 'e', 'f' };

  46:             char[] arr2 = { 'c', 'd', 'v'};

  47:  

  48:  

  49:             Console.WriteLine("index = {0}", IndexOf(arr1, arr2).ToString());

  50:  

  51:             Console.ReadKey();

  52:         }

  53:     }

  54: }

Coding Questions

Please answer one or both of the following questions. Please do not use existing class libraries in your answer(s):

Write me a function that receives three integer inputs for the lengths of the sides of a triangle and returns one of four values to determine the triangle type (1=scalene, 2=isosceles, 3=equilateral, 4=error). Generate test cases for the function assuming another developer coded the function

   1: using System;

   2:  

   3: namespace CubicType

   4: {

   5:     class Program

   6:     {

   7:         public enum CubicType

   8:         {

   9:             Scalene = 1, // no sides same length

  10:             Isosceles = 2, // 2 sides same length

  11:             Equilateral = 3, // 3 sides same length

  12:             Error = 4,

  13:         }

  14:  

  15:         private static CubicType GetCubicType(int a, int b, int c) {

  16:             if (a <= 0 || b <= 0 || c <= 0) {

  17:                 return CubicType.Error;

  18:             }

  19:  

  20:             if ((a == b) && (b == c)) {

  21:                 return CubicType.Equilateral;

  22:             }

  23:  

  24:  

  25:             if ((a == b) || (a == c) || (b == c)) {

  26:                 return CubicType.Isosceles;

  27:             }

  28:  

  29:  

  30:             if (((a + b) < c) || ((a + c) < b) || ((b + c) < a)) {

  31:                 return CubicType.Error;

  32:             }

  33:             else {

  34:                 return CubicType.Scalene;

  35:             }

  36:  

  37:         }

  38:  

  39:         static void Main(string[] args) {

  40:  

  41:             CubicType result;

  42:  

  43:             /*

  44:              * Test cases

  45:              * 1. valid scalene triangle?

  46:              * 2. valid equilateral triangle?

  47:              * 3. valid isosceles triangle?

  48:              * 4. 3 permutations of previous?

  49:              * 5. side = 0?

  50:              * 6. negative side?

  51:              * 7. one side is sum of others (1, 2, 3)?

  52:              * 8. 3 permutations of previous?

  53:              * 9. one side larger than sum of others (1, 2, 4)?

  54:              * 10. 3 permutations of previous?

  55:              * 11. all sides = 0?

  56:              * 12. non-integer input?

  57:              * 13. wrong number of values?

  58:              * 14. for each test case: is expected output specified?

  59:              * 15. check behaviour after output was produced?

  60:              * 

  61:             */

  62:             result = GetCubicType(1, 1, 1);

  63:             Console.WriteLine("(1, 1, 1) = {0}", result.ToString()); // Equilateral triangle

  64:  

  65:             result = GetCubicType(2, 1, 1);

  66:             Console.WriteLine("(2, 1, 1) = {0}", result.ToString()); // Isosceles triangle

  67:  

  68:             result = GetCubicType(1, 2, 1);

  69:             Console.WriteLine("(1, 2, 1) = {0}", result.ToString()); // Isosceles triangle

  70:  

  71:             result = GetCubicType(1, 1, 2);

  72:             Console.WriteLine("(1, 1, 2) = {0}", result.ToString()); // Isosceles triangle

  73:                        

  74:             

  75:             result = GetCubicType(1, 2, 25);

  76:             Console.WriteLine("(1, 2, 25) = {0}", result.ToString()); // Error

  77:  

  78:             result = GetCubicType(1, 0, -1);

  79:             Console.WriteLine("(1, 0, -1) = {0}", result.ToString());

  80:  

  81:             result = GetCubicType(4, 5, 6);

  82:             Console.WriteLine("(4, 5, 6) = {0}", result.ToString());

  83:             

  84:             result = GetCubicType(2147483647, 2147483647, 2147483647);

  85:             Console.WriteLine("(2147483647, 2147483647, 2147483647) = {0}", result.ToString());

  86:  

  87:         }

  88:     }

  89: }

 

1) Implement a circular queue of integers of user-specified size using a simple array. Provide routines to initialize(), enqueue() and dequeue() the queue. Make it thread safe.

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5: using System.Threading;

   6:  

   7: namespace ThreadSafeCircularQueue

   8: {

   9:     /// <summary>

  10:     ///  CircularQueue

  11:     /// </summary>

  12:     public class CircularQueue

  13:     {

  14:         private int head;

  15:         private int tail;

  16:         private int[] queue;

  17:         private int length;

  18:  

  19:         private static Object QueueLock = new Object(); // Make the Queue thread safe

  20:  

  21:         /// <summary>

  22:         ///  Queue Constructor

  23:         /// </summary>

  24:         /// <param name="lengh"> Length of Queue</param>

  25:         public CircularQueue(int lengh)

  26:         {

  27:             Initialize(length);

  28:         }

  29:  

  30:         public CircularQueue()

  31:         {

  32:  

  33:         }

  34:  

  35:         /// <summary>

  36:         /// Initializes the Queue

  37:         /// </summary>

  38:         /// <param name="length"> length </param>

  39:         private void Initialize(int length)

  40:         {

  41:             head = -1;

  42:             tail = -1;

  43:  

  44:             this.length = length;

  45:             queue = new int[length];

  46:  

  47:             Console.WriteLine("Queue size: {0}", length);

  48:         }

  49:  

  50:         /// <summary>

  51:         /// Adds a new int element to the tail of the Queue

  52:         /// </summary>

  53:         /// <param name="value">The integer value of the element to be queued</param>

  54:         /// <returns>The index of the queued element or failure</returns>

  55:         public int Enqueue(int value)

  56:         {

  57:             lock (QueueLock) {

  58:                 if ((head == 0 && tail == length - 1) || (tail + 1 == head)) {

  59:                     Console.WriteLine("Queue is full.");

  60:                     return -1;

  61:                 }

  62:                 else {

  63:                     if (tail == length - 1)

  64:                         tail = 0;

  65:                     else

  66:                         tail++;

  67:  

  68:                     queue[tail] = value;

  69:  

  70:                     if (head == -1)

  71:                         head = 0;

  72:  

  73:                     return tail;

  74:                 }

  75:  

  76:             }

  77:         }

  78:  

  79:         /// <summary>

  80:         /// Gets the first element's value

  81:         /// </summary>

  82:         /// <returns></returns>

  83:         public int Dequeue()

  84:         {

  85:             lock (QueueLock) {

  86:                 int value;

  87:  

  88:                 if (head == -1) {

  89:                     value = -1;

  90:                 }

  91:                 else {

  92:                     value = queue[head];

  93:                     queue[head] = 0;

  94:  

  95:                     if (head == tail)

  96:                         head = tail = -1;

  97:                     else

  98:                         if (head == length - 1)

  99:                             head = 0;

 100:                         else

 101:                             head++;

 102:                 }

 103:  

 104:                 return value;

 105:             }

 106:         }

 107:  

 108:         /// <summary>

 109:         /// Gets a formatted string of the queue elements

 110:         /// </summary>

 111:         /// <returns>Queue elements</returns>

 112:         public string ShowQueue()

 113:         {

 114:             lock (QueueLock) {

 115:                 int i;

 116:                 string result = " Queue Emelemnts: ";

 117:  

 118:                 if (head == -1) {

 119:                     result = "No elements(empty)";

 120:                 }

 121:                 else {

 122:                     if (tail < head) {

 123:                         for (i = 0; i <= length - 1; i++)

 124:                             result += queue[i] + " ";

 125:                     }

 126:                     else

 127:                         for (i = 0; i <= tail; i++)

 128:                             result += queue[i] + " ";

 129:                 }

 130:                 return result + "\n";

 131:             }

 132:         }

 133:  

 134:         /// <summary>

 135:         /// Test

 136:         /// </summary>

 137:         public void QueueTest()

 138:         {

 139:             Initialize(3);

 140:             Enqueue(1);

 141:             Console.Write(ShowQueue());

 142:             Enqueue(2);

 143:             Console.Write(ShowQueue());

 144:             Enqueue(3);

 145:             Console.Write(ShowQueue());

 146:             Enqueue(4);

 147:             Console.Write(ShowQueue()); 

 148:             Dequeue();

 149:             Console.Write(ShowQueue());

 150:             Dequeue();

 151:             Console.Write(ShowQueue());

 152:             Dequeue();

 153:             Console.Write(ShowQueue());

 154:             Dequeue();

 155:             Console.Write(ShowQueue());

 156:             Enqueue(4);

 157:             Console.Write(ShowQueue());

 158:             Dequeue();

 159:             Console.Write(ShowQueue());

 160:             Dequeue();

 161:             Console.Write(ShowQueue());

 162:         }

 163:  

 164:     }

 165:  

 166:     class Program

 167:     {

 168:         static void Main(string[] args)

 169:         {

 170:             CircularQueue circularQueue = new CircularQueue();

 171:  

 172:             Thread[] threads = new Thread[5];

 173:  

 174:             for (int i = 0; i < threads.Length; i++) {

 175:                 threads[i] = new Thread(new ThreadStart(circularQueue.QueueTest));

 176:             }

 177:  

 178:             for (int i = 0; i < threads.Length; i++) {

 179:                 threads[i].Start();

 180:             }

 181:             Console.ReadLine();

 182:         }

 183:     }

 184: }

Technical Questions 1

1) Which is better – singly linked list or doubly linked list? What are the pros and cons of using each?

Singly-linked list:

Pros: Simple in implementation, requires relatively lesser memory for storage, assuming you need to insert/delete at next node; insertion/deletion is faster.

Cons: Cannot be iterated in reverse, need to maintain a handle to the head node of the list else, the list will be lost in memory. If you’re deleting previous node or inserting at previous node, you will need to traverse list from head to previous node to be able to carry out those operations – O(N) time.

That should be used when you have lesser memory and your main purpose is insertion/deletion and not searching elements.

Doubly-linked list:

Pros: Can be iterated in forward as well as reverse direction. In case of needing to delete previous node, there is no need to traverse from head node, as the node to be deleted can be found from ‘.previous’ pointer.

Cons: Relatively complex to implement, requires more memory for storage (1 ‘.previous’ pointer per node). Insertions and deletions are relatively more time consuming (assigning/reassigning ‘.previous’ pointer for neighbor nodes)

That should be used when you have no minimal limitations on memory, and your main purpose is to search for elements.

2) What’s the difference between Managed code and Native code? Give examples of each you have worked on.
The big difference is memory management. With Native Code, you need to do your own resource (RAM / Memory) allocation and cleanup. If you forget something, you end up with what’s called a “Memory Leak” that can crash the computer. A Memory Leak is a term for when an application starts using up (eating up) Ram/Memory but not letting it go so the computer can use if for other applications; eventually this causes the computer to crash. With Managed Code, all the resource (RAM / Memory) allocation and cleanup are done for you and the risk of creating “Memory Leaks” is reduced to a minimum. This allows more time to code features instead of spending it on resource management.

  • · Managed code runs under CLR whereas native code does not run under CLR.
  • · Managed code takes advantages of memory management, security and threading services CLR provides, whereas these are missing for native code that directly runs on the machine.
  • · The managed code is the one generated by C# and other .NET language compilers (IL) and gets finally converted to native code by JIT. The code in languages prior to .NET like VC++ get converted directly to native code and runs on the machine.eg COM components

Over the past two years, I developed web applications for extending the server by modules which are developed in two ways (We have specific requirements that demand native code development and would like to convert our existing native ISAPI components, take advantage of this API to build server components.):

a) Using managed code, and the ASP.NET server extensibility APIs

b) Using native code, and the IIS native server extensibility APIs

3) What is thread safe code? Give an example of times you’ve used thread safe code.
Thread-safety is a computer programming concept applicable to multi-threaded programs. A piece of code is thread-safe if it is reentrant or protected from multiple simultaneous executions by some form of mutual exclusion.

Thread-safety is a key challenge in multi-threaded programming. In a multi-threaded program, several threads execute simultaneously in a shared address space. Every thread has access to virtually all the memory of every other thread. Thus the flow of control and the sequence of accesses to data often have little relation to what would be reasonably expected by looking at the text of the program. This violates the principle of least astonishment. Thread-safety is a property aimed for so as to minimize surprising behavior by re-establishing some of the correspondences between the actual flow of control and the text of the program.

General-purpose types are rarely thread-safe in their entirety, for the following reasons:

  • · The development burden in full thread safety can be significant, particularly if a type has many fields (each field is a potential for interaction in an arbitrarily multithreaded context).
  • · Thread safety can entail a performance cost (payable, in part, whether or not the type is actually used by multiple threads).
  • · A thread-safe type does not necessarily make the program using it thread-safe, and often the work involved in the latter makes the former redundant.

Example: Methods used in Logger, to write a log file, should be threading safe for an application that runs under multi-threading environment.

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

   1: public static class SharedLogger

   2: {

   3:     private static LogToFile _writer = new LogToFile();

   4:     private static object _lock = new object();

   5:     public static void Write(string text)

   6:     {

   7:         lock (_lock)

   8:         {

   9:             _writer.LogToFile(string text);

  10:         }

  11:     }

  12: }

Implement a method to perform basic string compression using the counts of repeated characters.

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:  

   6: namespace _1_05_CompressionString

   7: {

   8:     class Program

   9:     {

  10:         private static int countCompression(string str)

  11:         {

  12:             int size = 0;

  13:  

  14:             char last = str[0];

  15:             int count = 1;

  16:  

  17:             for (int i = 0; i < str.Length; i++)

  18:             {

  19:                 if (str[i] == last)

  20:                 {

  21:                     count++;

  22:                 }

  23:                 else

  24:                 {

  25:                     last = str[i];

  26:                     size += 1 + count.ToString().Length;

  27:                     count = 1;

  28:                 }

  29:             }

  30:             size += 1 + count.ToString().Length;

  31:             return size;

  32:         }

  33:  

  34:  

  35:         private static string Compression1(string str)

  36:         {

  37:             int size = countCompression(str);

  38:             if (size >= str.Length)

  39:             {

  40:                 return str;

  41:             }

  42:  

  43:             StringBuilder stb = new StringBuilder();

  44:             char last = str[0];

  45:             int count = 1;

  46:  

  47:             for (int i = 1; i < str.Length; i++)

  48:             {

  49:                 if (last == str[i])

  50:                 {

  51:                     count++;

  52:                 }

  53:                 else

  54:                 {

  55:                     stb.Append(last);

  56:                     stb.Append(count);

  57:                     last = str[i];

  58:                     count = 1;

  59:                 }

  60:             }

  61:             stb.Append(last);

  62:             stb.Append(count);

  63:  

  64:             return stb.ToString();

  65:         }

  66:  

  67:         private static string Compression2(string str)

  68:         {

  69:             int size = countCompression(str);

  70:             if (size >= str.Length)

  71:             {

  72:                 return str;

  73:             }

  74:  

  75:             string result = string.Empty;

  76:             char last = str[0];

  77:             int count = 1;

  78:  

  79:             for (int i = 1; i < str.Length; i++)

  80:             {

  81:                 if (last == str[i])

  82:                 {

  83:                     count++;

  84:                 }

  85:                 else

  86:                 {

  87:                     result += last.ToString();

  88:                     result += count.ToString();

  89:                     last = str[i];

  90:                     count = 1;

  91:                 }

  92:             }

  93:             result += last.ToString();

  94:             result += count.ToString();

  95:  

  96:             return result;

  97:         }

  98:  

  99:         static void Main(string[] args)

 100:         {

 101:             string str = "abbcccccccccccccccccccccccccccde";

 102:  

 103:             Console.WriteLine("{0} : {1}", str, countCompression(str)); 

 104:  

 105:             Console.WriteLine("{0} : {1}", str, Compression1(str)); 

 106:             Console.WriteLine("{0} : {1}", str, Compression2(str));

 107:  

 108:             Console.ReadKey();

 109:         }

 110:     }

 111: }

Implement an algorithm to determine if a string has all unique characters.

 

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:  

   6: namespace IsUniqueCharacters

   7: {

   8:     class Program

   9:     {

  10:         private static bool isUniqueChars(string str)

  11:         {          

  12:  

  13:             bool[] arrBool = new bool[256];

  14:  

  15:             for (int i = 0; i < str.Length; i++)

  16:             {

  17:                 int val = str[i];

  18:                 if (arrBool[val])

  19:                     return false;

  20:  

  21:                 arrBool[val] = true;

  22:             }

  23:  

  24:             return true;

  25:         }

  26:  

  27:         private static void FindUniqueChars(string str)

  28:         {

  29:             if (!isUniqueChars(str))

  30:             {

  31:                 Console.WriteLine("No unique string");

  32:             }

  33:  

  34:             int[] arrIndex = new int[256];

  35:             for (int i = 0; i < str.Length; i++)

  36:             {

  37:                 arrIndex[str[i]]++;

  38:             }

  39:  

  40:             Console.Write("Duplicate chars in ({0}) = ", str);

  41:             for (int j = 0; j < 256; j++)

  42:             {

  43:                 if (arrIndex[j] > 1)

  44:                     Console.Write("{0} ", (char)j);

  45:             }

  46:             Console.WriteLine();

  47:         }

  48:  

  49:  

  50:         static void Main(string[] args)

  51:         {

  52:             string[] arrStrings = new string[] { "abcdedisp", "akcidiugs", "sacddes", "abcsnil", "abckiipdnsu", "iiiiiiii", "aaaiiimmm" };

  53:  

  54:             foreach (string str in arrStrings)

  55:             {

  56:                 if (isUniqueChars(str))

  57:                     Console.WriteLine("{0} is Uniq", str);

  58:                 else

  59:                     Console.WriteLine("{0} is NOT Uniq", str);

  60:  

  61:                 FindUniqueChars(str);

  62:  

  63:             }

  64:  

  65:             Console.ReadKey();

  66:         }

  67:     }

  68: }

Please make a list of all the different types of testing a tester can do.

I like this question b/c then candidates have all these categories at the top of their heads for use in testing questions later in the day.

There are different names for the same kinds of testing, so candidates may use different terms. If you’re not sure, ask them to clarify.

A good answer will include many of the following: (the farther down on the list, the more likely a candidate will miss it)

· Black box – testing without knowing how the code works

· White box – testing when you know exactly what the code is doing

· Gray box – a combination of black and white box

· Automation – using code to create test cases that can be run over and over at the click of a mouse

· Functionality – the basic functional aspects. Ex can you print, save?

· UI (User Interface) –Do buttons and links take you to the right place? Can you find your way around?

· Error handling – if you make a mistake or do something evil, does the product recover gracefully?

· Performance – how fast does the product run under certain conditions?

· Stress – how does the software do when you put stress on it? Heavy loads, fewer resources like memory…

· Stability – how does the software do over time? When it’s been running for days on end?

· Load – how does the software do when lots of people are using it at once?

· Database – is the data getting to and from the database correctly?

· End to End/Integration – testing the code as a full system, rather than testing individual parts

· Component testing – testing the individual parts

· Usability – is the software intuitive to use? Watch actual customers use the product

· Boundary – if a field can take up to 10 characters, test 8, 9 and 10 chars.

· Scalability – can we grow this software to run on more servers and have more customers in the future?

· BVT (Build Verification Test) – basic cases run each time a new build is released)

· API (Application Program Interface) – testing the input/output for an OS service

· Bug Bash – let the whole team (PM, dev, marketing etc) test the product

· Alpha/Beta – let the customers test the product, get their feedback

· Regression – is a bug really fixed? Was anything else broken as a side effect of the fix?

· Compatibility – can the software run on different browsers and operating systems? Backward compatibility for Office and Windows? Upgrades?

· Security – is the software vulnerable to attacks?

· Globalization – is the software world-ready? (ex no hard coded strings)

· Localization – did we break anything when we regionalized the product?

Technical Questions

1) Which is better – singly linked list or doubly linked list? What are the pros and cons of using each?
Singly linked list has smaller memory requirement because singly linked list can only be traversed in one direction. Doubly linked lists require more space for each element in the list and elementary operations such as insertion and deletion is more complex since they have to deal with two references. But doubly link lists allow easier manipulation since it allows traversing the list in forward and backward directions.

Singly Linked List vs. Doubly Linked List

· Elements in singly linked list are linked to only the next element in the series while elements are linked with previous and next both elements in doubly linked list.

· Singly linked lists need lesser space while doubly linked list need more space for every block in the list.

· Basic functions like addition or deletion are complicated in doubly linked list because there are two links to deal with but you can easily manipulate the data because you can cross over the list and move back and forth in the list.

2) What’s the difference between Managed code and Native code? Give examples of each you have worked on.

Managed Code:

Managed code runs on the CLR (Common Language Runtime), which, among other things, offers services like garbage collection, run-time type checking, and reference checking. Managed code takes advantages of memory management, security and threading services CLR provides.

The managed code is the one generated by C# and other .NET language compilers (IL) and gets finally converted to native code by JIT. If you are writing an application in Visual C++ .NET you can produce managed code if you like, but it’s optional.

Native Code:

Native code does not run under CLR and compiles straight to machine code. No free memory management or anything else the CLR provides. Since you cannot create unmanaged code with Visual Basic or C#, in Visual Studio all unmanaged code is written in C/C++.

I wrote some web applications in C and C++ on the apache on Linux. These are native code applications whose memory is not “managed”, as in, memory isn’t freed (C++’ delete and C’s free, for instance), no reference counting, no garbage collection. I had to take care of these to free allocated memory.

3) What is thread safe code? Give an example of times you’ve used thread safe code.

Thread Safe code is one which runs in a manner that when multiple threads are running simultaneously and are in need of using shared memory, they do not step onto each other or in other words access the shared memory exclusively.

By using thread-safe routines, the risk that one thread will interfere and modify data elements of another thread is eliminated by circumventing potential data race situations with coordinated access to shared data.

Implement a circular queue

Implement a circular queue of integers of user-specified size using a simple array. Provide routines to initialize(), enqueue() and dequeue() the queue. Make it thread safe.

   1: using System;

   2: using System.Text;

   3: using System.Threading;

   4:  

   5: public class IntegerQueue

   6: {

   7:     int[] _queue;

   8:     int _in;

   9:     int _out;

  10:     int _count;

  11:  

  12:     private static Object QueueLock = new Object(); // Make the Queue thread safe

  13:  

  14:     public IntegerQueue(int size)

  15:     {

  16:         Initialize(size);

  17:     }

  18:  

  19:     public void Initialize(int size)

  20:     {

  21:         _queue = new int[size];

  22:         _count = 0;

  23:         _in = 0;

  24:         _out = 0;

  25:     }

  26:  

  27:     public void Enqueue(int value)

  28:     {

  29:         lock (QueueLock)

  30:         {

  31:             Console.WriteLine("Enqueue: {0}", value);

  32:             if (_queue.Length <= _count)

  33:             {

  34:                 Console.WriteLine("Overflow.");

  35:             }

  36:             else

  37:             {

  38:                 _queue[_in] = value;

  39:                 _in = (_in + 1) % _queue.Length;

  40:                 _count++;

  41:             }

  42:             DebugPrint();

  43:         }

  44:     }

  45:     public int Dequeue()

  46:     {

  47:         lock (QueueLock)

  48:         {

  49:             Console.WriteLine("Dequeue:");

  50:             int value = 0;

  51:             if (_count <= 0)

  52:             {

  53:                 Console.WriteLine("Underflow.");

  54:             }

  55:             else

  56:             {

  57:                 value = _queue[_out];

  58:                 _out = (_out + 1) % _queue.Length;

  59:                 _count--;

  60:             }

  61:             DebugPrint();

  62:             return value;

  63:         }

  64:  

  65:     }

  66:     public override String ToString()

  67:     {

  68:         StringBuilder builder = new StringBuilder();

  69:         if (_count > 0)

  70:         {

  71:             for (int i = 0; i < _count; i++)

  72:             {

  73:                 builder.Append(_queue[(_out + i) % _queue.Length]);

  74:                 builder.Append(", ");

  75:             }

  76:         }

  77:         else

  78:         {

  79:             builder.Append("(empty)");

  80:         }

  81:         return builder.ToString();

  82:     }

  83:     public void DebugPrint()

  84:     {

  85:  

  86:         lock (QueueLock)

  87:         {

  88:             Console.WriteLine("\t{0}", ToString());

  89:         }

  90:  

  91:     }

  92:  

  93:  

  94:     public void QueueTest()

  95:     {

  96:         Enqueue(1);

  97:         Console.WriteLine();

  98:  

  99:         Enqueue(2);

 100:         Console.WriteLine();

 101:  

 102:        Enqueue(3);

 103:         Console.WriteLine();

 104:  

 105:         Console.WriteLine("--> {0}", Dequeue());

 106:         Console.WriteLine();

 107:  

 108:         Console.WriteLine("--> {0}", Dequeue());

 109:         Console.WriteLine();

 110:  

 111:         Console.WriteLine("--> {0}", Dequeue());

 112:         Console.WriteLine();

 113:  

 114:         Enqueue(4);

 115:         Console.WriteLine();

 116:  

 117:         Enqueue(5);

 118:         Console.WriteLine();

 119:  

 120:         Console.WriteLine("--> {0}", Dequeue());

 121:         Console.WriteLine();

 122:  

 123:         Enqueue(6);

 124:         Console.WriteLine();

 125:  

 126:         Enqueue(7);

 127:         Console.WriteLine();

 128:  

 129:         Enqueue(8);

 130:         Console.WriteLine();

 131:  

 132:         Enqueue(9);

 133:         Console.WriteLine();

 134:  

 135:         Console.WriteLine("--> {0}", Dequeue());

 136:         Console.WriteLine();

 137:  

 138:         Console.WriteLine("--> {0}", Dequeue());

 139:         Console.WriteLine();

 140:  

 141:         Console.WriteLine("--> {0}", Dequeue());

 142:         Console.WriteLine();

 143:  

 144:         Console.WriteLine("--> {0}", Dequeue());

 145:         Console.WriteLine();

 146:  

 147:         Console.WriteLine("--> {0}", Dequeue());

 148:         Console.WriteLine();

 149:  

 150:         Console.ReadLine();

 151:     }

 152:  

 153: }

 154:  

 155: public class QueueApp

 156: {

 157:     public static void Main(String[] args)

 158:     {

 159:         IntegerQueue queue = new IntegerQueue(5);

 160:  

 161:         Thread[] threads = new Thread[1];

 162:  

 163:         for (int i = 0; i < threads.Length; i++)

 164:         {

 165:             threads[i] = new Thread(new ThreadStart(queue.QueueTest));

 166:         }

 167:  

 168:         for (int i = 0; i < threads.Length; i++)

 169:         {

 170:             threads[i].Start();

 171:         }

 172:         Console.ReadLine();

 173:     }

 174: }

Triangle check

Write me a function that receives three integer inputs for the lengths of the sides of a triangle and returns one of four values to determine the triangle type (1=scalene, 2=isosceles, 3=equilateral, 4=error). Generate test cases for the function assuming another developer coded the function

 

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:  

   6: namespace Triangle

   7: {

   8:     class Program

   9:     {

  10:         public enum TriangleType

  11:         {

  12:             Scalene = 1,

  13:             Isosceles = 2,

  14:             Equilateral = 3,

  15:             Error = 4,

  16:         }

  17:         private static TriangleType triangle(int a, int b, int c)

  18:         {

  19:             TriangleType answer;

  20:  

  21:             if (a <= 0 || b <= 0 || c <= 0)

  22:             {

  23:                 // negative length -- illegal

  24:                 answer =  TriangleType.Error;

  25:             }

  26:             else if ((a + b <= c) || (b + c <= a) || (a + c <= b))

  27:             {

  28:                 // Sides can't possible connect -- illegal

  29:                 answer = TriangleType.Error;

  30:             }

  31:             else if ((a == b) && (b == c))

  32:             {

  33:                 // by the transitive rule, a == c well

  34:                 answer = TriangleType.Equilateral;

  35:             }

  36:             else if ((a == b) || (b == c) || (a == c))

  37:             {

  38:                 // We've already eliminated quilateral triangles above,

  39:                 // we'll only get here if exactly two sides match

  40:                 answer = TriangleType.Isosceles;

  41:             }

  42:             else

  43:             {

  44:                 // Since, we've eliminated all alternatives, we must have

  45:                 // a scalene triangle if we get here.

  46:                 answer = TriangleType.Scalene;

  47:             }

  48:  

  49:             return answer;

  50:         }

  51:  

  52:         static void Main(string[] args)

  53:         {

  54:             TriangleType result;

  55:             result = triangle(0, 0, 0);

  56:             Console.WriteLine("(0, 0, 0) = {0}", result.ToString());

  57:  

  58:             result = triangle(-1, 2, 3);

  59:             Console.WriteLine("(-1, 2, 3) = {0}", result.ToString());

  60:  

  61:             result = triangle(1, -2, 3);

  62:             Console.WriteLine("(1, -2, 3) = {0}", result.ToString());

  63:  

  64:             result = triangle(1, 2, -3);

  65:             Console.WriteLine("(1, 2, -3) = {0}", result.ToString());

  66:  

  67:             result = triangle(1, 1, 1);

  68:             Console.WriteLine("(1, 1, 1) = {0}", result.ToString());

  69:  

  70:             result = triangle(1, 2, 2);

  71:             Console.WriteLine("(1, 2, 2) = {0}", result.ToString());

  72:  

  73:             result = triangle(4, 5, 6);

  74:             Console.WriteLine("(4, 5, 6) = {0}", result.ToString());

  75:  

  76:             result = triangle(5, 1, 5);

  77:             Console.WriteLine("(5, 1, 5) = {0}", result.ToString());

  78:  

  79:             result = triangle(5, 5, 5);

  80:             Console.WriteLine("(5, 5, 5) = {0}", result.ToString());

  81:  

  82:             result = triangle(-10, -10, -10);

  83:             Console.WriteLine("(-10, -10, -10) = {0}", result.ToString());

  84:         }

  85:     }

  86: }

Merge 2 sorted Array in C#

using System;
using System.Linq;

namespace Merge2Array
{
class Program
{
static void Main()
{
int[] A = { 0, 3, 5, 6, 9, 10, 13, 14 }; // already sorted
int[] B = { 1, 2, 4, 6, 7, 11, 12, 15, 16 }; // ditto

// create sufficiently large output array
int[] C = new int[A.Length + B.Length];

// create indices to keep track of positions in B and C
int indexB = 0, indexC = 0;

// iterate through A
for (int i = 0; i < A.Length; i++)
{
// iterate through B ignoring elements already added to C
for (int j = indexB; j < B.Length; j++)
{
// if B contains elements which are smaller than the current element of A, add them to C
if (B[j] < A[i])
{
C[indexC++] = B[j];
indexB = j + 1; // value at which to start next iteration of B
}
else
{
// stop iterating when there are no more elements of B smaller than current element of A
break;
}
}
// now add current element of A to C
C[indexC++] = A[i];
// if this is A's final element but there are still larger items of B, add them to C
if (i == A.Length - 1 && indexB < B.Length)
{
for (int k = indexB; k < B.Length; k++) C[indexC++] = B[k];
}
}

// check it worked
for (int i = 0; i < C.Length; i++) Console.Write("{0} ", C[i]);
Console.WriteLine();

// Test do the same way by LINQ
int[] D = A.Concat(B).OrderBy(n => n).ToArray();

// check it worked again
for (int i = 0; i < D.Length; i++) Console.Write("{0} ", D[i]);
Console.WriteLine();

Console.ReadKey();
}
}
}



Is Palindrome in C#

using System;

namespace CheckStringForPalindrome
{
    class Program
    {
        public static bool IsPalindrome(string strValue)
       {
            int intLen, intStrPartLen;
            intLen = strValue.Length - 1;

            //Cut the length of the string into 2 halfs
            intStrPartLen = intLen / 2;
            for (int intIndex = 0; intIndex <= intStrPartLen; intIndex++)
            {
                //intIndex is the index of the char in the front of the string
                //Check from behind and front for match
                if (strValue[intIndex] != strValue[intLen])
                {
                    return false;
                }

                //decrease the lenght of the original string to
                //test the next Char from behind
                intLen--;
            }
            return true;
        }

        static void Main(string[] args)
        {
            string str;

            Console.Write("Please input:");
            str = Console.ReadLine();

            char[] strAry = str.ToCharArray();
            Array aStr = str.ToCharArray();
            Array.Reverse(aStr);
            string strreverse = string.Empty;
            foreach (char c in aStr) 
            { 
                strreverse = strreverse + c;
            }
            if (str.Equals(strreverse))
            {
                Console.WriteLine("String is poly" + System.Environment.NewLine);
            }
            else
            {
                Console.WriteLine("String is Not poly" + System.Environment.NewLine);
            }

        }
    }
}

Number to word in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NumberToWord
{
public class NumberToWords{
string [] Number1 = {""," Hundrad"};
string [] Number2 = {"","One","Two", "Three","Four","Five"," Six"," Seven", "Eight"," Nine","Ten" };


public string Number(int number)
{
String str;
if (number % 100 < 10)
{
str = Number2[number % 100];
number /= 100;
}
else
{
str= Number2[number % 5];
number /= 5;
}

if (number == 0) return str;

return Number2[number] + "hundred" + str;

}

public String convert(int number) {
if (number == 0){
return "zero";
}
String pre = "";
String str1 = "";
int i = 0;
do {
int n = number % 100;
if (n != 0){
string s = Number(n);
str1 = s + Number1[i] + str1;
}
i++;
number /= 100;
}
while (number > 0);
return (pre + str1).Trim();
}

public static void Main(String[] args)
{
NumberToWords num = new NumberToWords();

Console.WriteLine("words is :=" + num.convert(0));
Console.WriteLine("words is :=" + num.convert(12));
Console.WriteLine("words is :=" + num.convert(9));
Console.WriteLine("words is :=" + num.convert(100));
}

} }

Make permutation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Permutation2
{
class Program
{
private static void permutation(string str)
{
int length = str.Length;
bool[] used = new bool[length];

StringBuilder sb = new StringBuilder();
char[] arrChar = str.ToCharArray();

doPermute(arrChar, sb, used, length, 0);
}

private static void doPermute(char[] arrCh, StringBuilder sb, bool[] used, int length, int level)
{
if (level == length)
{
Console.WriteLine(sb.ToString());
return;
}

for (int i = 0; i < length; ++i)
{
if (used[i])
continue;

sb.Append(arrCh[i]);
used[i] = true;
doPermute(arrCh, sb, used, length, level + 1);
used[i] = false;
//sb.Capacity = sb.Length - 1;
sb.Remove(sb.Length - 1, 1);
}
}

static void Main(string[] args)
{
string sample = "abc";

Console.WriteLine("{0} : ", sample);
permutation(sample);

Console.ReadLine();

}
}
}

Convert String to Int & Int to String

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StringToLong
{
class StringToLong
{
private static int strToInt(string str)
{
int i = 0, num = 0;
bool isNeg = false;

int len = str.Length;

if (str[0] == '-')
{
isNeg = true;
i = 1;
}

while (i < len)
{
num *= 10;
num += (str[i++] - '0');
}
if (isNeg)
num *= -1;

return num;
}

private static string intToStr(int num)
{
int i = 0;
bool isNeg = false;

char[] temp = new char[10 + 1];

if (num < 0)
{
num *= -1;
isNeg = true;
}

//while (num != 0)
//{
// temp[i++] = (char)((num % 10) + '0');
// num /= 10;
//}

do
{
temp[i++] = (char)((num % 10) + '0');
num /= 10;

} while (num != 0);

StringBuilder sb = new StringBuilder();

if (isNeg)
sb.Append('-');

while(i > 0)
{
sb.Append( temp[--i]);
}
return sb.ToString();
}

private static long ConvertString(string str)
{
int len = str.Length;
bool blNegative = false;

int index = blNegative? 1:0;

if (str[0].Equals("-"))
{
blNegative = true;
}

long lnResult = 0;

do {
lnResult *= 10;
int i = str[index] - 48; //ASCII zero
if (i < 0 | i > 9)
throw new FormatException();

lnResult += i;
index++;
} while(len > index);

return blNegative? -lnResult:lnResult;
}

static void Main(string[] args)
{
string str1 = "3511";

Console.WriteLine(ConvertString(str1).ToString());

Console.WriteLine("{0} : {1}", str1, strToInt(str1).ToString());

str1 = "0";

Console.WriteLine("{0} : {1}", strToInt(str1), intToStr(strToInt(str1)));

Console.ReadLine();

}
}
}

Checking if a string has balanced parentheses

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace isBalanced {
    class Program {

        const char LeftParenthesis = '(';
 const char RightParenthesis = ')';

        static bool isBalancedWithStack(string str) {
            
            if (str.Length <;= 1 || str.Equals(null))
                return false;

 var items = new Stack<int>(str.Length);
            int errorAt = -1;
 for (int i = 0; i < str.Length; i++)
            {
 
                if (str[i].Equals(LeftParenthesis))
                    items.Push(i);
 else if (str[i].Equals(RightParenthesis))
                {
                    if (items.Count == 0)
                    {
                        errorAt = i + 1;
 return false;
                    }
                    items.Pop();
 }
            }
            if (items.Count >; 0)
            {
                errorAt = items.Peek() + 1;
 return false;
            }
            return true;
 }


        static bool isBalancedWithoutStack(string str) {

            int count = 0;

 if (str.Length <= 1)
                return false;

 for (int i = 0; i < str.Length; i++)
            {
                if (str[i].Equals('('))
                    count++;
 else if (str[i].Equals(')'))
                {
                    count--;
 if (count < 0)
                        return false;
 }
            }

            return (count == 0);
 }

        static bool checkParentheses(string str) 
        {
            if (str.Length <;= 1)
                return false;

 int count = 0;

            for (int i = 0; i < str.Length; i++)
            {
                switch (str[i])
                {
                    case '(':
                        count++;
 break;

                    case ')':
                        count--;
 if (count < 0)
                            return false;
 break;
                }
            }

            return (count == 0);

 }

        static void Main(string[] args) {

            string[] arrSample = new string[] { " ", "", "(","()))))))", "(()((fff))())", "(()", "((((()))))", "(()(((())))())", "(()(((())))()", "()()()()()()()()()()()()" };



 for (int i = 0; i < arrSample.Length; i++)
            {
                if (isBalancedWithStack(arrSample[i]))
                {
                    Console.WriteLine("{0} is True", arrSample[i]);
 }
                else
                {
                    Console.WriteLine("{0} is False", arrSample[i]);
 }

                if (isBalancedWithoutStack(arrSample[i]))
                {
                    Console.WriteLine("{0} is True", arrSample[i]);
 }
                else
                {
                    Console.WriteLine("{0} is False", arrSample[i]);
 }

                if (checkParentheses(arrSample[i]))
                {
                    Console.WriteLine("{0} is True", arrSample[i]);
 }
                else
                {
                    Console.WriteLine("{0} is False", arrSample[i]);
 }

                Console.WriteLine();
 }

        }
    }
}