Showing posts from July, 2011

Tech Qu: Some SQL Server Questions

The Idiot ones I have gathered a few from some interview sites, and the ones below are so trivial that it’s shocking that they were asked!   WriteTSSL to find all the duplicate email address in a table which contains only one column "email" Code Snippet select [email] from [sometable] where [email] is not null OR len ( [email] )= 0 group by [email] having count ( [email] ) > 1   Many answers failed to exclude no email (could be recorded as null or an empty string), or return the count with it (which was not asked for).   Given a table: CustomerOrders: (Customer ID | Order ID | Order Date) 1. Write a SQL to find all customers who has placed an order today. 2. Write a SQL to find all customers who has placed an order today AND yesterday. Again, a trivial one Code Snippet Select CustomerId from CustomerOrders Where OrderDate >= Cast ( GetDate as Date ) Select CustomerId from CustomerOrders Where Ord

Tech Qu: Removing duplicates from an integer array

Write two algorithms to remove duplicates from an integer array.   There are many solutions including sorting the array and then finding duplicates. My preference would be the following ones Code Snippet public static int [] NoDuplicate1( int [] arr) {    var map = new HashSet < int >();    foreach ( var i in arr)     map.Add(i);    return map.ToArray(); } public static int [] NoDuplicate2( int [] arr) {    var map = new Queue < int >();    foreach ( var i in arr)      if (!map.Contains(i))       map.Enqueue(i);    return map.ToArray(); }   And testing: Code Snippet int [] a = { 6,5,4,3,1,2,1, 2, 3, 4, 5, 6, 5, 6 };       var test = Questions .NoDuplicate1(a); foreach ( var i in test) {    Console .WriteLine(i); } test = Questions .NoDuplicate2(a); foreach ( var i in test) {    Console .WriteLine(i); }   Both approaches had the sequence maintained of the first integer found in the array.

Tech Qu: Intersect two arrays

