Skip to content

Commit

Permalink
Merge branch 'master' into twostrings
Browse files Browse the repository at this point in the history
  • Loading branch information
RyanFehr authored Jul 5, 2018
2 parents a7313f5 + 215c150 commit 3da3937
Show file tree
Hide file tree
Showing 21 changed files with 1,511 additions and 19 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
Problem: https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array/problem
C# Language Version: 6.0
.Net Framework Version: 4.7
Tool Version : Visual Studio Community 2017
Thoughts :
1. Sort the input
2. Iterate the sorted input and track the absolute difference between adjacent elements
3. Print the minimum difference thus found.

Time Complexity: O(n log(n)) //actually it is O(n log(n)) + O(n)
Space Complexity: O(n) //need to store all the elements in memory for processing as sorting using quick sort is also involved.

*/
using System;
using System.Collections.Generic;
using System.Linq;

class Solution
{
static void Main(string[] args)
{
//No need to capture the size of array. We can use array's length property instead.
Console.ReadLine();
var arr_temp = Console.ReadLine().Split(' ');
var inputNumbers = Array.ConvertAll(arr_temp, int.Parse);
//contributes O(n log(n)) complexity
inputNumbers = QuickSort2(inputNumbers);
var minimumDiff = Math.Abs(inputNumbers[0] - inputNumbers[1]);
//contributes O(n) complexity
for (var i = 1; i < inputNumbers.Length - 1; i++)
minimumDiff = Math.Min(Math.Abs(inputNumbers[i] - inputNumbers[i + 1]), minimumDiff);

Console.WriteLine(minimumDiff);
}

static int[] QuickSort2(int[] arr)
{
var pivot = arr[0];
var smallerItems = new List<int>();
var equalItems = new List<int>();
var biggerItems = new List<int>();
var outputArr = new int[arr.Length];

equalItems.Add(arr[0]);

for (var i = 1; i < arr.Length; i++)
{
if (arr[i] < pivot)
smallerItems.Add(arr[i]);
else if (arr[i] > pivot)
{
biggerItems.Add(arr[i]);
}
else
equalItems.Add(arr[i]);
}

if (smallerItems.Count > 1)
smallerItems = QuickSort2(smallerItems.ToArray()).ToList();

if (biggerItems.Count > 1)
biggerItems = QuickSort2(biggerItems.ToArray()).ToList();

var j = 0;

foreach (var item in smallerItems)
outputArr[j++] = item;

foreach (var item in equalItems)
outputArr[j++] = item;

foreach (var item in biggerItems)
outputArr[j++] = item;

return outputArr;
}
}
128 changes: 128 additions & 0 deletions Algorithms/Search/Gridland Metro/Solution.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/*
Problem: https://www.hackerrank.com/challenges/gridland-metro/problem
C# Language Version: 6.0
.Net Framework Version: 4.7
Tool Version : Visual Studio Community 2017
Thoughts :
- Create a map for for each row number where a track is present. If there are more than one track on a given row it will become a list. e.g.
Row Number List of Tracks
1 (2,3), (1,4), (3,6)
2 (2,6)
3 (1,4), (3,6)
- Start with a total cell counter which keeps a track of total possible cells in the grid land matrix. So for 4x4 matrix it will be 16.
- Deduct the number of cells occupied by every track from the total cell counter.

Gotchas:
- If the list of tracks on any row > 1 then overlapping intervals need to be merged.
- Total cell counter must be of long type. Value n*m can't be held in Int32. It will result in range overflow.


Time Complexity: O(k) //k is number of tracks. Time complexity involved in sorting and merging the ranges of tracks on a given row can be ignored
Space Complexity: O(k) //k is number of tracks. We need to store the map of ranges of tracks

*/

