Algorithms, Data Structures, Collections Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/category/technology/languages-platforms-object-oriented-observations/csharp/c-collections/ Production Grade Technical Solutions | Data Encryption and Public Cloud Expert Wed, 21 Feb 2024 15:27:47 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.2 https://www.anujvarma.com/wp-content/uploads/anujtech.png Algorithms, Data Structures, Collections Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/category/technology/languages-platforms-object-oriented-observations/csharp/c-collections/ 32 32 Books on Algorithms https://www.anujvarma.com/books-on-algorithms/ https://www.anujvarma.com/books-on-algorithms/#comments Wed, 14 Jun 2017 22:17:51 +0000 http://www.anujvarma.com/?p=4769 Also see my – Problem Books for Pure Math, Physics and Mathematical Physics If you are looking for a recap of computer science algorithmic concepts either for fun or for […]

The post Books on Algorithms appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Also see my – Problem Books for Pure Math, Physics and Mathematical Physics

If you are looking for a recap of computer science algorithmic concepts either for fun or for an upcoming programming interview, look no further than these books.

  • The first one – Data Structures and Algorithms Made Easy –  A great reference and easy to read. This one is a little time consuming, which is why I listed the second option below.
  • The second one – Beginning Algorithms (Wrox Book)is a little more concise and more basic.  Maybe not for the google interview, but for most mid-level tech interviews, I prefer the Wrox book as a refresher.
  • Python Algorithms – by  Hetland. A Press publication. Don’t be put off if python isn’t your first language. The explanation of algorithms in general, itself makes this worth the money.

Summary

Do you have a favorite algorithms book? Please share in the comments.

The post Books on Algorithms appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/books-on-algorithms/feed/ 1
Recursion versus Iteration ( Looping ) https://www.anujvarma.com/recursion-versus-looping/ https://www.anujvarma.com/recursion-versus-looping/#respond Mon, 13 Jun 2016 18:39:35 +0000 http://www.anujvarma.com/?p=4233 Overview In general, whatever problem you can solve with Recursion can also be solved with Looping (iteration). It turns out, that for most use cases, Iteration (looping) performs better than […]

The post Recursion versus Iteration ( Looping ) appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Overview

In general, whatever problem you can solve with Recursion can also be solved with Looping (iteration).

It turns out, that for most use cases, Iteration (looping) performs better than Recursion

The problem with recursion, is that small results need to be computed many times. This makes it somewhat inefficient.

Looping can accomplish the same result – without being computationally expensive.

fibonacci

Summary

As you can see, recursion is almost 10,000 times as expensive as Looping. It gets more expensive as the computation increases (as N increases).

Here is the full source code, in C#

Example – Fibonacci  – Using Recursion

 

      private static int RecurseFibonacci(int f)
{
if (f <= 1)
return 1;
else
{
return RecurseFibonacci(f  1) + RecurseFibonacci(f  2);
}
}

Example – Fibonacci  – Using Looping

static int LoopFibonacci(int n)
{
int prev = 1; int first = 1; int next = 1; 

if (n <= 1)
return 1;
else
{
for(int k=2; k<=n; k++)
{
next = first + prev;
first = prev;
prev = next;
} 

return prev;
}
}

   static void Main(string[] args)
{ 

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
int result1  = LoopFibonacci(f);
stopwatch.Stop(); 

// Write hours, minutes and seconds.
            Console.WriteLine(” Computing Fibonacci for N = ” + f);
Console.WriteLine(“Fibonacci Result = ” + result1 + ” Loop Time:” + stopwatch.Elapsed.TotalMilliseconds + ” ms”); 

stopwatch.Start();
int result2 = RecurseFibonacci(f);
stopwatch.Stop();
// Write hours, minutes and seconds.
            Console.WriteLine(“Fibonacci Result = ” + result2 + ” Recursion Time: ” + stopwatch.Elapsed.TotalMilliseconds + ” ms”); 

}

The post Recursion versus Iteration ( Looping ) appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/recursion-versus-looping/feed/ 0
Binary tree (count nodes) interview question https://www.anujvarma.com/binary-tree-count-nodes-interview-question/ https://www.anujvarma.com/binary-tree-count-nodes-interview-question/#respond Tue, 28 Apr 2015 21:43:32 +0000 http://www.anujvarma.com/?p=3037 Given a LEFT and a RIGHT property that returns the underlying LEFT tree and the underlying RIGHT tree respectively, find the total count of the nodes in the tree. class […]