Write the code to find the intersection of two arrays, a,b.   The code can be very simple (or horribly complex) from the right perspective: Code Snippet public static int [] IntersectionArray( int [] arr, int [] arr2) {    var result = new HashSet < int >();    var map = new HashSet < int >();    foreach ( var i in arr)    //  if (!map.Contains(i))       map.Add(i);    foreach ( var i in arr2)      if (map.Contains(i) ) // && !result.Contains(i))       result.Add(i);    return result.ToArray(); }   I have included some unneeded condition tests as comments above (HashSet does not retain duplicates and it is assumed that an explicit test would be more expensive then letting the hashset do it itself).   Unit testing is trivial Code Snippet int [] a = { 1, 2, 3, 4, 5, 6, 5, 6 }; int [] b = { 3, 4, 3, 4, 3, 4, 3, 4, }; var test = Questions .IntersectionArray(a, b); foreach ( var i in test) {    Console .Writ

Random number generator from binary input

This question is likely if you are dealing with quantum randomizers, etc. It’s irrelevant if there is an appropriate function in the language. You are given a function that generates 0 and 1 with equal probability. Write a function that uses the above function to generate any n(1<=n<=1000) so that probability of producing any number between 1 to 1000 is equal and is 1/1000. The solution is simple and fast using bit shifting (which gives performance, *2 could be used but that will raise flags with many interviewers) Code Snippet static Random _Ran = new Random (); public static int ZeroOne() {    return _Ran.Next(2); } /// <summary> /// We bitshift for optimal performance /// </summary> /// <returns></returns> public static int Random1to1000() {    var num = 0;    var outofrange = true ;    while (outofrange)   {     num = ZeroOne() << 1;      for ( int i = 0; i < 8; i++)     {       num = (num |

The bizarreness of coding questions–it is time to cut the garbage?

There have been a trend in the industry to evolve to pro-forma interviews running off stock questions that are actually rote based and often irrelevant to the position.    For an example that may make sense to you: Asking for any job that require writing emails , the following questions dealing with literacy: What is a Oxford Comma? What is a split infinitive and give me an example of a valid exception to the rule. What is the difference between obtuse and abstruse? What is the collective noun for a group of crows? (murder); quail? (covey); magpies? (tidings), etc If someone fails these questions, people could assert they are low literacy, and thus not qualified. In reality a person that aces these questions may write incomprehensible emails, while someone that funks these questions may write elegant clear emails.   In terms of coding questions, for a C# position you may get asked about single linked lists and how to do an AddBefore or other silliness. Sy

Using Elmah with Azure Table Storage

Article Summary This article will explain how to extend Elmah to log to and view errors from Windows Azure Table Storage.  Introduction Elmah is an exception handling and logging tool that plugs into ASP.NET and ASP.NET MVC applications. When an error is thrown, Elmah grabs all the information including the stack trace, server variables, and query string. Then this information is entered into the data container of your choice. When you want to review these exceptions, the tool provides a web interface to display the errors. Your Windows Azure Usage This article assumes you already have a Windows Azure account and know how to manage data in Azure Table Storage. I use either the Visual Studio Server Explorer or the Azure Storage Explorer ( codeplex ) to look at the tables. A longer list of Storage Viewer applications is referenced at the bottom of this article. Visual Studio Server Explorer Azure Storage Explorer Steps to Connect Elmah to Windows Azure Table Storage T

Tech Qu: Finding the minimum of the maximum difference.

Given 3 arrays A,B,C find three indices i,j,k such that the value of I = max((a-b),(b-c),(c-a)) is minimized. i.e. a = A[i] b = B[j] c = C[k] This is one of those problems that you can accidentally head down a rabbit hole. Remember the KISS principle. Instead of trying to do an elegant solution, write a direct solution and then attempt optimize it if need be.   Code Snippet public static string MinOf3Arrays( int [] a, int [] b, int [] c)     {        var results = "no result" ;        var min = int .MaxValue;        foreach ( var ai in a)          foreach ( var bi in b)            foreach ( var ci in c)           {              var max = Math .Max( Math .Max(ai - bi, bi - ci), ci - ai);              if (max < min)             {               min = max;               results = string .Format( "{3} Min from: A@i={0}, B@j={1}, C@k={2}" , ai, bi, ci, min);                           }           }        ret

Tech Qu: Merge two sorted arrays

Sorted Array Merge Problem: Design an algorithm to merge two sorted positive integer arrays A and B. Size of array A is n and size of array B is m. Array A has m empty blocks(-1) at random places. Merge array B into A such that array A is sorted and does not have empty blocks.   The approach is simple and reminds me of my old tape handling days. Would be fun if someone describes the problem as two data tapes and see where the reader goes.   A good start would be to define test cases (Boundary cases) all of B occurs before any of A. all of B occurs after all of A A simple routine would be to compact A so all of the empty blocks are at the front and then just walk both arrays, picking the smallest number from each array to fill in the resulting array.   Code Snippet public static int ?[] MergeSorted( int ?[] a, int ?[] b) {    var ai = a.Length - 1;    var bi = 0;    var mi=0;    // Move all nulls to end    for ( int i=a.Length-1; i > -1;i--)

Tech Qu: Write a function to do RLE (Run Length Encoding)

Given a string, compress using run-length encoding. Example: Input: aaabbac Output: a3b2ac First Pass – simplistic solution Code Snippet /// <summary>   /// Assuming no digits in string.   /// </summary>   /// <param name="s"></param>   /// <returns></returns>   public static string RLEEncode1( string s)  {     var sb = new StringBuilder ();     int count = 1;     char current = s[0];     for ( int i = 1; i < s.Length; i++)    {       if (current == s[i])      {        count++;      }       else      {         if (count > 1)          sb.AppendFormat( "{1}{0}" , count, current);         else          sb.Append(current);        count = 1;        current = s[i];      }    }     if (count > 1)      sb.AppendFormat( "{1}{0}" , count, current);     else      sb.Append(current);       return sb.ToString();  } A better solution is to assum

Tech Qu: Find the Median/Percentile value of a table

Everyone knows how to find the average of a column, asking to find a median (technically the 50percentile) in TSQL  can be an exercise for some. A simple solution is shown below.   Code Snippet DECLARE @Percentile int = 50 DECLARE @PercentileTop int DECLARE @PercentileValue money SELECT @PercentileTop = count ( 1 )    FROM [SalesLT] . [Product]    WHERE LISTPRICE IS NOT NULL SET @PercentileTop =( @PercentileTop * @Percentile )/ 100    SELECT TOP ( @PercentileTop ) @PercentileValue = [ListPrice]          FROM [SalesLT] . [Product]    WHERE LISTPRICE IS NOT NULL    ORDER BY LISTPRICE SELECT @PercentileValue   The next question would be to encapsulate this for reuse – I will leave that for people to comment on. Let us see how creative our readers can be!

Expanding your language patterns: R

R (“GNU S”) is  a sweet language and environment for statistical computing and graphics. R is similar to the award-winning S system, which was developed at Bell Laboratories by John Chambers et al. It is also very similar to my first taught language APL/360 except it does not require special characters.   You can install it from , there is a Windows version which comes with it’s own UI.   As simple example.  You want to calculate   1/1 +1/2+ …. 1/1000.  A verbose solution may be:   > a1 <- 1:1000 > sum(1/a1) [1] 7.485471   A one-liner (which APL is infamous for) would be: > sum(1/1:1000) [1] 7.485471   You can also do some really interesting stuff, like finding the sum of all the square roots from –1 to -45   >  a1 <- -1:-45 > a2 <- a1+ 0i > sum(sqrt(a2)) [1] 0+204.3985i   Yes, complex number support is native!   Often in programming you end up with a hyped-focused on a part

Tech Qu: Find the numbers that occurs an odd number of times in a huge array of integers.

This is a more complex version of a reported Amazon question , where there is only a single one. There are two questions based on constraints: Minimize the time to get the array of numbers. Minimize the memory requirements. Minimize the time to get the array of numbers: Step 1 The first step of the solution is to use two bit maps : Map A is Int.MaxValue +1 in size Map B is Int.MinValue in size Both are initialized to zero (the default ). Walk the array. If not negative, toggle Map A If negative, take the negative value (you should raise the issue that the language should be tested for the fastest way to do this, i.e. Math.Abs(), using binary operations, x=-x, etc). NOTE: We could use 1 bitmap, but this means that we will need to do an arithmetic operation for 50% of the array. In general bit operations perform better, hence the design should be bit-operation centric. Once the array has been walked, then walk the bitmaps for non-zero values.  T

Test Qu: Division and Remainder

Given two numbers n and m, divide n by m without using the division operator. Return both the integer answer as well as the remainder. This actually can get messy depending on your understanding of “Remainder”. One solution is shown below. Code Snippet public static int DivideWithRemainder( int top, int bottom, out int count)     {       count = 0;        if (bottom == 0)       {          throw new DataException ( "cannot divide by zero" );       }        bool sign = (top > 0 && bottom < 0)        || (top < 0 && bottom > 0);         top = Math .Abs(top);       bottom = Math .Abs(bottom);          while (top > bottom)       {         count++;         top -= bottom;       }        if (sign )       {         count = -count;       }        return top;     }   And for unit test: Avoid the know boundary condition in the 10000 loop Test explicitly for boundary condition afterwards.