using System;
using System.Collections.Generic;
using System.Linq;
class Solution
{
static void Main(string[] args)
{
var arr_temp = Console.ReadLine().Split(' ');
var rowCount = long.Parse(arr_temp[0]);
var colCount = long.Parse(arr_temp[1]);
var trackCount = int.Parse(arr_temp[2]);
var totalEmptyCells = rowCount * colCount;
var trackMap = new Dictionary<int, List<Tuple<int, int>>>();
//this for loop contributes O(k)
for (int i = 0; i < trackCount; i++)
{
arr_temp = Console.ReadLine().Split(' ');
var rowNumber = int.Parse(arr_temp[0]);
var colStart = int.Parse(arr_temp[1]);
var colEnd = int.Parse(arr_temp[2]);

//processing logic.
if (trackMap.ContainsKey(rowNumber))
{
var existingList = trackMap[rowNumber];
existingList.Add(Tuple.Create(colStart, colEnd));
}
else
trackMap.Add(rowNumber, new List<Tuple<int, int>> { Tuple.Create(colStart, colEnd) });
}


//now again iterate through all the track ranges map in each row and decrement totalEmptyCells variable

//this for loop contributes O(k) in worst case or < O(k) if there are overalapping tracks.
foreach (var item in trackMap)
{
var trackRanges = item.Value;
if (trackRanges.Count == 1)
totalEmptyCells -= trackRanges[0].Item2 - trackRanges[0].Item1 + 1;
else
{
//merge the ranges of overlapping tracks
trackRanges = MergeOverlappingIntervals(trackRanges);
//after merging do the subtraction sturff
foreach (var trackRange in trackRanges)
totalEmptyCells -= trackRange.Item2 - trackRange.Item1 + 1;
}
}
Console.WriteLine(totalEmptyCells);
}

private static List<Tuple<int, int>> MergeOverlappingIntervals(List<Tuple<int, int>> trackRanges)
{
trackRanges = QuickSortTuples(trackRanges);
var stack = new Stack<Tuple<int, int>>();
stack.Push(trackRanges[0]);
for (var i = 1; i < trackRanges.Count; i++)
{
var tupleOnTop = stack.Peek();
if (tupleOnTop.Item2 < trackRanges[i].Item1)
stack.Push(trackRanges[i]);//no overlap
else if (tupleOnTop.Item2 < trackRanges[i].Item2)
{
var poppedTuple = stack.Pop();
stack.Push(Tuple.Create(poppedTuple.Item1, trackRanges[i].Item2));
}
}
return stack.ToList();
}

static List<Tuple<int, int>> QuickSortTuples(List<Tuple<int, int>> inputList)
{
var pivot = inputList[0];
var smallerItems = new List<Tuple<int, int>>();
var equalItems = new List<Tuple<int, int>>();
var biggerItems = new List<Tuple<int, int>>();
var sortedList = new List<Tuple<int, int>>();

equalItems.Add(inputList[0]);

for (var i = 1; i < inputList.Count; i++)
{
if (inputList[i].Item1 < pivot.Item1)
smallerItems.Add(inputList[i]);
else if (inputList[i].Item1 > pivot.Item1)
biggerItems.Add(inputList[i]);
else
equalItems.Add(inputList[i]);
}

if (smallerItems.Count > 1)
smallerItems = QuickSortTuples(smallerItems);

if (biggerItems.Count > 1)
biggerItems = QuickSortTuples(biggerItems);

sortedList.AddRange(smallerItems);
sortedList.AddRange(equalItems);
sortedList.AddRange(biggerItems);

return sortedList;
}
}
114 changes: 114 additions & 0 deletions Algorithms/Search/Hackerland Radio Transmitters/Solution.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
Problem: https://www.hackerrank.com/challenges/hackerland-radio-transmitters/problem
C# Language Version: 7.0
.Net Framework Version: 4.7
Tool Version : Visual Studio Community 2017
Thoughts :

- the first idea is to sort the house numbers in the input array using quick sort.
- Secondly we need to keep in mind that any installed radio transmitter will cover houses both on left and right
hand side. I've done the handling for it inside for loop. See below house numbers which are already sorted for k = 2:

2 4 5 6 7 9 11 12

If we install radio transmitter at house # 4 then it will cover house #s 2,4,5,6
_ ↓ _ _
2 4 5 6 7 9 11 12

Next can be installed at house # 9 which will take care of 7,9 & 11
_ ↓ _
2 4 5 6 7 9 11 12

Last transmitter can be installed at house # 12 which will take care of house # 12 only.
2 4 5 6 7 9 11 12


Time Complexity: O(n log(n)) it involves two parts. Sorting using quick sort which is nlog(n) and one iteration of order O(n)
Space Complexity: O(n) We need to store the sorted input array in memory to iterate through it.

*/
using System.Collections.Generic;
using System.Linq;
using System;