The post Binary tree (count nodes) interview question appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Given a LEFT and a RIGHT property that returns the underlying LEFT tree and the underlying RIGHT tree respectively, find the total count of the nodes in the tree.
class BinaryTree<T>
{
private BinaryTree<T> left;
private BinaryTree<T> right;
public int CountNodes<T>(this IBinaryTree<T> tree)
    {
        // TODO: What goes here?
     }    
}
Solution
public int CountNodes<T>(this IBinaryTree<T> t) 
 {
   return  1 +  t.left.CountNodes() + t.right.CountNodes();
 }
 
      

The post Binary tree (count nodes) interview question appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/binary-tree-count-nodes-interview-question/feed/ 0
Swapping without a temp variable https://www.anujvarma.com/swapping-without-a-temp-variable/ https://www.anujvarma.com/swapping-without-a-temp-variable/#respond Mon, 31 Oct 2011 23:36:11 +0000 http://www.anujvarma.com/swapping-without-a-temp-variable/ Everyone is familiar with the basic swap – using a temporary variable static void RegularSwapUsingTempVariable(ref int a, ref int b) { int temp = a; a = b; b = […]

The post Swapping without a temp variable appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Everyone is familiar with the basic swap – using a temporary variable

 static void RegularSwapUsingTempVariable(ref int a, ref int b)
 {
           int temp = a;
           a = b;
           b = temp;
 }

The same swap can be done without the use of a temporary variable.  One needs to simply store the differences of the two values in each variable – and use a simple algorithms as shown below:

static void SwapWithoutTempVariable(ref int a, ref int b)
      {
          // first, set a to the difference a-b 
          a = a - b;
          // next, add b to the difference - thereby being left with a
          b = a + b;
          // now remove a from the original difference - leaving just b
          a = b - a;
      }

Summary

Next time you want to stump someone, ask them to write a simple swap. Chances are 100% that they will use a temporary variable to write it. Now, ask them to write it without using any temporary variable.

The post Swapping without a temp variable appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/swapping-without-a-temp-variable/feed/ 0
The Under-Appreciated Hash Function–Illustrated using a Birthday Lookup https://www.anujvarma.com/the-under-appreciated-hash-functionillustrated-using-a-birthday-lookup/ https://www.anujvarma.com/the-under-appreciated-hash-functionillustrated-using-a-birthday-lookup/#respond Thu, 28 Jul 2011 20:10:54 +0000 http://www.anujvarma.com/the-under-appreciated-hash-functionillustrated-using-a-birthday-lookup/ Overview Arrays are superfast. Simply becasue the exact location (index) of the element is provided. What if we could tie that index to the actual value of the data being […]

The post The Under-Appreciated Hash Function–Illustrated using a Birthday Lookup appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Overview

Arrays are superfast. Simply becasue the exact location (index) of the element is provided.

What if we could tie that index to the actual value of the data being stored? If there was a way to UNIQUELY map each value being stored to an index, that would allow array-speed lookups on virtually ALL data.

That’s what a hash function is. While 100% uniqueness will not be guaranteed, it is still a worthwhile function to try and find for each data set.

Consider the simplest example of the birthday problem – given a day and a month – you need to look up the name of a person who has a birthday on that date.

For simplicity, let us assume that there are only 365 people in our data set and each one has a unique birthday.

The LinkedList Solution:

If you were to use a linked list to store each person’s name and birthdate, you would have to visit an average of 183 nodes to perform this simple lookup.

The Hashtable Solution:

With a hashtable, this average is reduced to ONE!

That’s right – just ONE direct lookup retrieves the appropriate person’s name – all the lookup does is take the input (day and month) – computes its hash (which gives it a number between 1 and 365) – and uses that as an index into an array containing the names. So – if my birthday is on the 14th of Feb  (which happens to be the 45th day of the year) – the hashing function should correctly return the number 45. My storage array’s 45th element – Array[45] – should contain my name.  No traversing down any list – just one simple, straight to the point, lookup.

What is the catch? The trick, of course, lies in finding a way to map all those days and months to a unique number.

Somehow – we need to go from two numbers (the MONTH – running from 1 through 12 – and the DAY – running from 1 through 31) – and come up with a single number running from 1 through 365 (or 0 through 364 to appease arrays in most languages).

Here is a simple way to accomplish this feat.

Step 1 : Store a simple static array containing 12 entries – for the days elapsed  when you reach the FIRST of each month. So for January 1st – this entry would be 0 for February 1st, it would be 31 (since 31 days have elapsed before you get to Feb 1st), for March 1st, it would be 60. And so on for each of the 12 months.

Step 2: Given a birthday (month and day) – say Feb 14th  – all you do is look up the February days elapsed from step 1  (which is 31) – and add 14 to it – to give you 45.  For March 10th, you would take 60 and add 10 to it – to give you 70. All we are saying here is that March 10th is the 70th day of the year and Feb 14th is the 45th day of the year.

