Posts

Showing posts with the label Technical Questions

An old SQL Server Interview Question: What are Crow’s Feet?

Image
I recall being asked that question at an interview long ago. In the circles that I had been working we had never used that (academic) term and had been using the diagramming tools in SQL Server Management Studio(SSMS). It was simply what we used. So what are crow’s feet?   It is a diagramming notation which, incidentally, is not supported in SQL Server Management Studio but is supported in third party tools. Since I had been working for Microsoft’s ITG SQL Server Team for several years prior without any third party tools --- I could not return a snappy answer. The origin of this was that the early adapters moved to Oracle, so this because an attitude issue with Microsoft.   Today, crow’s foot notation has become the non-Microsoft industry standard in stead of SSMS infinity key notation. The comical thing is that Microsoft Visio does support crow’s foot notation. A few example tools that uses this notation are: ARIS , System Architect , PowerDesigner , Toad Data Modele...

Tech Qu: The checking your degree questions…

University transcripts are no longer trusted because of grade inflation and even bogus degrees. The result is that often people are asked questions that anyone that has taken a 3rd year computer science course (recently) should be able to answer. Personally, I feel these questions are biased for recent graduates and against those that have been in the industry many years. They are theory centric and not practical center.   On Glassdoor, one contributor says it perfectly: There are many question which will from you university course of Informatics, so worth to renew that knowledge. Many puzzles, and mostly of them you can find in internet. Nothing difficult, just good exam on things which you will never use in real life .   A few examples are: Differences between Array, Linked List, Heap etc You could dive into mechanisms of implementation, or cite a table (i.e. rote learning) such as   Linked list ...

Tech Qu: Some SQL Server Questions

Image
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 CustomerOrde...

Tech Qu: Removing duplicates from an integer array

Image
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 th...

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) {   ...

Random number generator from binary input

Image
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?

Image
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...

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);                           }           }       ...

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

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!

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

Image
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....

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 after...

Test Qu: Some Binary Search Tree Illustrations

The following was toss together for the sake of coding up example questions  (no testing code written because I would prefer to code up a red-black implementation and that’s an exercise). See one of many examples on the web.   Code Snippet using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text;   namespace ConsoleApplication1 {    public class BSTNode   {      /// <summary>      /// Low Value      /// </summary>      public BSTNode LeftNode { get ; set ;}      /// <summary>      /// Low Value      /// </summary>      public BSTNode RightNode { get ; set ; }      /// <summary>      /// Value or Object      /// </summary>      public int Value { get ; set ; }      public object Object { get ; set ; }   }    public class BinarySearchTree   {      private BSTNode _Root;      public BinarySearchTree( BSTNode root)     {     ...

Tech Qu: Create a class and then a 2nd class that both overrides and overload.

A trivial item – but a few folks may get confused with the double “over”.     Code Snippet class MyBase   {      private string cr = "Open Source" ;           public virtual string Copyright()     {        return cr;     }        }    class MyOver : MyBase   {      private string lt = string .Empty;      //overload      public MyOver( string licensedTo)     {       lt = licensedTo;     }      public override string Copyright()     {        return "Company Conf " +lt;     }      // Overload      public string Copyright( string userName)     {        return Copyright()+ " " +userName;     }   }

Tech Qu: Implement a Stack as a Linked List

This is very much a low value question in the C# world because both exists in out standard library. An implementation is shown below. Additional items like Top, IsEmpty are easy adds. Code Snippet public class MyStack <T> : LinkedList <T>   {      public void Push(T item)     {        this .AddFirst(item);     }      public T Pop()     {       T result = this .First();        this .RemoveFirst();        return result;     }      public T Peek()     {        return this .First();     }   } Test Cases Code Snippet var test = new MyStack < int >();     test.Push(1);     test.Push(2);      Console .WriteLine(test.Peek());      Console .WriteLine(test.Pop());      Console .WriteLine(test.Pop()); With the console showing 2,2,1 as expected.