class Solution
{
static void Main(string[] args)
{
var arr_temp = Console.ReadLine().Split(' ');
//No need to capture the number of houses. We can use array's length property instead.
var transmissionRange = int.Parse(arr_temp[1]);
var transmitterCount = 0;
arr_temp = Console.ReadLine().Split(' ');
var houseLocations = Array.ConvertAll(arr_temp, int.Parse);

//sort the array: Contributes O(nlog(n))
houseLocations = QuickSort2(houseLocations);

//this loop contributes O(n)
for (var i = 0; i < houseLocations.Length;)
{
var counter = 1;
while (i + counter < houseLocations.Length
&& houseLocations[i + counter] - houseLocations[i] <= transmissionRange)
counter++;

transmitterCount++;//install a transmitter
i = i + counter - 1; //array index of the house where we just installed a transmitter

//now find the index of next house which is out of range from the transmitter we've just installed above.
counter = 1;
while (i + counter < houseLocations.Length
&& houseLocations[i + counter] - houseLocations[i] <= transmissionRange)
counter++;

i += counter;

}
Console.WriteLine(transmitterCount);
}

static int[] QuickSort2(int[] arr)
{
var pivot = arr[0];
var smallerItems = new List<int>();
var equalItems = new List<int>();
var biggerItems = new List<int>();
var outputArr = new int[arr.Length];

equalItems.Add(arr[0]);

for (var i = 1; i < arr.Length; i++)
{
if (arr[i] < pivot)
smallerItems.Add(arr[i]);
else if (arr[i] > pivot)
{
biggerItems.Add(arr[i]);
}
else
equalItems.Add(arr[i]);
}

if (smallerItems.Count > 1)
smallerItems = QuickSort2(smallerItems.ToArray()).ToList();

if (biggerItems.Count > 1)
biggerItems = QuickSort2(biggerItems.ToArray()).ToList();

var j = 0;

foreach (var item in smallerItems)
outputArr[j++] = item;

foreach (var item in equalItems)
outputArr[j++] = item;


foreach (var item in biggerItems)
outputArr[j++] = item;

return outputArr;
}
}
75 changes: 75 additions & 0 deletions Algorithms/Search/Missing Numbers/Solution.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
Problem: https://www.hackerrank.com/challenges/missing-numbers/problem
C# Language Version: 6.0
.Net Framework Version: 4.7
Tool Version : Visual Studio Community 2017
Thoughts :

Simple brute force method:

- use a sorted dictionary to keep the frequency of any number which is appearing in arrB.
- then iterate arrA and decrement its frequency in the sorted dictionary lookup
- now iterate the dictionary and print the key whereever the value > 0
- Since it is a sorted dictionary so keys will be in increasing order.

By finding the minimum in arrB method:

- first iterate arrB and find the smallest value
- now maintain two frequence arrays arrFreqB and arrFreqA.
- Again iterate arrB and fill-up arrFreqB so that frequency of smallest value at index 0 and so on.
- Iterate arrA and fill-up freqA so that frequency of smallest value at index 0 and so on.
- Now iterate arrFreqB. If for any position there is a mismatch in corresponding value in arrFreqA then print the
number. Number can be obtained by adding the curent index with smallest value in arrB.

Pivot method (Current implementation)
- Here we take up first element of arrB as our pivot element.
- All the remaining elments in the array can be spread 100 ahead or 100 behind.
- So we take up the frequency array of size 201
- first iterate arrB and fill up the frequency of each number by finding its index w.r.t. pivot element
- Then iterate arrA and decrement the frequency of each number by finding its index w.r.t. pivot element.
- Iterate the frequency array and print the nummber wherever frequency > 0. Number to be printed will have to caculated using pivot and current index.



Time Complexity: O(n) //We need to iterate both the source arrays once.
Space Complexity: O(n) //input numbers need to be stored in array + an array of 200 constant length

*/
using System;

class Solution
{
static void Main(string[] args)
{
//No need to capture the number of items. We'll use for loop to iterate the list items
Console.ReadLine();
var arr_temp = Console.ReadLine().Split(' ');
var arrA = Array.ConvertAll(arr_temp, int.Parse);
//No need to capture the number of items. We'll use for loop to iterate the list items
Console.ReadLine();
arr_temp = Console.ReadLine().Split(' ');
var arrB = Array.ConvertAll(arr_temp, int.Parse);

var frequency = new int[201];
frequency[100] = 1;

var pivot = arrB[0];
for (var i = 1; i < arrB.Length; i++)
{
var diff = arrB[i] - pivot;
frequency[100 + diff]++;
}

for (var i = 0; i < arrA.Length; i++)
{
var diff = arrA[i] - pivot;
frequency[100 + diff]--;
}

for (var i = 0; i < frequency.Length; i++)
{
if (frequency[i] > 0)
Console.Write(string.Format("{0} ", pivot + (i - 100)));
}
}
}
Loading

0 comments on commit 3da3937

Please sign in to comment.