int CreateHashUsingDayandMonth(int day, int month)
{
  int[12] days_elapsed = {0, 31, 60, 121, 152, 182, 213, 244, 274, 305, 335};

  return days_elapsed[month] + day
}

This is an example of a perfect hashing function – since we assumed our data set was nice enough that there were no duplicates.  If we have duplicates, we run into ‘collisions’ which are the norm rather than the exception.  More on those in a future post.

For now,  the beauty of the simple hashing function above is that we have reduced the average number of lookups from 183 to 1 !

Don’t you think that hashes (hash functions) are under-appreciated? When was the last time you thanked a hash function?

The post The Under-Appreciated Hash Function–Illustrated using a Birthday Lookup appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/the-under-appreciated-hash-functionillustrated-using-a-birthday-lookup/feed/ 0
The Under-Appreciated Hash Function–Illustrated using a Birthday Lookup https://www.anujvarma.com/the-under-appreciated-hash-function%e2%80%93illustrated-using-a-birthday-lookup/ https://www.anujvarma.com/the-under-appreciated-hash-function%e2%80%93illustrated-using-a-birthday-lookup/#respond Thu, 14 Jul 2011 20:52:31 +0000 http://www.anujvarma.com/?p=254 Considering the amount of time they have saved mankind, Hash-functions are among the most under-appreciated gems of computing.  A hashing function will typically, using just a SINGLE lookup – retrieve […]

The post The Under-Appreciated Hash Function–Illustrated using a Birthday Lookup appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Considering the amount of time they have saved mankind, Hash-functions are among the most under-appreciated gems of computing.  A hashing function will typically, using just a SINGLE lookup – retrieve a deeply buried patient record or a stock quote or a bank balance.  Just a single lookup! It is the FASTEST structure possible when it comes to looking up (searching for) stuff (after all, it is hard to do better than JUST ONE lookup). The non-hash structures used for searching for stuff, typically take much longer. A hash function saves not just minutes but HOURS on every single search. 

Consider the simplest example of the birthday problem – given a day and a month – you need to look up the name of a person who has a birthday on that date.

For simplicity, let us assume that there are only 365 people in our data set and each one has a unique birthday.

The LinkedList Solution:

If you were to use a linked list to store each person’s name and birthdate, you would have to visit an average of 183 nodes to perform this simple lookup.

The Hashtable Solution:

With a hashtable, this average is reduced to ONE!

That’s right – just ONE direct lookup retrieves the appropriate person’s name – all the lookup does is take the input (day and month) – computes its hash (which gives it a number between 1 and 365) – and uses that as an index into an array containing the names. So – if my birthday is on the 14th of Feb  (which happens to be the 45th day of the year) – the hashing function should correctly return the number 45. My storage array’s 45th element – Array[45] – should contain my name.  No traversing down any list – just one simple, straight to the point, lookup.

What is the catch? The trick, of course, lies in finding a way to map all those days and months to a unique number.

Somehow – we need to go from two numbers (the MONTH – running from 1 through 12 – and the DAY – running from 1 through 31) – and come up with a single number running from 1 through 365 (or 0 through 364 to appease arrays in most languages).

Here is a simple way to accomplish this feat.

Step 1 : Store a simple static array containing 12 entries – for the days elapsed  when you reach the FIRST of each month. So for January 1st – this entry would be 0 for February 1st, it would be 31 (since 31 days have elapsed before you get to Feb 1st), for March 1st, it would be 60. And so on for each of the 12 months.

Step 2: Given a birthday (month and day) – say Feb 14th  – all you do is look up the February days elapsed from step 1  (which is 31) – and add 14 to it – to give you 45.  For March 10th, you would take 60 and add 10 to it – to give you 70. All we are saying here is that March 10th is the 70th day of the year and Feb 14th is the 45th day of the year.

int CreateHashUsingDayandMonth(int day, int month)
{
  int[12] days_elapsed = {0, 31, 60, 121, 152, 182, 213, 244, 274, 305, 335};

  return days_elapsed[month] + day
}

This is an example of a perfect hashing function – since we assumed our data set was nice enough that there were no duplicates.  If we have duplicates, we run into ‘collisions’ which are the norm rather than the exception.  More on those in a future post.

For now,  the beauty of the simple hashing function above is that we have reduced the average number of lookups from 183 to 1 !

Don’t you think that hashes (hash functions) are under-appreciated? When was the last time you thanked a hash function?

The post The Under-Appreciated Hash Function–Illustrated using a Birthday Lookup appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]> https://www.anujvarma.com/the-under-appreciated-hash-function%e2%80%93illustrated-using-a-birthday-lookup/feed/ 0