├── .gitattributes
├── .gitignore
├── Anagram
├── AnagramQuestion.csproj
├── Problem
│ └── Anagram.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── Tests
│ ├── AnagramTester.cs
│ └── AnagramTesterInput.cs
└── packages.config
├── ArrayEquals
├── App.config
├── ArrayEquals.cs
├── ArrayEqualsQuestion.csproj
├── Properties
│ └── AssemblyInfo.cs
├── README.md
└── packages.config
├── ArrayPairSumK
├── ArrayPairSumK.csproj
├── CountPairsWithSumSolver.cs
├── CountPairsWithSumTester.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
└── packages.config
├── CTCI-ArraysAndStrings
├── CTCI-ArraysAndStrings.csproj
├── Problems
│ ├── ArrayString_1.cs
│ ├── ArrayString_4.cs
│ └── ArrayString_5.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── Tests
│ ├── ArrayString_1Tester.cs
│ ├── ArrayString_4Tester.cs
│ └── ArrayString_5Tester.cs
└── packages.config
├── CTCI-LinkedList
├── CTCI-LinkedList.csproj
├── Problems
│ ├── LinkedList_1.cs
│ └── LinkedList_2.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── SinglyLinkedList.cs
├── Tests
│ ├── LinkedListCreator.cs
│ ├── LinkedList_1TestInput.cs
│ ├── LinkedList_1Tester.cs
│ ├── LinkedList_2TestInput.cs
│ └── LinkedList_2Tester.cs
└── packages.config
├── ConvertNumberIntoWords
├── ConvertNumberIntoWords.csproj
├── Problem
│ └── NumberToEnglishConverter.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── Tests
│ └── NumberWordTester.cs
└── packages.config
├── CountPossibleDecodings
├── App.config
├── CountPossibleDecodingsQuestion.csproj
├── Problem
│ └── CountPossibleDecodings.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── Tests
│ ├── CountPossibleDecodingsTestInput.cs
│ └── CountPossibleDecodingsTester.cs
└── packages.config
├── DavisStairs
├── DavisStairClimbSolver.cs
├── DavisStairs.csproj
├── DavisStairsTester.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
└── packages.config
├── EggDropTrialQuestion
├── EggDropTrialQuestion.csproj
├── Problem
│ ├── EggDropSolverDynamicProgramming.cs
│ ├── EggDropSolverRecursive.cs
│ ├── IOptimalEggDropTrials.cs
│ └── MinEggDropTrials.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── Tests
│ └── EggDropTrialTest.cs
├── images
│ └── egg-drop-recursive-basics.png
└── packages.config
├── ExcelColumnName
├── App.config
├── ExcelColumnName.cs
├── ExcelColumnNameQuestion.csproj
├── Properties
│ └── AssemblyInfo.cs
├── README.md
└── packages.config
├── Factorial
├── FactorialQuestion.csproj
├── Problem
│ └── Factorial.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── Tests
│ └── FactorialTester.cs
└── packages.config
├── FibonacciQuestion
├── FibonacciQuestion.csproj
├── Problem
│ └── Fibonacci.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── Tests
│ └── FibonacciTester.cs
└── packages.config
├── FirstRepeatedWordInASentence
├── FirstRepeatedWordInASentence.csproj
├── Problem
│ └── FirstRepeatWordFinder.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── Tests
│ ├── FirstRepeatWordFinderTest.cs
│ └── FirstRepeatWordTestInput.cs
└── packages.config
├── InterviewQuestions.sln
├── LICENSE
├── LinkedListMergeSort
├── LinkedListMergeSort.csproj
├── Problem
│ ├── ArrayMergeSorter.cs
│ ├── LinkedList.cs
│ ├── LinkedListMergeSorter.cs
│ └── Node.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── Tests
│ ├── IntArrayMergeSortTestInput.cs
│ ├── IntArrayMergeSortTester.cs
│ └── LinkedListTester.cs
└── packages.config
├── LongestContinuousStringOfRepeatingCharsQuestion
├── LongestContinuousStringOfRepeatingChars.cs
├── LongestContinuousStringOfRepeatingCharsQuestion.csproj
├── LongestContinuousStringOfRepeatingCharsTest.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
└── packages.config
├── LongestIncreasingSubsequence
├── App.config
├── LongestIncreasingSubsequenceQuestion.csproj
├── Problem
│ └── LongestIncreasingSubsequence.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── Tests
│ ├── LongestIncreasingSubsequenceTester.cs
│ └── LongestIncreasingSubsequenceTesterInput.cs
└── packages.config
├── NonRepeatingCharacter
├── App.config
├── FirstNonRepeatingCharacterInStringQuestion.csproj
├── Problem
│ ├── FirstNonRepeatingCharacterInString.cs
│ └── StringsLengths.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── Tests
│ └── FirstNonRepeatingCharInStringTester.cs
└── packages.config
├── OverlappingRectangles
├── App.config
├── OverlappingRectanglesQuestion.csproj
├── Problem
│ ├── OverlappingRectangles.cs
│ ├── PairOfRectangleCoordinates.cs
│ ├── Point.cs
│ └── RectangleCoordinates.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── Tests
│ ├── OverlappingRectangleTest.cs
│ └── OverlappingRectangleTestInput.cs
└── packages.config
├── PermMissingElem
├── PermMissingElem.csproj
├── README.md
├── Solution.cs
└── SolutionTests.cs
├── QueueTaleOfTwoStacks
├── App.config
├── Properties
│ └── AssemblyInfo.cs
├── QueueOfTwoStacks.cs
├── QueueOfTwoStacks1.cs
├── QueueTaleOfTwoStacks.csproj
├── README.md
├── Solution.cs
└── packages.config
├── README.md
├── RemoveDuplicatesArraySorted
├── DuplicateRemover.cs
├── DuplicateRemoverTests.cs
├── Properties
│ └── AssemblyInfo.cs
├── RemoveDuplicatesArraySorted.csproj
└── packages.config
├── RemoveDuplicatesFromSortedArray
├── DuplicateRemovalTests.cs
├── DuplicateRemover.cs
└── RemoveDuplicatesFromSortedArray.csproj
├── ReverseWordsInASentence
├── App.config
├── Problem
│ └── ReverseWordsInASentence.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── ReverseWordsInASentence.csproj
├── Tests
│ ├── ReverseWordsInASentenceTest.cs
│ └── ReverseWordsInASentenceTestInput.cs
└── packages.config
├── RobotGrid
├── App.config
├── Program.cs
├── Properties
│ └── AssemblyInfo.cs
├── RobotGrid.csproj
└── packages.config
├── RotateByKSteps
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── RotateByKSteps.csproj
├── Rotater.cs
├── RotaterTests.cs
└── packages.config
├── ShoppingCheckout
├── Problem
│ └── Checkout.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── ShoppingCheckout.csproj
├── Tests
│ └── CheckoutTester.cs
└── packages.config
├── StackMinimumQuestion
├── Problem
│ └── StackMinQuestion.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── StackMinimumQuestion.csproj
├── Tests
│ └── StackMinTester.cs
└── packages.config
├── SumTree
├── Problem
│ ├── Node.cs
│ └── SumTreeQuestion.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── SumTreeQuestion.csproj
├── Tests
│ └── SumTreeTest.cs
└── packages.config
├── SumTwoNumbers
├── Improved
│ ├── Solution.cs
│ ├── SolutionTestCases.cs
│ └── SolutionTests.cs
├── ListNode.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── Solution.cs
├── SumTwoNumbers.csproj
├── TestHelper.cs
├── TestHelperTest.cs
├── Tests.cs
└── packages.config
├── SwapNodes
├── LinkedList.cs
├── Node.cs
├── NodeSwapper.cs
├── NodeSwapperTests.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.md
├── SwapNodes.csproj
└── packages.config
├── TheMaximumNumberWithAllDigitsInANumber
├── Problem
│ └── MaxNumberFinder.cs
├── Properties
│ └── AssemblyInfo.cs
├── README.txt
├── Tests
│ ├── MaxNumberFinderTest.cs
│ └── MaxNumberFinderTestInput.cs
├── TheMaximumNumberWithAllDigitsInANumber.csproj
└── packages.config
├── TimeComplexity
└── UtopianTree
├── Problem
└── HeightCalculator.cs
├── Properties
└── AssemblyInfo.cs
├── README.md
├── Tests
└── HeightTester.cs
├── UtopianTree.csproj
└── packages.config
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/Anagram/Problem/Anagram.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace AnagramQuestion.Problem
4 | {
5 | public class Anagram
6 | {
7 | ///
8 | /// A word is an anagram of another word if one can be
9 | /// created from the other by simply re-arranging the letters in it
10 | /// dictionary cannot work for words where a letter is repeated multiple times
11 | ///
12 | ///
13 | ///
14 | ///
15 | public static bool isAnagram(string string1, string string2)
16 | {
17 | var str1 = string1.ToLower();
18 | var str2 = string2.ToLower();
19 | if (str1.Length != str2.Length)
20 | {
21 | return false;
22 | }
23 | var dictionary = new Dictionary();
24 | for (int i = 0; i < str1.Length; i++) {
25 | dictionary.Add(str1[i], i + 1);
26 | }
27 | for (int i = 0; i < dictionary.Count; i++) {
28 | if (!dictionary.ContainsKey(str2[i]))
29 | {
30 | return false;
31 | }
32 | }
33 | return true;
34 | }
35 |
36 | ///
37 | /// my alternate solution is to convert lower
38 | /// length check
39 | /// and then sort both strings
40 | /// and compare them
41 | ///
42 | ///
43 | ///
44 | ///
45 | public static bool isAnagramNoDictionary(string string1, string string2)
46 | {
47 | if (string.IsNullOrEmpty(string1) || string.IsNullOrEmpty(string2))
48 | return false;
49 |
50 | if (string1.Length != string2.Length)
51 | {
52 | return false;
53 | }
54 |
55 | foreach (var c in string2)
56 | {
57 | var idx = string1.IndexOf(c);
58 | //char is present in string1
59 | if (idx >= 0)
60 | string1 = string1.Remove(idx, 1);
61 | else
62 | return false;
63 | }
64 |
65 | return string.IsNullOrEmpty(string1);
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/Anagram/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("Anagram")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("Anagram")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("19d8e13b-541e-4041-9cbd-b1edd94f0c56")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Anagram/README.md:
--------------------------------------------------------------------------------
1 | # Anagram
2 |
3 | Given two strings, check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “act” and “tac” are anagram of each other.
4 |
5 | Input:
6 |
7 | The first line of input contains an integer T denoting the number of test cases. Each test case consist of two strings in 'lowercase' only, in a separate line.
8 |
9 | Output:
10 |
11 | Print "YES" without quotes if the two strings are anagram else print "NO".
12 |
13 | Constraints:
14 |
15 | 1 ≤ T ≤ 30
16 |
17 | 1 ≤ |s| ≤ 100
18 |
19 | Example:
20 |
21 | Input:
22 | 2
23 | geeksforgeeks
24 | forgeeksgeeks
25 | allergy
26 | allergic
27 |
28 | Output:
29 | YES
30 | NO
--------------------------------------------------------------------------------
/Anagram/Tests/AnagramTester.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using AnagramQuestion.Problem;
3 |
4 | namespace AnagramQuestionTester.Tests
5 | {
6 | [TestFixture]
7 | public class AnagramTester
8 | {
9 | //[Test, TestCaseSource(typeof(AnagramTesterInput), "TestCases")]
10 | //public bool AnagramTest(string input1, string input2)
11 | //{
12 | // return Anagram.Anagram.isAnagram(input1, input2);
13 | //}
14 |
15 | [Test, TestCaseSource(typeof(AnagramTesterInput), "TestCases")]
16 | public bool AnagramTestNoDictionary(string input1, string input2)
17 | {
18 | return Anagram.isAnagramNoDictionary(input1, input2);
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Anagram/Tests/AnagramTesterInput.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using NUnit.Framework;
3 |
4 | namespace AnagramQuestionTester
5 | {
6 | public class AnagramTesterInput
7 | {
8 | public static IEnumerable TestCases
9 | {
10 | get
11 | {
12 | yield return new TestCaseData("adult", "dulta")
13 | .Returns(true)
14 | .SetName("dulta is an anagram of adult");
15 | yield return new TestCaseData("anagram", "nagaram")
16 | .Returns(true)
17 | .SetName("nagaram is an anagram of anagram"); ;
18 | yield return new TestCaseData("anagram", "kilogram")
19 | .Returns(false)
20 | .SetName("anagram is not an anagram of kilogram");
21 | }
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Anagram/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/ArrayEquals/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/ArrayEquals/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("ArrayEquals")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("ArrayEquals")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("5e3d7836-38a6-4ab5-b23d-c4bc6a6c945d")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/ArrayEquals/README.md:
--------------------------------------------------------------------------------
1 | Given two arrays of equal length, the task is to find if given arrays are equal or not. Two arrays are said to be equal if both of them contain same set of elements, arrangements (or permutation) of elements may be different though.
2 |
3 | Note : If there are repetitions, then counts of repeated elements must also be same for two array to be equal.
4 |
5 | Examples:
6 |
7 | Input : A[] = {1, 2, 5, 4, 0};
8 | B[] = {2, 4, 5, 0, 1};
9 | Output : 1
10 |
11 | Input : A[] = {1, 2, 5};
12 | B[] = {2, 4, 15};
13 | Output : 0
14 |
15 |
16 | Input:
17 | The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer N denoting the size of the array. Then in the next two lines are N space separated values of the array of arrays A[] and B[].
18 |
19 | Output:
20 | For each test case in a new line print 1 if the arrays are equal else print 0.
21 |
22 | Constraints:
23 | 1<=T<=100
24 | 1<=N<=100
25 | 1<=A[],B[]<=1000
26 |
27 | Example:
28 | Input:
29 | 2
30 | 5
31 | 1 2 5 4 0
32 | 2 4 5 0 1
33 | 3
34 | 1 2 5
35 | 2 4 15
36 | Output:
37 | 1
38 | 0
--------------------------------------------------------------------------------
/ArrayEquals/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/ArrayPairSumK/CountPairsWithSumSolver.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace ArrayPairSumK
4 | {
5 | public class CountPairsWithSumSolver
6 | {
7 | ///
8 | /// An interesting solution to finding the number of pairs that add upto a sum
9 | /// Create a map of the element and its occurrences in the array. Requires one full traversal of the array
10 | /// initialize a counter.
11 | /// Traverse the array again but this time, check if the map contains a key sum-element . If it does then increase counter.
12 | /// That means you've found a pair.
13 | /// Now you don't want to count cases where 2 * element is sum, so you exclude it by decrementing the counter that was added.
14 | ///
15 | ///
16 | ///
17 | ///
18 | public static int CountNumberPairsWithSumK(int[] array, int sum)
19 | {
20 | var mapOfNumberCounts = new Dictionary();
21 | //create a map of numbers and their counts
22 | foreach(var element in array)
23 | {
24 | if (mapOfNumberCounts.ContainsKey(element))
25 | {
26 | mapOfNumberCounts[element] = mapOfNumberCounts[element] + 1;
27 | }
28 | else
29 | {
30 | mapOfNumberCounts.Add(element, 1);
31 | }
32 | }
33 | int doubleCounter = 0;
34 | //now iterate again and see if there sum-element exists in the hashmap
35 | foreach(var element in array)
36 | {
37 | if (mapOfNumberCounts.ContainsKey(sum - element))
38 | {
39 | doubleCounter += mapOfNumberCounts[sum - element];
40 | }
41 |
42 | // if we are adding the same number
43 | // soo decrease the counter
44 | if (sum - element == element)
45 | {
46 | doubleCounter--;
47 | }
48 | }
49 | return doubleCounter / 2;
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/ArrayPairSumK/CountPairsWithSumTester.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using NUnit.Framework;
3 |
4 | namespace ArrayPairSumK
5 | {
6 | [TestFixture]
7 | public class CountPairsWithSumTester
8 | {
9 | [Test, TestCaseSource(typeof(CountPairsWithSumTesterInput), "IntArrayAndSumK")]
10 | public int TestCountOfPairsWithSums(int[] array, int sum)
11 | {
12 | return CountPairsWithSumSolver.CountNumberPairsWithSumK(array, sum);
13 | }
14 | }
15 |
16 | public class CountPairsWithSumTesterInput
17 | {
18 | public static IEnumerable IntArrayAndSumK
19 | {
20 | get
21 | {
22 | yield return new TestCaseData(new int[] { 10, 15, 25, 15, 30, 5 }, 35).Returns(2);
23 | yield return new TestCaseData(new int[] { 1, 5, 7, -1, 5 }, 6).Returns(3);
24 | yield return new TestCaseData(new int[] { 1, 1, 1, 1 }, 2).Returns(6);
25 | yield return new TestCaseData(new int[] {10, 12, 10, 15, -1, 7, 6,
26 | 5, 4, 2, 1, 1, 1}, 11).Returns(9);
27 |
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/ArrayPairSumK/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("ArrayPairSumK")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("ArrayPairSumK")]
13 | [assembly: AssemblyCopyright("Copyright © 2018")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("6041ace6-0ce2-4d07-b157-48d06c412785")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/ArrayPairSumK/README.md:
--------------------------------------------------------------------------------
1 | # Count pairs with a given sum in an array
2 |
3 | Given an array of integers, and a number `sum`, find the number of pairs of integers in the array whose sum is equal to `sum`.
4 |
5 | Examples:
6 | Input : arr[] = {1, 5, 7, -1},
7 | sum = 6
8 | Output : 2
9 | Pairs with sum 6 are (1, 5) and (7, -1)
10 |
11 | Input : arr[] = {1, 5, 7, -1, 5},
12 | sum = 6
13 | Output : 3
14 | Pairs with sum 6 are (1, 5), (7, -1) &
15 | (1, 5)
16 |
17 | Input : arr[] = {1, 1, 1, 1},
18 | sum = 2
19 | Output : 6
20 | There are 3! pairs with sum 2.
21 |
22 | Input : arr[] = {10, 12, 10, 15, -1, 7, 6,
23 | 5, 4, 2, 1, 1, 1},
24 | sum = 11
25 | Output : 9
26 |
27 | Expected time complexity O(n)
28 |
29 |
--------------------------------------------------------------------------------
/ArrayPairSumK/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/CTCI-ArraysAndStrings/Problems/ArrayString_4.cs:
--------------------------------------------------------------------------------
1 | namespace CTCI_ArraysAndStrings.Problems
2 | {
3 | public class ArrayString_4
4 | {
5 | ///
6 | /// You are supposed to replace all whitespaces in a string with %20.
7 | /// Use a char array to do this in place.
8 | /// For most string manipluation problems it is easier to traverse from the end of the string
9 | /// to the front. In this case especially so, as we do not have to worry about what character we
10 | /// might overwrite.
11 | /// Although the char array would have space for the additional chars after encoding, we are also
12 | /// presented with the true length of the string. this means that the end of the actual sentence
13 | /// marked by the first null char ('\0') is given to us
14 | /// assumption is that the encoded string willa always fit in the char array
15 | ///
16 | ///
17 | public static void HtmlEncodeSpaces(char[] word, int trueLength)
18 | {
19 | int spaceCounter = 0;
20 | //lets first find out the number of spaces we have to encode
21 | for(int i=0; i < trueLength; i++)
22 | {
23 | if (word[i] == ' ')
24 | spaceCounter++;
25 | }
26 |
27 | // now that we have the number of spaces, we can find the length of encoding string
28 | // this is required to place the moved letters in the right positions
29 | // ' ' is to be converted to %20
30 | // 1 space becomes three characters. 2 spaces 6 and so on.
31 | // but we should find what number of chars should be added.
32 | // (spaceCounter * 3) - spaceCounter
33 | // which evaluates to spaceCounter * 2
34 | int newLength = trueLength + (spaceCounter * 2);
35 | word[newLength] = '\0';
36 | // start iterating from 1 less than trueLength as the last char is for '\0'
37 | for (int i= trueLength - 1; i >= 0; i--)
38 | {
39 | if (word[i] == ' ')
40 | {
41 | word[newLength - 1] = '0';
42 | word[newLength - 2] = '2';
43 | word[newLength - 3] = '%';
44 | newLength = newLength - 3;
45 | }
46 | else
47 | {
48 | word[newLength - 1] = word[i];
49 | newLength = newLength - 1;
50 | }
51 | }
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/CTCI-ArraysAndStrings/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("CTCI-ArraysAndStrings")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("CTCI-ArraysAndStrings")]
13 | [assembly: AssemblyCopyright("Copyright © 2018")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("edbeba2a-07a5-4ae0-9a04-05e8ed0eedf0")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/CTCI-ArraysAndStrings/README.md:
--------------------------------------------------------------------------------
1 | # Arrays and Strings
2 |
3 | ## Problem 1
4 |
5 | Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?
6 |
7 | ## Problem 2
8 |
9 | Implement a function `void reverse(char* str)` in `C` or `C++` which reverses a null-terminated string.
10 |
11 | CANNOT IMPLEMENT C CODE IN `C#`. Can do alternate C# solution.
12 |
13 | ## Problem 3
14 |
15 | Given two strings, write a method to decide if one is a permutation of the other. In other words, if one is an anagram of another.
16 |
17 | ## Problem 4
18 |
19 | Write a method to replace all white-spaces in a string with `%20`. You may assume that the string has sufficient space at the end of the string to hold the additional characters and that you are given the `true` length of the string.
20 |
21 | Please use a character array so that you can perform this operation in place.
22 |
23 | ##### Example:
24 | Input: "Mr John Smith ", 13
25 | Output: "Mr%20John%20Smith"
26 |
27 |
28 | ## Problem 5
29 |
30 | Implement a method to perform basic string compression using the counts of the repeated characters. If the compressed string would not become smaller than the original then your method should return the original string. You can assume that the string has only upper and lower case letters.
31 |
32 | ##### Example:
33 |
34 | Input: aabcccccaaa
35 | Output: a2b1c5a3
--------------------------------------------------------------------------------
/CTCI-ArraysAndStrings/Tests/ArrayString_4Tester.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using NUnit.Framework;
3 | using CTCI_ArraysAndStrings.Problems;
4 |
5 | namespace CTCI_ArraysAndStrings.Tests
6 | {
7 | [TestFixture]
8 | public class ArrayString_4Tester
9 | {
10 | [Test, TestCaseSource(typeof(ArrayString_4TestInput), "EncodeStringInput")]
11 | public void EncodeStringTester(char[] word, int trueLength, char[] expectedResult)
12 | {
13 | ArrayString_4.HtmlEncodeSpaces(word, trueLength);
14 | Assert.AreEqual(expectedResult, word);
15 | }
16 | }
17 |
18 | public class ArrayString_4TestInput
19 | {
20 | public static IEnumerable EncodeStringInput
21 | {
22 | get
23 | {
24 | yield return new TestCaseData(new char[] { 'M', 'r', ' ', 'J', 'o', 'h', 'n', ' ', 'S', 'm', 'i', 't', 'h', '\0', ' ', ' ', ' ', ' ' },
25 | 13, new char[] { 'M', 'r', '%', '2', '0', 'J', 'o', 'h', 'n', '%', '2', '0', 'S', 'm', 'i', 't', 'h', '\0' });
26 |
27 | yield return new TestCaseData(new char[] { 'A', 'r', 'e', ' ', 'y', 'o', 'u', ' ', 'E', 'a', 'k', 'a', '\0', ' ', ' ', ' ', ' ' },
28 | 12, new char[] { 'A', 'r', 'e', '%', '2', '0', 'y', 'o', 'u', '%', '2', '0', 'E', 'a', 'k', 'a', '\0' });
29 |
30 | yield return new TestCaseData(
31 | new char[] { 'A', ' ', 'e', ' ', 'i', ' ', 'o', ' ', 'u', '\0', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
32 | 9,
33 | new char[] { 'A', '%', '2', '0', 'e', '%', '2', '0', 'i', '%', '2', '0', 'o', '%', '2', '0', 'u', '\0' });
34 | }
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/CTCI-ArraysAndStrings/Tests/ArrayString_5Tester.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using NUnit.Framework;
3 | using CTCI_ArraysAndStrings.Problems;
4 |
5 | namespace CTCI_ArraysAndStrings.Tests
6 | {
7 | [TestFixture]
8 | public class ArrayString_5Tester
9 | {
10 | [Test, TestCaseSource(typeof(ArrayString_5TesterInputs), "WordsToCompress")]
11 | public string CompressTest(string word)
12 | {
13 | return ArrayString_5.CompressIfNecessary(word);
14 | }
15 |
16 | [Test, TestCaseSource(typeof(ArrayString_5TesterInputs), "WordsToCompress")]
17 | public string CompressTestWithChecksFirst(string word)
18 | {
19 | return ArrayString_5.CompressIfNecessaryCheckFirst(word);
20 | }
21 | }
22 |
23 | public class ArrayString_5TesterInputs
24 | {
25 | public static IEnumerable WordsToCompress
26 | {
27 | get
28 | {
29 | yield return new TestCaseData("aaaabcccccde").Returns("a4b1c5d1e1");
30 | yield return new TestCaseData("abra").Returns("abra");
31 | yield return new TestCaseData("jaaambulka").Returns("jaaambulka");
32 | yield return new TestCaseData("eeeeaakkkkaaaaannnn").Returns("e4a2k4a5n4");
33 | }
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/CTCI-ArraysAndStrings/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/CTCI-LinkedList/Problems/LinkedList_1.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace CTCI_LinkedList.Problems
4 | {
5 | ///
6 | /// Solutions for removing duplicates from an unsorted singly linked LinkedList.
7 | ///
8 | public class LinkedList_1
9 | {
10 | ///
11 | /// The most straightforward way is to have a map to keep track of elements and occurrence
12 | /// and delete accordingly.
13 | /// This solution being the simplest, may not be accepted by the interviewer.
14 | /// This solution takes O(n) time where n is obviously the number of elements in the linked list.
15 | ///
16 | ///
17 | public static void RemoveDuplicates(SinglyLinkedList head)
18 | {
19 | var valuesMap = new HashSet();
20 | var n = head;
21 | SinglyLinkedList previous = null;
22 | while (n != null)
23 | {
24 | if (valuesMap.Contains(n.Data))
25 | {
26 | previous.Next = n.Next;
27 | }
28 | else
29 | {
30 | valuesMap.Add(n.Data);
31 | previous = n;
32 | }
33 | n = n.Next;
34 | }
35 | }
36 |
37 | ///
38 | /// Now if you are not allowed to use a secondary storage space or buffer to track your duplicates
39 | /// how would you remove duplicates? Sounds crazy right?
40 | /// One of the most common techniques to solve linked list problems is to use two pointers to traverse the list.
41 | /// Now you might just say "hey but that's a buffer right there". I think so too. But CTCI thinks otherwise.
42 | /// The idea is to keep:
43 | /// * one pointer at the node in context, the one you are checking if it has duplicates
44 | /// * the other pointer goes through the remaining elements to check if there is a duplicate
45 | /// That does sound easy enough.
46 | /// This way the time complexity is O(n^2)
47 | /// space complexity is O(1)
48 | ///
49 | ///
50 | public static void RemoveDuplicatesWithoutBuffer(SinglyLinkedList head)
51 | {
52 | if (head == null)
53 | {
54 | return;
55 | }
56 |
57 | var current = head;
58 | while (current != null)
59 | {
60 | SinglyLinkedList runner = current;
61 | while (runner.Next != null)
62 | {
63 | // do we have a duplicate?
64 | if (runner.Next.Data == current.Data)
65 | {
66 | // reset the pointer - basically what delete would do
67 | runner.Next = runner.Next.Next;
68 | }
69 | else
70 | {
71 | runner = runner.Next;
72 | }
73 | }
74 | current = current.Next;
75 | }
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/CTCI-LinkedList/Problems/LinkedList_2.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace CTCI_LinkedList.Problems
4 | {
5 | ///
6 | /// Implement an algorithm to find the k'th to the last element of a singly linked list.
7 | /// In a singly linked list you can only traverse in one direction.
8 | /// So when asked to print the penultimate elment, you have to travel from the first to the penultimate element
9 | /// And you also need a way to identify that it is the penultimate or in this case, a more general, k'th element
10 | /// from the end.
11 | ///
12 | /// Also keep in mind that the size of the linked list is not always known. This would have made the algorithm easy to implement
13 | ///
14 | public class LinkedList_2
15 | {
16 |
17 | ///
18 | /// A recursive solution to print the kth to the last element in a linked list
19 | /// Here we do not return the node, however we just print the value.
20 | /// Why recurse?
21 | /// When a recursive function executes, it keeps calling itself till it hits the base case
22 | /// and then returns backwards, helping us seemingly traverse the linked list backwards
23 | /// It returns the number of the node in the linked list from the last
24 | ///
25 | ///
26 | ///
27 | ///
28 | public static int PrintKthElementRecursive(SinglyLinkedList node, int k, ref int kthElementValue)
29 | {
30 | if (node == null)
31 | return 0;
32 |
33 | int i = PrintKthElementRecursive(node.Next, k, ref kthElementValue) + 1;
34 | //print this node's data if i is the kth element
35 | if (i == k)
36 | {
37 | kthElementValue = node.Data;
38 | Console.WriteLine(node.Data);
39 | }
40 | return i;
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/CTCI-LinkedList/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("CTCI-LinkedList")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("CTCI-LinkedList")]
13 | [assembly: AssemblyCopyright("Copyright © 2018")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("6ccee05a-70c9-4ae6-b497-74c300106e56")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/CTCI-LinkedList/README.md:
--------------------------------------------------------------------------------
1 | # Cracking the Coding Interview Series - Linked List Problems
2 |
3 | I have decided to solve the problems in the CTCI book. Every chapter will be a different project in the solution.
4 | This is the one on LinkedLists and I am hoping to tackle all the 7 linked list questions that can possibly be solved in C#.
5 |
6 | ## Duplicate Removal
7 |
8 | Write a program to remove duplicate nodes from an unsorted linked list.
9 |
10 | Followup
11 |
12 | How would you achieve this if a temporary buffer was not allowed?
13 |
14 | Solutions in `LinkedList_1.cs`
15 |
16 | ## Value of kth to the last element
17 |
18 | Implement an algorithm to find the k'th to the last element of a singly linked list.
19 |
20 | Solutions in `LinkedList_2.cs`
21 |
22 | ## Delete a node in the middle
23 |
24 | Implement an algorithm to delete a node in the middle of a singly linked list, give only acess to that node.
25 |
26 | Solutions in `LinkedList_3.cs`
27 |
28 |
--------------------------------------------------------------------------------
/CTCI-LinkedList/SinglyLinkedList.cs:
--------------------------------------------------------------------------------
1 | using System.Text;
2 |
3 | namespace CTCI_LinkedList
4 | {
5 | ///
6 | /// Simplest implementation of LinkedList as given in CTCI
7 | ///
8 | public class SinglyLinkedList
9 | {
10 | public SinglyLinkedList Next = null;
11 | public int Data;
12 |
13 | public SinglyLinkedList(int d)
14 | {
15 | Data = d;
16 | }
17 |
18 | ///
19 | /// add d to the end of the linked list.
20 | ///
21 | ///
22 | public void AppendToTail(int d)
23 | {
24 | var end = new SinglyLinkedList(d);
25 | var node = this;
26 | while(node.Next != null)
27 | {
28 | node = node.Next;
29 | }
30 | node.Next = end;
31 | }
32 |
33 | ///
34 | /// Delete val from the linked list that starts at head
35 | /// You are relying on the garbage collector to clear unreferenced elements
36 | /// not sure I like this way, I prefer my delete method in the LinkedList merge sort project
37 | ///
38 | ///
39 | ///
40 | ///
41 | public SinglyLinkedList Delete(SinglyLinkedList head, int val)
42 | {
43 | var n = head;
44 | // check existing element
45 | if (n.Data == val)
46 | {
47 | return head.Next;
48 | }
49 |
50 | //check the remaining elements
51 | while (n.Next != null)
52 | {
53 | if (n.Next.Data == val)
54 | {
55 | n.Next = n.Next.Next;
56 | return head;
57 | }
58 | n = n.Next;
59 | }
60 | return head;
61 | }
62 |
63 | public static string ToString(SinglyLinkedList head)
64 | {
65 | var iterator = head;
66 | var stringRep = new StringBuilder();
67 | while (iterator != null)
68 | {
69 | stringRep.Append(iterator.ToString());
70 | //forgot this at first. infinite loop
71 | iterator = iterator.Next;
72 | }
73 | return stringRep.ToString();
74 | }
75 |
76 | public override string ToString()
77 | {
78 | return string.Format("{0}->{1}", Data, (Next == null) ? "NULL" : "");
79 | }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/CTCI-LinkedList/Tests/LinkedListCreator.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace CTCI_LinkedList.Tests
4 | {
5 | public class LinkedListCreator
6 | {
7 | public static SinglyLinkedList CreateSinglyLinkedListFromGenericList(List inputList)
8 | {
9 | SinglyLinkedList node = null;
10 | for (int i = 0; i < inputList.Count; i++)
11 | {
12 | if (i == 0)
13 | {
14 | node = new SinglyLinkedList(inputList[i]);
15 | }
16 | else
17 | {
18 | node.AppendToTail(inputList[i]);
19 | }
20 | }
21 | return node;
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/CTCI-LinkedList/Tests/LinkedList_1TestInput.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using System.Collections.Generic;
3 | using NUnit.Framework;
4 |
5 | namespace CTCI_LinkedList.Tests
6 | {
7 | public class LinkedList_1TestInput
8 | {
9 | public static IEnumerable UnsortedLinkedListTestData
10 | {
11 | get
12 | {
13 | yield return
14 | new TestCaseData(
15 | new List { 90, 10, 8, 15, 8, 20, 85, 77, 89, 91, 90 },
16 | "90->10->8->15->20->85->77->89->91->NULL");
17 |
18 | yield return
19 | new TestCaseData(
20 | new List { 13, 10, 8, 15, 15, 10, 85, 77, 91, 77, 13 },
21 | "13->10->8->15->85->77->91->NULL");
22 |
23 | yield return
24 | new TestCaseData(
25 | new List { 13, 10, 8, 10, 15, 85, 85, 77, 91, 13, 91 },
26 | "13->10->8->15->85->77->91->NULL");
27 |
28 | yield return
29 | new TestCaseData(
30 | new List { 13, 13, 13, 13, 10, 13, 13, 10, 13, 13 },
31 | "13->10->NULL");
32 |
33 | yield return
34 | new TestCaseData(
35 | new List { 13, 13, 13, 13, 13 },
36 | "13->NULL");
37 | }
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/CTCI-LinkedList/Tests/LinkedList_1Tester.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using System.Collections.Generic;
3 | using CTCI_LinkedList.Problems;
4 |
5 | namespace CTCI_LinkedList.Tests
6 | {
7 | [TestFixture]
8 | public class LinkedList_1Tester
9 | {
10 | [Test(Description = "Remove Duplicates from an unsorted LinkedList with the help of a buffer data structure"),
11 | TestCaseSource(typeof(LinkedList_1TestInput), "UnsortedLinkedListTestData")]
12 | public void TestRemovalOfDuplicatesWithBuffer(List inputList, string expected)
13 | {
14 | SinglyLinkedList node = LinkedListCreator.CreateSinglyLinkedListFromGenericList(inputList);
15 | LinkedList_1.RemoveDuplicates(node);
16 | Assert.AreEqual(expected, SinglyLinkedList.ToString(node));
17 | }
18 |
19 | [Test(Description = "Remove Duplicates from an unsorted LinkedList without the help of a buffer data structure"),
20 | TestCaseSource(typeof(LinkedList_1TestInput), "UnsortedLinkedListTestData")]
21 | public void TestRemovalOfDuplicatesWithoutBuffer(List inputList, string expected)
22 | {
23 | SinglyLinkedList node = LinkedListCreator.CreateSinglyLinkedListFromGenericList(inputList);
24 | LinkedList_1.RemoveDuplicatesWithoutBuffer(node);
25 | Assert.AreEqual(expected, SinglyLinkedList.ToString(node));
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/CTCI-LinkedList/Tests/LinkedList_2TestInput.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using System.Collections.Generic;
3 | using NUnit.Framework;
4 |
5 | namespace CTCI_LinkedList.Tests
6 | {
7 | public class LinkedList_2TestInput
8 | {
9 | public static IEnumerable KthToTheLastElementInALinkedListTestCases
10 | {
11 | get
12 | {
13 | yield return
14 | new TestCaseData(
15 | new List { 13, 12, 15}, //list of elements
16 | 2, //kth the last element
17 | 12); //expected value
18 |
19 | yield return
20 | new TestCaseData(
21 | new List { 13, 12, 15 }, //list of elements
22 | 1, //kth the last element
23 | 15); //expected value
24 |
25 | yield return
26 | new TestCaseData(
27 | new List { 13, 12, 15 }, //list of elements
28 | 3, //kth the last element
29 | 13); //expected value
30 |
31 | yield return
32 | new TestCaseData(
33 | new List { 13,12 },
34 | 2, 13);
35 |
36 | yield return
37 | new TestCaseData(
38 | new List { 5, 25, 15, 9, 16, 12, 17, 18, 21},
39 | 3,
40 | 17);
41 | }
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/CTCI-LinkedList/Tests/LinkedList_2Tester.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using System.Collections.Generic;
3 | using CTCI_LinkedList.Problems;
4 |
5 | namespace CTCI_LinkedList.Tests
6 | {
7 | [TestFixture]
8 | public class LinkedList_2Tester
9 | {
10 | [Test, TestCaseSource(typeof(LinkedList_2TestInput), "KthToTheLastElementInALinkedListTestCases")]
11 | public void LinkedList_2RecursiveRefConsoleWrite(List inputList, int kToTheLastElementNumber, int expectedResult)
12 | {
13 | SinglyLinkedList node = LinkedListCreator.CreateSinglyLinkedListFromGenericList(inputList);
14 | int kToTheLastElementValue = 0;
15 | LinkedList_2.PrintKthElementRecursive(node, kToTheLastElementNumber, ref kToTheLastElementValue);
16 | Assert.AreEqual(expectedResult, kToTheLastElementValue);
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/CTCI-LinkedList/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/ConvertNumberIntoWords/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("ConvertNumberIntoWords")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("ConvertNumberIntoWords")]
13 | [assembly: AssemblyCopyright("Copyright © 2018")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("1fec05ba-0651-4d07-aa5b-967351b30a94")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/ConvertNumberIntoWords/README.md:
--------------------------------------------------------------------------------
1 | # Convert number into words
2 |
3 | Write a program that converts a given integer number into words.
4 |
5 |
6 | For example, if `1234` is given as input, output should be `one thousand two hundred thirty four`.
7 | For the sake of simplicity, let us consider that the input will be a number `x` such that `0 < x < 9999`
--------------------------------------------------------------------------------
/ConvertNumberIntoWords/Tests/NumberWordTester.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using ConvertNumberIntoWords.Problem;
3 | using NUnit.Framework;
4 |
5 | namespace ConvertNumberIntoWordsTester.Tests
6 | {
7 | [TestFixture]
8 | public class NumberWordTester
9 | {
10 | [Test, TestCaseSource(typeof(NumberWordTestInput), "NumberAndWordsTestData")]
11 | public string NumberInEnglishTest(int number)
12 | {
13 | return NumberToEnglishConverter.ToEnglish(number);
14 | }
15 | }
16 | public class NumberWordTestInput
17 | {
18 | public static IEnumerable NumberAndWordsTestData
19 | {
20 | get
21 | {
22 | yield return new TestCaseData(1000).Returns("one thousand").SetName("One Thousand");
23 | yield return new TestCaseData(1001).Returns("one thousand one").SetName("One Thousand and one");
24 | yield return new TestCaseData(1101).Returns("one thousand one hundred one").SetName("One Thousand one hundred and one");
25 | yield return new TestCaseData(1110).Returns("one thousand one hundred ten").SetName("One Thousand one hundred and ten");
26 | yield return new TestCaseData(1111).Returns("one thousand one hundred eleven").SetName("one thousand one hundred eleven");
27 | yield return new TestCaseData(1120).Returns("one thousand one hundred twenty").SetName("one thousand one hundred twenty");
28 | yield return new TestCaseData(21).Returns("twenty one").SetName("twenty one");
29 | yield return new TestCaseData(19).Returns("nineteen").SetName("nineteen");
30 | yield return new TestCaseData(10).Returns("ten").SetName("ten");
31 | yield return new TestCaseData(5).Returns("five").SetName("five");
32 | }
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/ConvertNumberIntoWords/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/CountPossibleDecodings/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/CountPossibleDecodings/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("CountPossibleDecodings")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("CountPossibleDecodings")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("0310d9ce-e7aa-4093-9cf2-12760ee6afcb")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/CountPossibleDecodings/README.md:
--------------------------------------------------------------------------------
1 | # Encrypted Message
2 |
3 | ## Problem description
4 |
5 | A top secret message containing letters from `A-Z` is being encoded to numbers using the following mapping:
6 |
7 | 'A' -> 1
8 | 'B' -> 2
9 | ...
10 | 'Z' -> 26
11 |
12 | You are an FBI agent. You have to determine the total number of ways that message can be decoded.
13 |
14 | Note: An empty digit sequence is considered to have one decoding.
15 |
16 | * It may be assumed that the input contains valid digits from 0 to 9
17 | * If there are leading 0’s, extra trailing 0’s and two or more consecutive 0’s then it is an invalid string.
18 |
19 | ## Online Resources
20 |
21 | * Solution and explanation: https://www.geeksforgeeks.org/count-possible-decodings-given-digit-sequence/
22 | * https://www.topcoder.com/community/data-science/data-science-tutorials/dynamic-programming-from-novice-to-advanced/#!
23 | * https://www.hackerrank.com/domains/algorithms/dynamic-programming
24 |
25 | ## Example
26 |
27 | Given encoded message "123", it could be decoded as:
28 |
29 | * `"ABC" (1 2 3)`
30 | * `"LC" (12 3)`
31 | * `"AW" (1 23)`
32 |
33 | So in total there are 3 ways of decoding the message.
34 |
35 | ### Input
36 |
37 | First line contains the test cases T. 1<=T<=1000
38 | Each test case have two lines
39 | First is length of string N. 1<=N<=40
40 | Second line is string S of digits from '0' to '9' of N length.
41 |
42 | ### Sample
43 |
44 | #### Input
45 |
46 | 2
47 | 3
48 | 123
49 | 4
50 | 2563
51 |
52 | #### Output
53 |
54 | 3
55 | 2
56 |
--------------------------------------------------------------------------------
/CountPossibleDecodings/Tests/CountPossibleDecodingsTestInput.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using System.Collections;
3 |
4 | namespace CountPossibleDecodingsTester.Tests
5 | {
6 | public class CountPossibleDecodingsTestInput
7 | {
8 | public static IEnumerable TestCases
9 | {
10 | get
11 | {
12 | yield return new TestCaseData("1234").Returns(3);
13 | yield return new TestCaseData("1202").Returns(1);
14 | yield return new TestCaseData("675356291270936062618792").Returns(0);
15 | yield return new TestCaseData("123").Returns(3);
16 | yield return new TestCaseData("103").Returns(1);
17 | yield return new TestCaseData("23759228973").Returns(4);
18 | yield return new TestCaseData("05279196").Returns(0);
19 | }
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/CountPossibleDecodings/Tests/CountPossibleDecodingsTester.cs:
--------------------------------------------------------------------------------
1 | using CountPossibleDecodingsQuestion.Problem;
2 | using NUnit.Framework;
3 |
4 | namespace CountPossibleDecodingsTester.Tests
5 | {
6 | [TestFixture]
7 | public class CountPossibleDecodingsTester
8 | {
9 | [Test, TestCaseSource(typeof(CountPossibleDecodingsTestInput), "TestCases")]
10 | public int CountPossibleDecodingsTestRecursive(string inputString)
11 | {
12 | return CountPossibleDecodings.NumberOfDecodedStringsRecursive(inputString);
13 | }
14 |
15 | [Test, TestCaseSource(typeof(CountPossibleDecodingsTestInput), "TestCases")]
16 | public int CountPossibleDecodingsTestNonRecursive(string inputString)
17 | {
18 | return CountPossibleDecodings.NumberOfDecodedStringsNonRecursive(inputString);
19 | }
20 |
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/CountPossibleDecodings/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/DavisStairs/DavisStairClimbSolver.cs:
--------------------------------------------------------------------------------
1 | namespace DavisStairs
2 | {
3 | public class DavisStairClimbSolver
4 | {
5 | public static int NumberOfWaysToClimbStepsRecursive(int n)
6 | {
7 | if (n == 0)
8 | return 0;
9 | //base case when 1 step
10 | if (n == 1 || n == 2)
11 | {
12 | return n;
13 | }
14 | var totalNumberOfWays = 1;
15 | totalNumberOfWays += NumberOfWaysToClimbStepsRecursive(n - 1) + NumberOfWaysToClimbStepsRecursive(n - 2) + NumberOfWaysToClimbStepsRecursive(n - 3);
16 | return totalNumberOfWays;
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/DavisStairs/DavisStairsTester.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using NUnit.Framework;
3 |
4 | namespace DavisStairs
5 | {
6 | [TestFixture]
7 | public class DavisStairsTester
8 | {
9 | [Test, TestCaseSource(typeof(DavisStairsTester), "RecursiveTestInput")]
10 | public int DavisStairsRecursiveTester(int numberOfSteps)
11 | {
12 | return DavisStairClimbSolver.NumberOfWaysToClimbStepsRecursive(numberOfSteps);
13 | }
14 |
15 | public static IEnumerable RecursiveTestInput
16 | {
17 | get
18 | {
19 | yield return new TestCaseData(3).Returns(4);
20 | yield return new TestCaseData(2).Returns(2);
21 | yield return new TestCaseData(1).Returns(1);
22 | yield return new TestCaseData(0).Returns(0);
23 | yield return new TestCaseData(4).Returns(8);
24 | yield return new TestCaseData(5).Returns(15);
25 | yield return new TestCaseData(6).Returns(28);
26 | }
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/DavisStairs/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("DavisStairs")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("DavisStairs")]
13 | [assembly: AssemblyCopyright("Copyright © 2018")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("708b40a7-58b7-467c-a09e-e33a1b51715a")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/DavisStairs/README.md:
--------------------------------------------------------------------------------
1 | # Davis climbing stairs
2 |
3 | Davis is the name of a very curious child.
4 |
5 | He lives in a large mansion with his parents and they have plenty of stairs to get to the different floors.
6 |
7 | Davis loves to climb stairs. Being a small child, climbing stairs help him look at the world from a higher position.
8 |
9 | But being an only child, he finds very different games to play on the stairs. One such game is what Davis calls, `3 ways of climbing stairs`.
10 |
11 | His rules are simple:
12 | * He can climb a stair of `n` steps in three different ways
13 | * climb 1 step at a time
14 | * climb 2 steps at a time
15 | * climb 3 steps at a time.
16 |
17 | Now could you write a program that can find out all possible ways in which Davis can climb `n` steps in a stair?
18 |
19 | ## Input
20 |
21 | `n` - the number of steps to climb
22 |
23 | Note:
24 | There are various flavours of this problem.
25 | Some of them give you a number of stairs, `x` and each of them would have `n` steps.
26 | The question could be to find the number of ways to climb each stair.
27 |
28 |
29 | ## Output
30 |
31 | The total number of ways Davis can climb the stairs.
32 |
33 | ## Example inputs and outputs
34 |
35 | If Davis had to climb `1` step, there is only `1` way to do it. Climb one step.
36 |
37 | If Davis had to climb `2` steps, he has two ways to do it:
38 | * Climb 1 step and then another.
39 | * Climb 2 steps in one go.
40 | * A set based representation: `[{1, 1}, {2}]`
41 | * That is a total of `2` ways to climb
42 |
43 | If Davis had to climb `3` steps, he could:
44 | * `[{1, 1, 1}, {1, 2}, {2, 1}, {3}]`
45 | * That is a total of `4` ways to climb
46 |
47 | ## Online resources
48 |
49 | There are a variety of problems that are similar to this one.
50 | * [GeeksForGeeks - Number of ways to get to the n'th step](https://www.geeksforgeeks.org/count-ways-reach-nth-stair/)
51 | * [Hackerrank - Davis staircase](https://www.hackerrank.com/challenges/ctci-recursive-staircase/problem)
52 | * [TutorialHorizon - Stair climbing puzzle](http://algorithms.tutorialhorizon.com/dynamic-programming-stairs-climbing-puzzle/)
53 |
54 | ## Tests
55 |
56 | As the number of projects in this solution is growing like crazy, I would like to keep tests and question for a problem in the same project from now on.
57 |
58 | I will be moving other test projects into the question project as I go.
59 |
60 | ## Solution
61 |
62 | The easiest way to solve this is by recursion.
63 |
64 | We know that the child can climb stairs in three ways. The child gets to make that choice at every step.
65 |
66 | * If the child decides to take `1` step, then we have to find number of ways to climb `n-1 steps + 1`.
67 | * If the child decides to climb `2` steps, then we have to find number of ways to climb `n-2 steps + 1`.
68 | * If the child decides to climb `3` steps, then we have to find number of ways to climb `n-3 steps + 1`.
69 |
70 | Thus total number of ways to climb `n` steps would be:
71 |
72 | numberOfWays(n-1) + numberOfWays(n-2) + numberOfWays(n-3) + 1
73 |
74 |
--------------------------------------------------------------------------------
/DavisStairs/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/EggDropTrialQuestion/Problem/EggDropSolverRecursive.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace EggDropTrialQuestion.Problem
4 | {
5 | ///
6 | /// This is a recursion based solution for finding
7 | /// the optimal number of egg drops required to find the highest floor from where
8 | /// an egg can be dropped safely without cracking.
9 | /// This is the slowest performing solution. Keep that in mind when you choose values for
10 | /// testing this solution
11 | ///
12 | public class EggDropSolverRecursive : IOptimalEggDropTrials
13 | {
14 | ///
15 | /// If the egg breaks:
16 | /// * the problem then reduces to numberOfEggs - 1, numberOfFloors - 1
17 | ///
18 | /// If the egg doesn't break:
19 | /// * The problem then continues with the same number of eggs. The number of floors remaining is what matters.
20 | /// This becomes numberOfFloors - currentFloor
21 | ///
22 | /// This is a very slow solution as there are several recursive calls and many of them repeated calls for the same values.
23 | ///
24 | ///
25 | ///
26 | ///
27 | public int FindOptimalNumberOfDrops(int numberOfEggs, int numberOfFloors)
28 | {
29 | // the base case
30 | if (numberOfFloors == 0 || numberOfFloors == 1 || numberOfEggs == 1)
31 | {
32 | return numberOfFloors;
33 | }
34 | //set
35 | var minimum = int.MaxValue;
36 |
37 | //find it for every floor
38 | for (int floor=1; floor<=numberOfFloors; floor++)
39 | {
40 | minimum = Math.Min(minimum,
41 | (1 + Math.Max(FindOptimalNumberOfDrops(numberOfEggs, numberOfFloors - floor),
42 | FindOptimalNumberOfDrops(numberOfEggs - 1, floor - 1))
43 | ));
44 | }
45 | return minimum;
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/EggDropTrialQuestion/Problem/IOptimalEggDropTrials.cs:
--------------------------------------------------------------------------------
1 | namespace EggDropTrialQuestion.Problem
2 | {
3 | interface IOptimalEggDropTrials
4 | {
5 | int FindOptimalNumberOfDrops(int numberOfEggs, int numberOfFloors);
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/EggDropTrialQuestion/Problem/MinEggDropTrials.cs:
--------------------------------------------------------------------------------
1 | namespace EggDropTrialQuestion.Problem
2 | {
3 | public class MinEggDropTrials
4 | {
5 | public static int GetMinimumDropTrials()
6 | {
7 | return 1;
8 | }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/EggDropTrialQuestion/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("EggDropTrialQuestion")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("EggDropTrialQuestion")]
13 | [assembly: AssemblyCopyright("Copyright © 2018")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("c788eae6-d9dd-473f-a551-62dfd2ee2689")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/EggDropTrialQuestion/README.md:
--------------------------------------------------------------------------------
1 | # Egg Drop puzzle
2 |
3 | ## Introduction
4 |
5 | The following is a description of the instance of this famous puzzle involving n=2 eggs and a building with k=36 floors.
6 |
7 | So we want to know which floors in a 36-story building are safe to drop eggs from. We first make a few assumptions:
8 |
9 | * An egg that survives a fall can be used again for a drop test.
10 | * A broken egg must be discarded - no point in dropping a broken egg again.
11 | * The effect of a fall is the same for all eggs - all eggs are created equal.
12 | * If an egg breaks when dropped from one floor, then it would definitely break if dropped from a higher floor.
13 | * If an egg survives a fall from a floor, then it would survive a fall from a lower floor.
14 | * It is not ruled out that the first-floor windows break eggs, nor is it ruled out that the 36th-floor do not cause an egg to break.
15 |
16 | In this problem you have to find the minimum number of trials required to find where n eggs would break in a building of k floors.
17 |
18 | ## Online Resources
19 |
20 | * One of the best video descriptions of the problem can be watched here: [Ted Ed Video on Youtube](https://www.youtube.com/watch?v=NGtt7GJ1uiM).
21 |
22 | * For more details on the problem you could also check out [Dynamic Programming on Wikipedia](https://en.wikipedia.org/wiki/Dynamic_programming#Egg_dropping_puzzle).
23 |
24 | * Another great explanation of the problem description can be found here: [Brilliant.Org - Egg Drop Problem Explained](https://brilliant.org/wiki/egg-dropping/#2-eggs-100-floors)
25 |
26 | ## Solutions
27 |
28 | There are plenty of ways to solve this problem.
29 |
30 | * Recursive method
31 | * Dynamic programming method
32 | * Recursion in combination with binary search
33 |
34 | ### Recursive solution
35 |
36 | 
37 |
38 | #### Pseudo code:
39 |
40 | ```python
41 | def drops(n,h):
42 | if(n == 1 or k == 0 or k == 1):
43 | return k
44 | end if
45 |
46 | minimum = ∞
47 |
48 | for x = 1 to h:
49 | minimum = min(minimum,
50 | 1 + max(drops(n - 1, x - 1), drops(n, h - x))
51 | )
52 | end for
53 |
54 | return minimum
55 | ```
56 |
57 | Solution Implemented in `EggDropSolverRecrusive`.
58 |
59 |
--------------------------------------------------------------------------------
/EggDropTrialQuestion/Tests/EggDropTrialTest.cs:
--------------------------------------------------------------------------------
1 | using EggDropTrialQuestion.Problem;
2 | using NUnit.Framework;
3 |
4 | namespace EggDropTrialTester.Tests
5 | {
6 | [TestFixture]
7 | public class EggDropTrialTest
8 | {
9 | [Test]
10 | public void EggDropRecursionTest_1()
11 | {
12 | var minNumberOfTrials = new EggDropSolverRecursive().FindOptimalNumberOfDrops(2, 10);
13 | Assert.AreEqual(4, minNumberOfTrials);
14 | }
15 |
16 | [Test]
17 | public void EggDropDynamicProgrammingTest_1()
18 | {
19 | var minNumberOfTrials = new EggDropSolverDynamicProgramming().FindOptimalNumberOfDrops(2, 100);
20 | Assert.AreEqual(14, minNumberOfTrials);
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/EggDropTrialQuestion/images/egg-drop-recursive-basics.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lonelydev/InterviewQuestions/65fc7d0d7305444eb8ec7a012782ef4c901dee94/EggDropTrialQuestion/images/egg-drop-recursive-basics.png
--------------------------------------------------------------------------------
/EggDropTrialQuestion/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/ExcelColumnName/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/ExcelColumnName/ExcelColumnName.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace ExcelColumnNameQuestion
6 | {
7 | public class ExcelColumnName
8 | {
9 | public static void Main(string[] args)
10 | {
11 | var numOfTests = Console.ReadLine();
12 | int numberOfTests = int.Parse(numOfTests);
13 | var listOfColNumbers = new List();
14 | while(numberOfTests > 0)
15 | {
16 | var colNum = Console.ReadLine();
17 | var columnNumber = int.Parse(colNum);
18 | listOfColNumbers.Add(columnNumber);
19 | numberOfTests--;
20 | }
21 | foreach(var colNum in listOfColNumbers)
22 | {
23 | Console.WriteLine(GetColumnName(colNum));
24 | }
25 | }
26 |
27 | public static string GetColumnName(int num)
28 | {
29 | var colName = new StringBuilder();
30 | while (num>0)
31 | {
32 | int remainder = num % 26;
33 | if(remainder == 0)
34 | {
35 | colName.Append("Z");
36 | num = (num / 26) - 1;
37 | }else
38 | {
39 | colName.Append((char)(remainder + 65 - 1));
40 | num = num / 26;
41 | }
42 | }
43 | var colNameString = colName.ToString();
44 | var colNameCharArray = colNameString.ToCharArray();
45 | Array.Reverse(colNameCharArray);
46 | return string.Join("",colNameCharArray);
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/ExcelColumnName/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("ExcelColumnName")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("ExcelColumnName")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("5ff14875-31ce-44b7-93d3-1efeccc2075f")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/ExcelColumnName/README.md:
--------------------------------------------------------------------------------
1 | Given a positive integer, return its corresponding column title as appear in an Excel sheet.
2 | MS Excel columns has a pattern like A, B, C, … ,Z, AA, AB, AC,…. ,AZ, BA, BB, … ZZ, AAA, AAB ….. etc.
3 | In other words, column 1 is named as “A”, column 2 as “B”, column 27 as “AA”.
4 |
5 | Input:
6 |
7 | The first line of each input consists of the test cases. And, the second line consists of a number N.
8 |
9 | Output:
10 |
11 | In each separate line print the corresonding column title as it appears in an Excel sheet.
12 |
13 | Constraints:
14 |
15 | 1 ≤ T ≤ 70
16 | 1 ≤ N ≤ 4294967295
17 |
18 | Example:
19 |
20 | Input:
21 |
22 | 2
23 | 28
24 | 13
25 |
26 | Output:
27 |
28 | AB
29 | M
30 |
31 |
--------------------------------------------------------------------------------
/ExcelColumnName/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/Factorial/Problem/Factorial.cs:
--------------------------------------------------------------------------------
1 | namespace FactorialQuestion.Problem
2 | {
3 | public class Factorial
4 | {
5 | ///
6 | /// Calculate factorial
7 | /// if (n == 1) return 1;
8 | /// if (n==0) return 1;
9 | /// factorial(n) = n * factorial(n-1);
10 | ///
11 | ///
12 | ///
13 | public static int FactorialRecursive(int n)
14 | {
15 | if (n == 0) return 1;
16 | if (n == 1) return 1;
17 | return (n * FactorialRecursive(n - 1));
18 | }
19 |
20 | ///
21 | /// Although this is tail recursion, I don't think .NET currently supports optimization
22 | /// of such a method.
23 | ///
24 | ///
25 | ///
26 | ///
27 | public static int FactorialRecursiveOptimized(int n, int factorial = 1)
28 | {
29 | if (n == 0 || n == 1) return factorial;
30 | return FactorialRecursiveOptimized(n - 1, n * factorial);
31 | }
32 |
33 | ///
34 | /// An iterative take on factorial solution
35 | /// factorial = n * n-1 * n-2 * n-3
36 | ///
37 | ///
38 | ///
39 | public static int FactorialIterative(int n)
40 | {
41 | if (n == 0 || n == 1) return 1;
42 | int iterator = n;
43 | int factorial = 1;
44 | while (iterator > 1)
45 | {
46 | factorial = factorial * iterator;
47 | iterator--;
48 | }
49 | return factorial;
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Factorial/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("Factorial")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("Factorial")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("77d249ab-c8e8-4530-99fb-d75e91000a64")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Factorial/README.md:
--------------------------------------------------------------------------------
1 | Calculate the factorial for a given number.
2 |
3 | Input:
4 | The first line contains an integer 'T' denoting the total number of test cases. In each test cases, it contains an integer 'N'.
5 |
6 |
7 | Output:
8 | In each seperate line output the answer to the problem.
9 |
10 |
11 | Constraints:
12 | 1<=T<=19
13 | 0<=N<=18
14 |
15 |
16 | Example:
17 | Input:
18 | 1
19 | 1
20 |
21 | Output:
22 | 1
--------------------------------------------------------------------------------
/Factorial/Tests/FactorialTester.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using FactorialQuestion.Problem;
3 |
4 | namespace FactorialTester.Tests
5 | {
6 | [TestFixture]
7 | public class FactorialTester
8 | {
9 | [TestCase(1, 0)]
10 | [TestCase(1, 1)]
11 | [TestCase(2, 2)]
12 | [TestCase(120, 5)]
13 | public void FactorialRecursiveTest1(int expected, int input)
14 | {
15 | var factorial = Factorial.FactorialRecursive(input);
16 | Assert.AreEqual(expected, factorial);
17 | }
18 |
19 | [TestCase(1, 0)]
20 | [TestCase(1, 1)]
21 | [TestCase(2, 2)]
22 | [TestCase(120, 5)]
23 | public void FactorialRecursiveTest2(int expected, int input)
24 | {
25 | var factorial = Factorial.FactorialIterative(input);
26 | Assert.AreEqual(expected, factorial);
27 | }
28 |
29 | [TestCase(1, 0)]
30 | [TestCase(1, 1)]
31 | [TestCase(2, 2)]
32 | [TestCase(120, 5)]
33 | public void FactorialRecursiveTest3(int expected, int input)
34 | {
35 | var factorial = Factorial.FactorialRecursiveOptimized(input);
36 | Assert.AreEqual(expected, factorial);
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Factorial/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/FibonacciQuestion/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("FibonacciQuestion")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("FibonacciQuestion")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("1bc2d3a0-a4a2-4ca2-8911-a80ce779f4ad")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/FibonacciQuestion/README.md:
--------------------------------------------------------------------------------
1 | Write a piece of code to create a Fibonacci sequence using recursion.
2 | Write a piece of code to create a Fibonacci sequence using the iterative method.
3 | The Fibonacci Sequence is the series of numbers:
4 | 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
5 | The next number is found by adding up the two numbers before it.
6 | The 2 is found by adding the two numbers before it(1+1)
7 | The 3 is found by adding the two numbers before it(1+2),
8 | And the 5 is (2+3),
9 | and so on!
10 |
--------------------------------------------------------------------------------
/FibonacciQuestion/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/FirstRepeatedWordInASentence/Problem/FirstRepeatWordFinder.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace FirstRepeatedWordInASentence.Problem
4 | {
5 | public class FirstRepeatWordFinder
6 | {
7 | public static string FirstRepeatedWord(string sentence)
8 | {
9 | var wordRepCounter = new HashSet();
10 | var delimiters = new char[] { ' ', ',', ':', '-', '.', '\t' };
11 | string firstRepeatWord = null;
12 | foreach (var word in sentence.Split(delimiters))
13 | {
14 | if (string.IsNullOrEmpty(word) || string.IsNullOrWhiteSpace(word))
15 | continue;
16 | if (wordRepCounter.Contains(word))
17 | {
18 | firstRepeatWord = word;
19 | break;
20 | }
21 | else
22 | {
23 | wordRepCounter.Add(word);
24 | }
25 | }
26 | return firstRepeatWord;
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/FirstRepeatedWordInASentence/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("FirstRepeatedWordInASentence")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("FirstRepeatedWordInASentence")]
13 | [assembly: AssemblyCopyright("Copyright © 2018")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("74ac33e6-0130-4d4a-96ce-0f8e0e67a9a5")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/FirstRepeatedWordInASentence/README.md:
--------------------------------------------------------------------------------
1 | # First Repeated Word
2 |
3 | A sentence is a group of words. A word is a sequence of characters or letters `a-zA-Z`.
4 | Words are delimited by spaces or non-leter characters like `',', ':', '-', '.', '\t'`.
5 |
6 | A repeated word is when a word occurs more than once in a sentence provided the comparison is case sensitive.
7 | For example, `had != Had`.
8 |
9 | Given a sentence as a string, find the first repeated word in the string.
10 |
11 | The sentence will always have a repeated word.
12 |
--------------------------------------------------------------------------------
/FirstRepeatedWordInASentence/Tests/FirstRepeatWordFinderTest.cs:
--------------------------------------------------------------------------------
1 | using FirstRepeatedWordInASentence.Problem;
2 | using NUnit.Framework;
3 |
4 | namespace FirstRepeatedWordInASentenceTester.Tests
5 | {
6 | [TestFixture]
7 | public class FirstRepeatWordFinderTest
8 | {
9 | [Test, TestCaseSource(typeof(FirstRepeatWordTestInput), "RepeatedWordSentences")]
10 | public string FirstRepeatedWordTest(string sentence)
11 | {
12 | return FirstRepeatWordFinder.FirstRepeatedWord(sentence);
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/FirstRepeatedWordInASentence/Tests/FirstRepeatWordTestInput.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using NUnit.Framework;
3 |
4 | namespace FirstRepeatedWordInASentenceTester.Tests
5 | {
6 | class FirstRepeatWordTestInput
7 | {
8 | public static IEnumerable RepeatedWordSentences
9 | {
10 | get
11 | {
12 | yield return new TestCaseData("This, is:a a sent-ence with-with a repeated word. Are you ready? for this!?")
13 | .Returns("a").SetName("Sentence with tabs, space, comma, hyphen, question mark, exclamation and period");
14 | yield return new TestCaseData("This, this is a wonderful wonderful repeated word sentence.")
15 | .Returns("wonderful").SetName("Test if it understands case sensitive repeats");
16 | yield return new TestCaseData("multi-multi word word in in a a sentence.")
17 | .Returns("multi").SetName("Repeats separated by -");
18 | yield return new TestCaseData("multi:multi word word in in a a sentence.")
19 | .Returns("multi").SetName("Repeats separated by :");
20 | yield return new TestCaseData("multimulti word, word in in a a sentence.")
21 | .Returns("word").SetName("Repeats separated by ,");
22 | yield return new TestCaseData("multimulti word word in in a a sentence.")
23 | .Returns("word").SetName("Repeats separated by tab");
24 | }
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/FirstRepeatedWordInASentence/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/LinkedListMergeSort/Problem/ArrayMergeSorter.cs:
--------------------------------------------------------------------------------
1 | namespace LinkedListMergeSort.Problem
2 | {
3 | public class ArrayMergeSorter
4 | {
5 | ///
6 | /// an example of merge sort of integer arrays first
7 | ///
8 | ///
9 | public static void MergeSortIntArray(int[] inputArray)
10 | {
11 | var size = inputArray.Length;
12 | if (size < 2)
13 | return;
14 | var middle = size / 2;
15 | var leftArraySize = middle;
16 | var rightArraySize = size - middle;
17 | var leftArray = new int[middle];
18 | var rightArray = new int[rightArraySize];
19 | for(int i=0; i
34 | /// Replaces elements in dest array with merged result of source1 and source2
35 | ///
36 | ///
37 | ///
38 | ///
39 | private static void MergeArrays(int[] source1, int[] source2, int[] dest)
40 | {
41 | int i = 0;
42 | int j = 0;
43 | int k = 0;
44 | while (i < source1.Length && j < source2.Length)
45 | {
46 | if (source1[i] < source2[j])
47 | {
48 | dest[k++] = source1[i++];
49 | }
50 | else
51 | {
52 | dest[k++] = source2[j++];
53 | }
54 | }
55 | //now fill in the remaining
56 | while (i < source1.Length)
57 | {
58 | dest[k++] = source1[i++];
59 | }
60 | while (j < source2.Length)
61 | {
62 | dest[k++] = source2[j++];
63 | }
64 | }
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/LinkedListMergeSort/Problem/Node.cs:
--------------------------------------------------------------------------------
1 | namespace LinkedListMergeSort.Problem
2 | {
3 | public class Node
4 | {
5 | public int? Data { get; set; }
6 | public Node Next { get; set; }
7 | public Node(int data)
8 | {
9 | Data = data;
10 | Next = null;
11 | }
12 |
13 | public Node()
14 | {
15 | Data = null;
16 | Next = null;
17 | }
18 |
19 | public override string ToString()
20 | {
21 | return string.Format("{0}->{1}", Data, (Next == null) ? "NULL" : "");
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/LinkedListMergeSort/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("LinkedListMergeSort")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("LinkedListMergeSort")]
13 | [assembly: AssemblyCopyright("Copyright © 2018")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("c6226cb8-76f1-476f-a13e-c0f4f44490fd")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/LinkedListMergeSort/README.md:
--------------------------------------------------------------------------------
1 | # Merge Sort
2 |
3 | There are several sorting algorithms and **merge sort** is just one of them.
4 | It uses a [Divide and Conquer](https://en.wikipedia.org/wiki/Divide_and_conquer_algorithm) strategy to sorting. What that means is given a set of objects, merge sort attempts to sort the set by dividing the set into smaller groups and sorting each individual group by applying the same divide strategy recursively.
5 |
6 | That might have been a lot of words to understand the concept.
7 | Let us look at it using an example.
8 |
9 | ## Algorithm
10 |
11 | Conceptually, a merge sort works as follows:
12 |
13 | 1. Divide the unsorted list into `n` sublists, each containing 1 element (a list of 1 element is considered sorted).
14 | 1. Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining. This will be the sorted list.
15 |
16 | ## Complexity analysis
17 |
18 | When sorting `n` objects merge sort has a worst case complexity of `O(n log n)`.
19 |
20 | I wouldn't want to repeat the wonderful analysis done at [Khan Academy](https://www.khanacademy.org/computing/computer-science/algorithms/merge-sort/a/analysis-of-merge-sort). Please refer their analysis and you will know how the value is derived.
21 |
22 | ## Problems:
23 |
24 | I thought I'd take this opportunity to implement merge sort for different types of data structures.
25 |
26 | * ArrayMergeSort - sorts and integer array in ascending order using merge sort
27 | * LinkedListMergeSort - sorts a linked list with integers in ascending order.
--------------------------------------------------------------------------------
/LinkedListMergeSort/Tests/IntArrayMergeSortTestInput.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using NUnit.Framework;
3 |
4 |
5 | namespace LinkedListMergeSortTester
6 | {
7 | internal class IntArrayMergeSortTestInput
8 | {
9 | public static IEnumerable TestCases
10 | {
11 | get
12 | {
13 | yield return new TestCaseData(new int[] { 10, 22, 9, 33, 21, 50, 41, 60, 80 })
14 | .Returns(new int[] { 9, 10, 21, 22, 33, 41, 50, 60, 80 }).SetName("The standard unsorted");
15 | yield return new TestCaseData(new int[] { 99, 89, 79, 69, 59, 49, 39, 29, 19, 9 })
16 | .Returns(new int[] { 9, 19, 29, 39, 49, 59, 69, 79, 89, 99 }).SetName("Another unsorted"); ;
17 | yield return new TestCaseData(new int[] { 1, 9, 5, 12, 4, 7, 35, 24, 15, 19, 22, 33, 23, 8, 6, 3 })
18 | .Returns(new int[] { 1, 3, 4, 5, 6, 7, 8, 9, 12, 15, 19, 22, 23, 24, 33, 35 }).SetName("The ultimate unsorted"); ;
19 | yield return new TestCaseData(new int[] { 10, 12, 13, 20, 21, 29, 35, 42, 50 })
20 | .Returns(new int[] { 10, 12, 13, 20, 21, 29, 35, 42, 50 }).SetName("Sorted input");
21 | yield return new TestCaseData(new int[] { 10 }).Returns(new int[] { 10 }).SetName("Just one element");
22 | yield return new TestCaseData(new int[] { 1, 1, 1, 1, 1, 1 }).Returns(new int[] { 1, 1, 1, 1, 1, 1 }).SetName("Duplicate elements only");
23 | yield return new TestCaseData(new int[] { 10, 22, 9, 80, 33, 21, 50, 9, 41, 10, 60, 80 })
24 | .Returns(new int[] { 9, 9, 10, 10, 21, 22, 33, 41, 50, 60, 80, 80 }).SetName("The standard unsorted with duplicates");
25 |
26 | }
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/LinkedListMergeSort/Tests/IntArrayMergeSortTester.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using LinkedListMergeSort.Problem;
3 |
4 | namespace LinkedListMergeSortTester.Tests
5 | {
6 | [TestFixture]
7 | public class IntArrayMergeSortTester
8 | {
9 | [Test, TestCaseSource(typeof(IntArrayMergeSortTestInput), "TestCases")]
10 | public int[] TestArrayMergeSort1(int[] inputArray)
11 | {
12 | ArrayMergeSorter.MergeSortIntArray(inputArray);
13 | return inputArray;
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/LinkedListMergeSort/Tests/LinkedListTester.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using LinkedListMergeSort.Problem;
3 |
4 | namespace LinkedListMergeSortTester
5 | {
6 | [TestFixture]
7 | public class LinkedListTester
8 | {
9 | [Test]
10 | public void LinkedListAddPrint()
11 | {
12 | var list = new LinkedList(13);
13 | list.Append(12);
14 | Assert.AreEqual("13->12->NULL", list.ToString());
15 | }
16 |
17 | [Test]
18 | public void ListListAddReversePrint()
19 | {
20 | var list = new LinkedList(1);
21 | list.Append(5);
22 | list.Append(10);
23 | list.Reverse();
24 | Assert.AreEqual("10->5->1->NULL", list.ToString());
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/LinkedListMergeSort/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/LongestContinuousStringOfRepeatingCharsQuestion/LongestContinuousStringOfRepeatingCharsTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 | using NUnit.Framework;
5 | using LongestContinuousStringOfRepeatingChars.Solution;
6 |
7 | namespace LongestContinuousStringOfRepeatingChars.Test
8 | {
9 | [TestFixture]
10 | public class LongestUniformStringTest
11 | {
12 | [Test, TestCaseSource(typeof(LongestUniformStringTestInput), "TestCases")]
13 | public List SubstringOfStringRepTest1(string input)
14 | {
15 | return LongestUniformString.GetRepititiveCharSubstringsAndLengths(input);
16 | }
17 |
18 | [Test, TestCaseSource(typeof(LongestUniformStringTestInput), "LongestUniformSubstringTuple")]
19 | public Tuple LongestUniformSubstringTester(string input)
20 | {
21 | return LongestUniformString.GetLongestUniformubstringsAndStartIndex(input);
22 | }
23 | }
24 |
25 | public class LongestUniformStringTestInput
26 | {
27 | public static IEnumerable TestCases
28 | {
29 | get
30 | {
31 | yield return new TestCaseData("abbbbbaaafccccccccdd").Returns(new List { "a", "bbbbb", "aaa", "f", "cccccccc", "dd" });
32 | yield return new TestCaseData("geeksforgeeks").Returns(new List { "g", "ee", "k", "s", "f", "o", "r", "g", "ee", "k", "s" });
33 | }
34 | }
35 |
36 | public static IEnumerable LongestUniformSubstringTuple
37 | {
38 | get
39 | {
40 | yield return new TestCaseData("abbbbbaaafccccccccdd").Returns(new Tuple(10, "cccccccc"));
41 | yield return new TestCaseData("geeksforgeeks").Returns(new Tuple(1, "ee"));
42 | }
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/LongestContinuousStringOfRepeatingCharsQuestion/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("LongestContinuousStringOfRepeatingCharsQuestion")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("LongestContinuousStringOfRepeatingCharsQuestion")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("d6e48d64-a0b1-40d7-9b18-732c1e8e7a2d")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/LongestContinuousStringOfRepeatingCharsQuestion/README.md:
--------------------------------------------------------------------------------
1 | # Longest Uniform Substring
2 |
3 | This question can be asked in many flavours
4 |
5 | * Given an input string, divide it into substrings where each substring contains the longest continuous string of the same character and output a string with the character for each substring and the length of the respective substring
6 |
7 | Another question of the same type:
8 |
9 | * Find the Longest Uniform Substring. A string of repetitive characters is called a uniform substring. Given an input string, return a tuple that contains the following:
10 | * the start position of the longest sub-string of repetitive character in the input string
11 | * the longest sub-string of repetitive characters
12 |
13 |
14 | example would be:
15 | - input: geeksforgeeks
16 | - output: 1 ee
17 |
18 | - input: abbbbbaaafccccccccdd
19 | - output: 10, cccccccc
20 |
21 | #### Files
22 |
23 | * Solution in `LongestContinuousStringOfRepeatingChars`
24 | * Tests in `LongestContinuousStringOfRepeatingCharsTest`
--------------------------------------------------------------------------------
/LongestContinuousStringOfRepeatingCharsQuestion/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/LongestIncreasingSubsequence/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/LongestIncreasingSubsequence/Problem/LongestIncreasingSubsequence.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace LongestIncreasingSubsequenceQuestion.Problem
4 | {
5 | public class LongestIncreasingSubsequence
6 | {
7 | public static void Main(string[] args)
8 | {
9 | var inputArray = new int[] { 10, 22, 9, 33, 21, 50, 41, 60, 80 };
10 | var lengthOfLongestInS = GetSizeOfLongestIncreasingSubsequence(inputArray, 9);
11 | Console.WriteLine(lengthOfLongestInS);
12 | }
13 |
14 | public static int GetSizeOfLongestIncreasingSubsequence(int[] arr, int sizeOfArray)
15 | {
16 | var lengthOfIncSubsequence = new int[sizeOfArray];
17 |
18 | //1 element sequence is the smallest sequence
19 | for (int i = 0; i < sizeOfArray; i++)
20 | lengthOfIncSubsequence[i] = 1;
21 |
22 | for (int i = 1; i < sizeOfArray; i++)
23 | {
24 | for (int j = 0; j < i; j++)
25 | {
26 | //not entirely sure why the second condition is performed.
27 | if (arr[i] > arr[j] && lengthOfIncSubsequence[i] < lengthOfIncSubsequence[j] + 1)
28 | {
29 | lengthOfIncSubsequence[i] = lengthOfIncSubsequence[j] + 1;
30 | }
31 | }
32 | }
33 | var max = 0;
34 | for (int i = 0; i < lengthOfIncSubsequence.Length; i++)
35 | {
36 | if (max < lengthOfIncSubsequence[i])
37 | max = lengthOfIncSubsequence[i];
38 | }
39 | return max;
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/LongestIncreasingSubsequence/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("LongestIncreasingSubsequence")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("LongestIncreasingSubsequence")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("d39c07b4-89cb-4056-b725-7a1551ad3598")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/LongestIncreasingSubsequence/README.md:
--------------------------------------------------------------------------------
1 | Let us discuss Longest Increasing Subsequence (LIS) problem as an example problem that can be solved using Dynamic Programming.
2 | The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such
3 | that all elements of the subsequence are sorted in increasing order.
4 | For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80}
5 | is 6 and LIS is {10, 22, 33, 50, 60, 80}.
6 |
7 | http://www.geeksforgeeks.org/longest-increasing-subsequence/
--------------------------------------------------------------------------------
/LongestIncreasingSubsequence/Tests/LongestIncreasingSubsequenceTester.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using LongestIncreasingSubsequenceQuestion.Problem;
3 | namespace LongestIncreasingSubsequenceTester.Tests
4 | {
5 | public class LongestIncreasingSubsequenceTester
6 | {
7 | [Test, TestCaseSource(typeof(LongestIncreasingSubsequenceTesterInput), "TestCases")]
8 | public int Test(int[] inputArray, int arraySize)
9 | {
10 | return LongestIncreasingSubsequence
11 | .GetSizeOfLongestIncreasingSubsequence(inputArray, arraySize);
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/LongestIncreasingSubsequence/Tests/LongestIncreasingSubsequenceTesterInput.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using NUnit.Framework;
3 |
4 | namespace LongestIncreasingSubsequenceTester.Tests
5 | {
6 | public class LongestIncreasingSubsequenceTesterInput
7 | {
8 | public static IEnumerable TestCases
9 | {
10 | get
11 | {
12 | yield return new TestCaseData(new int[] { 10, 22, 9, 33, 21, 50, 41, 60, 80 }, 9)
13 | .Returns(6).SetName("6 element sequence");
14 | yield return new TestCaseData(new int[] { 10, 12, 13, 20, 21, 29, 35, 42, 50 }, 9)
15 | .Returns(9).SetName("Longest sequence is the size of the input");
16 | yield return new TestCaseData(new int[] { 10, 9 }, 1).Returns(1).SetName("Just one element sequences");
17 | }
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/LongestIncreasingSubsequence/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/NonRepeatingCharacter/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/NonRepeatingCharacter/Problem/FirstNonRepeatingCharacterInString.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace FirstNonRepeatingCharacterInStringQuestion.Problem
5 | {
6 | public class FirstNonRepeatingCharacterInString
7 | {
8 | public static void Main(string[] args)
9 | {
10 | var not = Console.ReadLine();
11 | var numberOfTestCases = int.Parse(not);
12 | var listOfStrings = new List();
13 | while (numberOfTestCases> 0)
14 | {
15 | var los = Console.ReadLine();
16 | var lengthOfString = int.Parse(los);
17 |
18 | var inputString = Console.ReadLine();
19 | listOfStrings.Add(new StringsLengths(lengthOfString, inputString));
20 | numberOfTestCases--;
21 | }
22 | foreach (var strLengths in listOfStrings)
23 | {
24 | Console.WriteLine(NonRepeatingCharacter(strLengths));
25 | }
26 | Console.ReadKey();
27 | }
28 |
29 | public static string NonRepeatingCharacter(StringsLengths strLength)
30 | {
31 | Dictionary characterMap = new Dictionary();
32 | foreach(var c in strLength.InputString)
33 | {
34 | if (characterMap.ContainsKey(c))
35 | {
36 | characterMap[c] = characterMap[c] + 1;
37 | }
38 | else
39 | {
40 | characterMap.Add(c, 1);
41 | }
42 | }
43 |
44 | foreach(var c in strLength.InputString)
45 | {
46 | if (characterMap[c] < 2)
47 | return c.ToString();
48 | }
49 |
50 | return "-1";
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/NonRepeatingCharacter/Problem/StringsLengths.cs:
--------------------------------------------------------------------------------
1 | namespace FirstNonRepeatingCharacterInStringQuestion.Problem
2 | {
3 | public class StringsLengths
4 | {
5 | private int _length;
6 | private string _inputString;
7 |
8 | public int Length { get { return _length; } }
9 | public string InputString { get { return _inputString; } }
10 | public StringsLengths(int n, string input)
11 | {
12 | _length = n;
13 | _inputString = input;
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/NonRepeatingCharacter/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("NonRepeatingCharacter")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("NonRepeatingCharacter")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("bc522c48-a6d1-4ce9-9fd7-e9dbf4eb0927")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/NonRepeatingCharacter/README.md:
--------------------------------------------------------------------------------
1 | # First non-repeating character in a string
2 |
3 | Given a string s consisting of lowercase Latin Letters, find the first non repeating character in s.
4 |
5 | ## Input:
6 |
7 | The first line contains T denoting the number of testcases. Then follows description of testcases.
8 | Each case begins with a single integer N denoting the length of string. The next line contains the string s.
9 |
10 | ## Output:
11 |
12 |
13 | For each testcase, print the first non repeating character present in string.
14 |
15 | Print -1 if there is no non repeating character.
16 |
17 | ### Constraints:
18 |
19 |
20 | 1<=T<=50
21 | 1<=N<=100
22 |
23 |
24 | ## Example:
25 |
26 | ### Input :
27 |
28 | 3
29 | 5
30 | hello
31 | 12
32 | zxvczbtxyzvy
33 | 6
34 | xxyyzz
35 |
36 |
37 |
38 | ### Output :
39 |
40 | h
41 | c
42 | -1
--------------------------------------------------------------------------------
/NonRepeatingCharacter/Tests/FirstNonRepeatingCharInStringTester.cs:
--------------------------------------------------------------------------------
1 | using FirstNonRepeatingCharacterInStringQuestion.Problem;
2 | using NUnit.Framework;
3 |
4 | namespace FirstNonRepeatingCharactersInStringTester.Tests
5 | {
6 | [TestFixture]
7 | public class FirstNonRepeatingCharInStringTester
8 | {
9 | [Test]
10 | public void FirstNonRepeaterTest1()
11 | {
12 | var stringLength = new StringsLengths(5, "aabbc");
13 | Assert.AreEqual("c", FirstNonRepeatingCharacterInString.NonRepeatingCharacter(stringLength));
14 | }
15 |
16 | [Test]
17 | public void FirstNonRepeaterTest2()
18 | {
19 | var stringLength = new StringsLengths(6, "paalla");
20 | Assert.AreEqual("p", FirstNonRepeatingCharacterInString.NonRepeatingCharacter(stringLength));
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/NonRepeatingCharacter/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/OverlappingRectangles/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/OverlappingRectangles/Problem/PairOfRectangleCoordinates.cs:
--------------------------------------------------------------------------------
1 | namespace OverlappingRectanglesQuestion.Problem
2 | {
3 | public class PairOfRectangleCoordinates
4 | {
5 | private RectangleCoordinates first;
6 | private RectangleCoordinates second;
7 |
8 | public RectangleCoordinates First { get { return first; } }
9 | public RectangleCoordinates Second { get { return second; } }
10 |
11 | public PairOfRectangleCoordinates(RectangleCoordinates one, RectangleCoordinates two)
12 | {
13 | first = one;
14 | second = two;
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/OverlappingRectangles/Problem/Point.cs:
--------------------------------------------------------------------------------
1 | namespace OverlappingRectanglesQuestion.Problem
2 | {
3 | public class Point
4 | {
5 | private int x;
6 | private int y;
7 |
8 | public int X { get { return x; } }
9 | public int Y { get { return y; } }
10 |
11 | public Point(int x1, int y1)
12 | {
13 | x = x1;
14 | y = y1;
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/OverlappingRectangles/Problem/RectangleCoordinates.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Linq;
3 |
4 | namespace OverlappingRectanglesQuestion.Problem
5 | {
6 | public class RectangleCoordinates
7 | {
8 | private Point leftTop;
9 | private Point rightBottom;
10 |
11 | public Point LeftTop { get { return leftTop; } }
12 | public Point RightBottom { get { return rightBottom; } }
13 |
14 |
15 | public RectangleCoordinates(List coordinates)
16 | {
17 | var listOfIntCoords = coordinates.Select(c => int.Parse(c)).ToList();
18 |
19 | leftTop = new Point(listOfIntCoords[0], listOfIntCoords[1]);
20 | rightBottom = new Point(listOfIntCoords[2], listOfIntCoords[3]);
21 | }
22 |
23 | public RectangleCoordinates(List coordinates)
24 | {
25 | leftTop = new Point(coordinates[0], coordinates[1]);
26 | rightBottom = new Point(coordinates[2], coordinates[3]);
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/OverlappingRectangles/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("OverlappingRectangles")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("OverlappingRectangles")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("5ac98c57-1136-4456-857e-796ade64b405")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/OverlappingRectangles/README.md:
--------------------------------------------------------------------------------
1 | # Overlapping rectangles
2 |
3 | ## Online resources
4 |
5 | http://www.geeksforgeeks.org/find-two-rectangles-overlap/
6 | https://practice.geeksforgeeks.org/problems/overlapping-rectangles/0
7 |
8 |
9 | ## Problem statement
10 | Given two rectangles, find if the given two rectangles overlap or not.
11 | A rectangle is denoted by providing the x and y co-ordinates of two points:
12 | the left top corner and the right bottom corner of the rectangle.
13 |
14 | Note that two rectangles sharing a side are considered overlapping.
15 |
16 | rectanglesOverlap
17 |
18 | ### Input
19 |
20 | * The first integer T denotes the number of test cases.
21 | * For every test case, there are 2 lines of input.
22 | * The first line consists of 4 integers: denoting the co-ordinates of the 2 points of the first rectangle.
23 | * The first integer denotes the x co-ordinate and the second integer denotes the y co-ordinate of the left topmost corner of the first rectangle.
24 | * The next two integers are the x and y co-ordinates of right bottom corner.
25 | * Similarly, the second line denotes the cordinates of the two points of the second rectangle.
26 |
27 |
28 | ### Output
29 |
30 | For each test case, output (either 1 or 0) denoting whether the 2 rectangles are overlapping.
31 | 1 denotes the rectangles overlap whereas 0 denotes the rectangles do not overlap.
32 |
33 |
34 | ### Constraints
35 |
36 | * `1 <= T <= 10`
37 | * `-10000 <= x,y <= 10000`
38 | * `T` denotes the number of test cases. `x` denotes the `x` co-ordinate and `y` denotes the `y` co-ordinate.
39 |
40 |
41 | ## Example
42 |
43 | ### Input
44 |
45 | 2
46 | 0 10 10 0
47 | 5 5 15 0
48 | 0 2 1 1
49 | -2 -3 0 2
50 |
51 | ### Output
52 |
53 | 1
54 | 0
55 |
56 |
--------------------------------------------------------------------------------
/OverlappingRectangles/Tests/OverlappingRectangleTest.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using OverlappingRectanglesQuestion.Problem;
3 |
4 | namespace OverlappingRectangleTester.Tests
5 | {
6 | [TestFixture]
7 | public class OverlappingRectangleTest
8 | {
9 | [Test, TestCaseSource(typeof(OverlappingRectangleTestInput), "TestCases")]
10 | public int DoRectanglesOverlap(PairOfRectangleCoordinates pair)
11 | {
12 | return OverlappingRectangles.DoRectanglesOverlap(pair);
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/OverlappingRectangles/Tests/OverlappingRectangleTestInput.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using System.Collections.Generic;
3 | using NUnit.Framework;
4 | using OverlappingRectanglesQuestion.Problem;
5 |
6 | namespace OverlappingRectangleTester.Tests
7 | {
8 | public class OverlappingRectangleTestInput
9 | {
10 | public static IEnumerable TestCases
11 | {
12 | get
13 | {
14 | yield return
15 | new TestCaseData(new PairOfRectangleCoordinates(
16 | new RectangleCoordinates(new List { 0, 10, 10, 0 }),
17 | new RectangleCoordinates(new List { 5, 5, 15, 0 })))
18 | .Returns(1)
19 | .SetName("They overlap!");
20 |
21 | yield return
22 | new TestCaseData(new PairOfRectangleCoordinates(
23 | new RectangleCoordinates(new List { 0, 2, 1, 1 }),
24 | new RectangleCoordinates(new List { -2, -3, 0, 2 })))
25 | .Returns(0)
26 | .SetName("They don't overlap!");
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/OverlappingRectangles/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/PermMissingElem/PermMissingElem.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.1
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/PermMissingElem/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
4 |
5 | Your goal is to find that missing element.
6 |
7 | Write a function:
8 |
9 | class Solution { public int solution(int[] A); }
10 |
11 | that, given an array A, returns the value of the missing element.
12 |
13 | For example, given array A such that:
14 | A[0] = 2
15 | A[1] = 3
16 | A[2] = 1
17 | A[3] = 5
18 |
19 | the function should return 4, as it is the missing element.
20 |
21 | Write an efficient algorithm for the following assumptions:
22 |
23 | N is an integer within the range [0..100,000];
24 | the elements of A are all distinct;
25 | each element of array A is an integer within the range [1..(N + 1)].
26 |
27 |
28 |
--------------------------------------------------------------------------------
/PermMissingElem/Solution.cs:
--------------------------------------------------------------------------------
1 | namespace PermMissingElem
2 | {
3 | public class Solution
4 | {
5 | public int Solve(int[] A)
6 | {
7 | // write your code in C# 6.0 with .NET 4.5 (Mono)
8 | var actualSum = 0;
9 | var max = 0;
10 | for (int i = 0; i < A.Length; i++)
11 | {
12 | if (A[i] > max)
13 | {
14 | max = A[i];
15 | }
16 | actualSum += A[i];
17 | }
18 | var expectedSum = (max * (max + 1)) / 2;
19 | return expectedSum - actualSum;
20 | }
21 | }
22 | }
--------------------------------------------------------------------------------
/PermMissingElem/SolutionTests.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using System.Collections;
3 | using System.Linq;
4 |
5 | namespace PermMissingElem
6 | {
7 | [TestFixture]
8 | public class SolutionTests
9 | {
10 | [Test, TestCaseSource(nameof(TestData))]
11 | public int Test(int[] input)
12 | {
13 | var solution = new Solution();
14 | return solution.Solve(input);
15 | }
16 |
17 | public static IEnumerable TestData
18 | {
19 | get
20 | {
21 | yield return new TestCaseData(new int[] { 2, 3, 1, 5 }).Returns(4);
22 |
23 | yield return new TestCaseData(new int[] { 1, 2, 4, 5, 6 }).Returns(3);
24 |
25 | yield return new TestCaseData(new int[] { 2, 3, 4, 5, 6 }).Returns(1);
26 |
27 | yield return new TestCaseData(new int[] { 2, 3 }).Returns(1);
28 |
29 | yield return new TestCaseData(new int[] { 2 }).Returns(1);
30 |
31 | var largeInput = Enumerable.Range(1, 100002).Where(i => i != 1001).ToArray();
32 | yield return new TestCaseData(largeInput).Returns(1001).SetName("Large input");
33 | }
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/QueueTaleOfTwoStacks/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/QueueTaleOfTwoStacks/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("QueueTaleOfTwoStacks")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("QueueTaleOfTwoStacks")]
13 | [assembly: AssemblyCopyright("Copyright © 2016")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("55ea4f01-a26b-4617-9084-f611018cbd61")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/QueueTaleOfTwoStacks/QueueOfTwoStacks.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace QueueTaleOfTwoStacks
4 | {
5 | ///
6 | /// This Implementation of a Queue using two stacks make the enqueue operation expensive
7 | /// by always emptying everything in newestOnTop onto oldestOnTop and then inserting the value
8 | /// in newestOnTop and then again emptying oldestOnTop onto newestOnTop.
9 | ///
10 | public class QueueOfTwoStacks
11 | {
12 | Stack newestOnTop = new Stack();
13 | Stack oldestOnTop = new Stack();
14 |
15 | ///
16 | /// Method 1 (By making enQueue operation costly)
17 | /// This method makes sure that oldest entered element is always at the top of stack 1,
18 | /// so that deQueue operation just pops from stack1. To put the element at top of
19 | /// stack1, stack2 is used.
20 | /// enQueue(q, x)
21 | /// 1) While stack1 is not empty, push everything from satck1 to stack2.
22 | /// 2) Push x to stack1(assuming size of stacks is unlimited).
23 | /// 3) Push everything back to stack1.
24 | ///
25 | ///
26 | public void Enqueue(int val)
27 | {
28 | while (newestOnTop.Count > 0)
29 | {
30 | oldestOnTop.Push(newestOnTop.Pop());
31 | }
32 | newestOnTop.Push(val);
33 |
34 | while(oldestOnTop.Count > 0)
35 | {
36 | newestOnTop.Push(oldestOnTop.Pop());
37 | }
38 | }
39 |
40 | ///
41 | /// /// dnQueue(q)
42 | /// 1) If stack1 is empty then error
43 | /// 2) Pop an item from stack1 and return it
44 | ///
45 | ///
46 | public int Dequeue()
47 | {
48 | if (newestOnTop.Count <= 0)
49 | {
50 | throw new System.Exception("What the hell? you can't pop an empty stack");
51 | }
52 | return newestOnTop.Pop();
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/QueueTaleOfTwoStacks/QueueOfTwoStacks1.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace QueueTaleOfTwoStacks
4 | {
5 | ///
6 | /// This Implementation of a Queue using two stacks make the dequeue operation expensive
7 | /// Method 2 (By making deQueue operation costly)In this method, in en-queue operation,
8 | /// the new element is entered at the top of stack1. In de-queue operation,
9 | /// if stack2 is empty then all the elements are moved to stack2 and
10 | /// finally top of stack2 is returned.
11 | ///
12 | public class QueueOfTwoStacks1
13 | {
14 | Stack newestOnTop = new Stack();
15 | Stack oldestOnTop = new Stack();
16 |
17 | ///
18 | /// enQueue(q, x)
19 | /// 1) Push x to stack1(assuming size of stacks is unlimited).
20 | ///
21 | ///
22 | public void Enqueue(int val)
23 | {
24 | newestOnTop.Push(val);
25 | }
26 |
27 | ///
28 | /// deQueue(q)
29 | /// 1) If both stacks are empty then error.
30 | /// 2) If stack2 is empty
31 | /// While stack1 is not empty, push everything from stack1 to stack2.
32 | /// 3) Pop the element from stack2 and return it.
33 | ///
34 | ///
35 | public int Dequeue()
36 | {
37 | if (newestOnTop.Count <= 0 && oldestOnTop.Count <= 0)
38 | {
39 | throw new System.Exception("Sorry Nothing in here to deque");
40 | }
41 | if (oldestOnTop.Count <= 0)
42 | {
43 | while (newestOnTop.Count > 0)
44 | {
45 | oldestOnTop.Push(newestOnTop.Pop());
46 | }
47 | return oldestOnTop.Pop();
48 | }
49 | else
50 | {
51 | throw new System.Exception("Sorry Nothing in here to deque");
52 | }
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/QueueTaleOfTwoStacks/README.md:
--------------------------------------------------------------------------------
1 | # Queue
2 |
3 | A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed.
4 |
5 | ## Operations on a Queue
6 |
7 | A basic queue has the following operations:
8 |
9 | Enqueue: add a new element to the end of the queue.
10 | Dequeue: remove the element from the front of the queue and return it.
11 |
12 | In this challenge, you must first implement a queue using two stacks. Then process queries, where each query is one of the following types:
13 |
14 | 1 x: Enqueue element into the end of the queue.
15 | 2: Dequeue the element at the front of the queue.
16 | 3: Print the element at the front of the queue.
17 |
18 | ## Input Format
19 |
20 | The first line contains a single integer, , denoting the number of queries.
21 | Each line of the subsequent lines contains a single query in the form described in the problem statement above. All three queries start with an integer denoting the query , but only query is followed by an additional space-separated value, , denoting the value to be enqueued.
22 |
23 | ### Constraints
24 |
25 | It is guaranteed that a valid answer always exists for each query of type .
26 |
27 | ## Output Format
28 |
29 | For each query of type , print the value of the element at the front of the queue on a new line.
30 |
31 | ## Sample Input
32 |
33 | 10
34 | 1 42
35 | 2
36 | 1 14
37 | 3
38 | 1 28
39 | 3
40 | 1 60
41 | 1 78
42 | 2
43 | 2
44 |
45 | ## Sample Output
46 |
47 | 14
48 | 14
49 |
50 | ## Explanation
51 |
52 | We perform the following sequence of actions:
53 |
54 | 1. Enqueue 42; queue = {42}.
55 | 1. Dequeue the value at the head of the queue, 42; queue = {}.
56 | 1. Enqueue 14; queue = {14}.
57 | 1. Print the value at the head of the queue, 14; queue = {14}.
58 | 1. Enqueue 28; queue = {14 <- 28}.
59 | 1. Print the value at the head of the queue, 14; {14 <- 28}.
60 | 1. Enqueue 60; queue = {14 <- 28 <- 60}.
61 | 1. Enqueue 78; queue = {14 <- 28 <- 60 <- 78}.
62 | 1. Dequeue the value at the head of the queue, 14; queue = {28 <- 60 <- 78}.
63 | 1. Dequeue the value at the head of the queue, 28; queue = {60 <- 78}.
64 |
65 | This question is from [Hackerrank](https://www.hackerrank.com/challenges/ctci-queue-using-two-stacks/problem)
--------------------------------------------------------------------------------
/QueueTaleOfTwoStacks/Solution.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace QueueTaleOfTwoStacks
5 | {
6 | public class Solution
7 | {
8 | public static void Main(string[] args)
9 | {
10 | QueueOfTwoStacks qOts = new QueueOfTwoStacks();
11 | var numberOfQueries = int.Parse(Console.ReadLine());
12 | List> operationsList = new List>();
13 | for (int i = 0; i < numberOfQueries; i++)
14 | {
15 | var operation = Console.ReadLine();
16 | var operationAndOperandPair = IdentifyOperationAndOperand(operation);
17 | operationsList.Add(operationAndOperandPair);
18 | }
19 |
20 | foreach (var keyValuePair in operationsList)
21 | {
22 | switch (keyValuePair.Key)
23 | {
24 | case 1:
25 | //1 x: Enqueue element into the end of the queue.
26 | Console.WriteLine("Inserting {0}", keyValuePair.Value);
27 | qOts.Enqueue(keyValuePair.Value);
28 | break;
29 | case 2:
30 | //2: Dequeue the element at the front of the queue.
31 | Console.WriteLine("Dequeuing from queue {0}", qOts.Dequeue());
32 | break;
33 | //case 3:
34 | // //3: Print the element at the front of the queue.
35 | // Console.WriteLine(qOts.Peek());
36 | // break;
37 | default:
38 | //throw exception
39 | break;
40 | }
41 | }
42 | Console.ReadLine();
43 | }
44 |
45 | public static KeyValuePair IdentifyOperationAndOperand(string operation)
46 | {
47 | var operationAndOperand = operation.Split(' ');
48 | if (operationAndOperand.Length < 2)
49 | {
50 | return new KeyValuePair(int.Parse(operationAndOperand[0]), 0);
51 | }
52 | return new KeyValuePair(int.Parse(operationAndOperand[0]), int.Parse(operationAndOperand[1]));
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/QueueTaleOfTwoStacks/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # InterviewQuestions
2 |
3 | Some popular questions and their solutions in `C#` from :
4 |
5 | * [geeksforgeeks](https://www.geeksforgeeks.org/)
6 | * [HackerRank](https://www.hackerrank.com)
7 |
8 | * Tests written using `NUnit 3.9`
9 | * Compiled and tested in VS2015 Community Edition.
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/RemoveDuplicatesArraySorted/DuplicateRemover.cs:
--------------------------------------------------------------------------------
1 | namespace RemoveDuplicatesArraySorted
2 | {
3 | public class DuplicateRemover
4 | {
5 |
6 | public int DuplicateRemoverSolution1(int[] nums)
7 | {
8 | /*
9 | * iterate through every element of the array.
10 | * at every position, i of the array, check if the next element, j= i+1 is a duplicate
11 | * until we find it is not.
12 | * set the next element as the newly found
13 | * shift all elements to the left
14 | * a[i+1] = a[j]
15 | * nums => 1,1,2,2,3
16 | * First pass:
17 | * i = 0
18 | * j = 1,2
19 | *
20 | * when j=2, swap elements at position i+1 and position j
21 | * nums => 1,2,1,2,3
22 | *
23 | * Second:
24 | * i=1
25 | * j=2
26 | * nums[i] => 2, nums[j] => 1
27 | * j=3
28 | * nums[i] => 2, nums[j] => 2
29 | * j=4
30 | * nums[i] => 2, nums[j] => 3
31 | *
32 | *
33 | *
34 | */
35 | if (nums.Length == 0)
36 | {
37 | return 0;
38 | }
39 | int i = 0;
40 | int lastElementPosition = nums.Length - 1;
41 | int lastSwappedValue = nums[i];
42 |
43 | while (i < lastElementPosition)
44 | {
45 | // until we find an element bigger than whats at i, keep looking
46 | int j = FindNextUniqueElementPosition(nums, i, lastSwappedValue);
47 | if (j > lastElementPosition)
48 | {
49 | // all elements after position i, were the same, no swapping necessary
50 | break;
51 | }
52 | lastSwappedValue = SwapElementsInArray(nums, j, i + 1);
53 | if (j == lastElementPosition)
54 | {
55 | // you've swapped i+1 with j. so total number of elements will be i+2.
56 | return i + 2;
57 | }
58 | i++;
59 | }
60 | return i+1;
61 | }
62 |
63 | private int FindNextUniqueElementPosition(int[] nums, int startIndex, int lastSwapped)
64 | {
65 | int j = startIndex + 1;
66 | while (j < nums.Length && (nums[j] <= nums[startIndex] || nums[j] <= lastSwapped))
67 | {
68 | j++;
69 | }
70 | return j;
71 | }
72 |
73 | private int SwapElementsInArray(int[] nums, int sourceIndex, int destIndex)
74 | {
75 | int x = nums[destIndex];
76 | nums[destIndex] = nums[sourceIndex];
77 | nums[sourceIndex] = x;
78 | return nums[destIndex];
79 | }
80 |
81 |
82 | public int DuplicateRemoverSolution2(int[] nums)
83 | {
84 | if (nums.Length == 0)
85 | return 0;
86 |
87 | int ptr = 0;
88 |
89 | foreach (int num in nums)
90 | {
91 | if (num != nums[ptr])
92 | nums[++ptr] = num;
93 | }
94 |
95 | return ptr + 1;
96 | }
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/RemoveDuplicatesArraySorted/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("RemoveDuplicatesArraySorted")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("RemoveDuplicatesArraySorted")]
13 | [assembly: AssemblyCopyright("Copyright © 2020")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("6dd30c52-f458-45ac-bac8-451ae29c9097")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/RemoveDuplicatesArraySorted/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/RemoveDuplicatesFromSortedArray/DuplicateRemovalTests.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 |
3 | namespace RemoveDuplicatesFromSortedArray
4 | {
5 | [TestFixture]
6 | public class DuplicateRemovalTests
7 | {
8 | private DuplicateRemover duplicateRemover { get; set; }
9 |
10 | [SetUp]
11 | public void Setup()
12 | {
13 | duplicateRemover = new DuplicateRemover();
14 | }
15 |
16 | [TestCase(new int[] { 1, 1, 3 }, ExpectedResult = 2)]
17 | [TestCase(new int[] { 1, 1, 2, 2, 3 }, ExpectedResult = 3)]
18 |
19 | public int Test_DuplicateRemoverSolution1(int[] nums)
20 | {
21 | return duplicateRemover.DuplicateRemoverSolution1(nums);
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/RemoveDuplicatesFromSortedArray/DuplicateRemover.cs:
--------------------------------------------------------------------------------
1 |
2 | namespace RemoveDuplicatesFromSortedArray
3 | {
4 | public class DuplicateRemover
5 | {
6 | public int DuplicateRemoverSolution1(int[] nums)
7 | {
8 | /*
9 | * iterate through every element of the array.
10 | * at every position, i of the array, check if the next element, j= i+1 is a duplicate
11 | * until we find it is not.
12 | * set the next element as the newly found
13 | * shift all elements to the left
14 | * a[i+1] = a[j]
15 | * nums => 1,1,2,2,3
16 | * First pass:
17 | * i = 0
18 | * j = 1,2
19 | *
20 | * when j=2, swap elements at position i+1 and position j
21 | * nums => 1,2,1,2,3
22 | *
23 | * Second:
24 | * i=1
25 | * j=2
26 | * nums[i] => 2, nums[j] => 1
27 | * j=3
28 | * nums[i] => 2, nums[j] => 2
29 | * j=4
30 | * nums[i] => 2, nums[j] => 3
31 | *
32 | *
33 | *
34 | */
35 | int i = 0;
36 | int lastElementPosition = nums.Length - 1;
37 | int lastSwappedValue = 0;
38 | while (i < lastElementPosition)
39 | {
40 | // until we find an element bigger than whats at i, keep looking
41 | int j = FindNextUniqueElementPosition(nums, i, lastSwappedValue);
42 | lastSwappedValue = SwapElementsInArray(nums, j, i + 1);
43 | if (j == lastElementPosition)
44 | {
45 | return i + 1;
46 | }
47 | i++;
48 | }
49 | return i;
50 | }
51 |
52 | private int FindNextUniqueElementPosition(int[] nums, int startIndex, int lastSwapped)
53 | {
54 | int j = startIndex + 1;
55 | while ((nums[j] <= nums[startIndex] || nums[j] <= lastSwapped) && j < nums.Length)
56 | {
57 | j++;
58 | }
59 | return j;
60 | }
61 |
62 | private int SwapElementsInArray(int[] nums, int sourceIndex, int destIndex)
63 | {
64 | int x = nums[destIndex];
65 | nums[destIndex] = nums[sourceIndex];
66 | nums[sourceIndex] = x;
67 | return nums[destIndex];
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/RemoveDuplicatesFromSortedArray/RemoveDuplicatesFromSortedArray.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.1
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/ReverseWordsInASentence/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/ReverseWordsInASentence/Problem/ReverseWordsInASentence.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 |
5 | namespace ReverseWordsInASentenceQuestion.Problem
6 | {
7 | public class ReverseWordsInASentence
8 | {
9 | public static void Main(string[] args)
10 | {
11 | var nOfTests = Console.ReadLine();
12 | var numberOfTests = 0;
13 | var listOfSentences = new List();
14 | int.TryParse(nOfTests, out numberOfTests);
15 | while (numberOfTests > 0)
16 | {
17 | var inputSentence = Console.ReadLine();
18 | Console.WriteLine(ReverseWordsInTheSentence(inputSentence));
19 | numberOfTests--;
20 | }
21 | }
22 |
23 | public static string ReverseWordsInTheSentence(string sentence)
24 | {
25 | var words = sentence.Split('.').Reverse().ToArray();
26 | return string.Join(".", words);
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/ReverseWordsInASentence/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("ReverseWordsInASentence")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("ReverseWordsInASentence")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("aa937db1-1509-4d50-b139-f476ca94c0e2")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/ReverseWordsInASentence/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | Given a String of length N reverse the words in it. Words are separated by dots.
4 |
5 | Input:
6 | The first line contains T denoting the number of testcases. Then follows description of testcases. Each case contains a string containing spaces and characters.
7 |
8 |
9 | Output:
10 | For each test case, output a single line containing the reversed String.
11 |
12 | Constraints:
13 | 1<=T<=20
14 | 1<=Lenght of String<=2000
15 |
16 |
17 | Example:
18 | Input:
19 | 2
20 | i.like.this.program.very.much
21 | pqr.mno
22 |
23 | Output:
24 | much.very.program.this.like.i
25 | mno.pqr
26 | ** For More Input/Output Examples Use 'Expected Output' option **
27 |
--------------------------------------------------------------------------------
/ReverseWordsInASentence/Tests/ReverseWordsInASentenceTest.cs:
--------------------------------------------------------------------------------
1 | using ReverseWordsInASentenceQuestion.Problem;
2 | using NUnit.Framework;
3 |
4 | namespace ReverseWordsInASentenceTester.Tests
5 | {
6 | [TestFixture]
7 | public class ReverseWordsInASentenceTest
8 | {
9 | [Test, TestCaseSource(typeof(ReverseWordsInASentenceTestInput), "TestCases")]
10 | public string ReverseWordsInTheSentenceTest(string input)
11 | {
12 | return ReverseWordsInASentence.ReverseWordsInTheSentence(input);
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ReverseWordsInASentence/Tests/ReverseWordsInASentenceTestInput.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using NUnit.Framework;
3 |
4 | namespace ReverseWordsInASentenceTester.Tests
5 | {
6 | class ReverseWordsInASentenceTestInput
7 | {
8 | public static IEnumerable TestCases
9 | {
10 | get
11 | {
12 | yield return new TestCaseData("this.is.a.freaking.long.sentence.that.has.to.be.reversed")
13 | .Returns("reversed.be.to.has.that.sentence.long.freaking.a.is.this")
14 | .SetName("The long sentence words should be reversed");
15 | yield return new TestCaseData("will.i.ever.get.a.job")
16 | .Returns("job.a.get.ever.i.will")
17 | .SetName("The job sentence words should be reversed");
18 | yield return new TestCaseData("m.a.l.a.y.a.l.a.m")
19 | .Returns("m.a.l.a.y.a.l.a.m")
20 | .SetName("The palindrome sentence words should be reversed");
21 | }
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/ReverseWordsInASentence/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/RobotGrid/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/RobotGrid/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace RobotGrid
4 | {
5 | class Program
6 | {
7 | static void Main(string[] args)
8 | {
9 | char[,] grid = new char[10, 10];
10 | var rowIndex = 5;
11 | var colIndex = 5;
12 | RedrawGrid(grid, rowIndex, colIndex);
13 | while (true)
14 | {
15 | var input = Console.ReadKey().KeyChar;
16 | switch (input)
17 | {
18 | case 'a':
19 | //move left
20 | if (colIndex > 0) colIndex--;
21 | break;
22 |
23 | case 'd':
24 | //move right
25 | if (colIndex < 9) colIndex++;
26 | break;
27 |
28 | case 'w':
29 | //move up
30 | if (rowIndex > 0) rowIndex--;
31 | break;
32 |
33 | case 's':
34 | //move down
35 | if (rowIndex < 9) rowIndex++;
36 | break;
37 |
38 | default:
39 | break;
40 | }
41 | RedrawGrid(grid, rowIndex, colIndex);
42 | }
43 | }
44 |
45 | static void RedrawGrid(char[,] grid, int row, int col)
46 | {
47 | for (int i = 0; i < 10; i++)
48 | for (int j = 0; j < 10; j++)
49 | grid[i, j] = ' ';
50 |
51 | grid[row, col] = '_';
52 | Console.Clear();
53 | for (int i = 0; i < 10; i++)
54 | {
55 | for(int j = 0; j < 10; j++)
56 | {
57 | Console.Write(grid[i, j]);
58 | }
59 | Console.WriteLine();
60 | }
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/RobotGrid/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("RobotGrid")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("RobotGrid")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("6eda3a72-b87c-471a-8181-7e2e0a03a873")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/RobotGrid/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/RotateByKSteps/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("RotateByKSteps")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("RotateByKSteps")]
13 | [assembly: AssemblyCopyright("Copyright © 2020")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("75d46200-e74e-4171-bb18-986a0fa96616")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/RotateByKSteps/README.md:
--------------------------------------------------------------------------------
1 | # Rotate by K Steps
2 |
3 | Given an array, rotate the array to the right by k steps, where k is non-negative.
4 |
5 | ##### Follow up:
6 |
7 | Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
8 | Could you do it in-place with O(1) extra space?
9 |
10 | ##### Example 1:
11 |
12 | Input: nums = [1,2,3,4,5,6,7], k = 3
13 | Output: [5,6,7,1,2,3,4]
14 |
15 | ###### Explanation:
16 | rotate 1 steps to the right: [7,1,2,3,4,5,6]
17 | rotate 2 steps to the right: [6,7,1,2,3,4,5]
18 | rotate 3 steps to the right: [5,6,7,1,2,3,4]
19 |
20 | ##### Example 2:
21 |
22 | Input: nums = [-1,-100,3,99], k = 2
23 | Output: [3,99,-1,-100]
24 |
25 | ###### Explanation:
26 | rotate 1 steps to the right: [99,-1,-100,3]
27 | rotate 2 steps to the right: [3,99,-1,-100]
28 |
29 | ##### Constraints:
30 |
31 | 1 <= nums.length <= 2 * 10^4
32 | It's guaranteed that nums[i] fits in a 32 bit-signed integer.
33 | k >= 0
34 |
35 |
--------------------------------------------------------------------------------
/RotateByKSteps/Rotater.cs:
--------------------------------------------------------------------------------
1 | namespace RotateByKSteps
2 | {
3 | public class Rotater
4 | {
5 | ///
6 | /// This solution is a fail
7 | ///
8 | ///
9 | ///
10 | public void Rotate_Solution_1(int[] nums, int k)
11 | {
12 | for (int i = (nums.Length - 1); i >= k; i--)
13 | {
14 | var swapPosition = GetSwapPosition(i, k, nums.Length);
15 | int temp = nums[swapPosition];
16 | nums[swapPosition] = nums[i];
17 | nums[i] = temp;
18 | }
19 | }
20 |
21 | private int GetSwapPosition(int currentPosition, int steps, int length)
22 | {
23 | return (currentPosition + steps) % length;
24 | }
25 |
26 | ///
27 | /// O(n) solution - it works
28 | ///
29 | ///
30 | ///
31 | public void Rotate_Solution_2(int[] nums, int k)
32 | {
33 | /*
34 | * if k>nums.Length then mod it by Length to do actual rotations
35 | * create temporary array of
36 | */
37 | if (k > nums.Length)
38 | {
39 | k %= nums.Length;
40 | }
41 | var otherSide = new int[k];
42 | var otherCounter = 0;
43 | // create a temporary array containing elements that will overflow from
44 | // right side to the left.
45 | for(int i=(nums.Length - k); i < nums.Length; i++)
46 | {
47 | otherSide[otherCounter++] = nums[i];
48 | }
49 | // shift all elements that can be shifted within the arrays size
50 | for (int i = (nums.Length - k); i > 0; i--)
51 | {
52 | nums[i - 1 + k] = nums[i - 1];
53 | }
54 |
55 | // fill in the left most elements using the temporary array.
56 | for(int i=0; i < k; i++)
57 | {
58 | nums[i] = otherSide[i];
59 | }
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/RotateByKSteps/RotaterTests.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 |
3 | namespace RotateByKSteps
4 | {
5 | [TestFixture]
6 | public class RotaterTests
7 | {
8 | private Rotater rotater;
9 |
10 | [SetUp]
11 | public void Setup()
12 | {
13 | rotater = new Rotater();
14 | }
15 |
16 |
17 | //[TestCase(new int[] { 1, 1, 3 }, 1, ExpectedResult = new int[] { 3, 1, 1 })]
18 | //[TestCase(new int[] { 1, 2, 3, 4, 5, 6, 7 }, 3, ExpectedResult = new int[] { 5, 6, 7, 1, 2, 3, 4 })]
19 | public int[] Test_Rotate_1(int[] nums, int steps)
20 | {
21 | rotater.Rotate_Solution_1(nums, steps);
22 | return nums;
23 | }
24 |
25 | [TestCase(new int[] { 1, 1, 3 }, 1, ExpectedResult = new int[] { 3, 1, 1 })]
26 | [TestCase(new int[] { -1, -100, 3, 99 }, 2, ExpectedResult = new int[] { 3, 99, -1, -100 })]
27 | [TestCase(new int[] { -1, -100, 3, 99 }, 6, ExpectedResult = new int[] { 3, 99, -1, -100 })]
28 | [TestCase(new int[] { 1, 2, 3, 4, 5, 6, 7 }, 3, ExpectedResult = new int[] { 5, 6, 7, 1, 2, 3, 4 })]
29 | [TestCase(new int[] { 1, 2, 3, 4, 5, 6, 7 }, 10, ExpectedResult = new int[] { 5, 6, 7, 1, 2, 3, 4 })]
30 | public int[] Test_Rotate_2(int[] nums, int steps)
31 | {
32 | rotater.Rotate_Solution_2(nums, steps);
33 | return nums;
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/RotateByKSteps/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/ShoppingCheckout/Problem/Checkout.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Linq;
3 |
4 | namespace ShoppingCheckout
5 | {
6 | public class Checkout
7 | {
8 | private static Dictionary itemPrices = new Dictionary()
9 | {
10 | { 'A', 20},
11 | { 'B', 30},
12 | { 'C', 10},
13 | { 'D', 25},
14 | { 'E', 15}
15 | };
16 |
17 | private static Dictionary> itemOffer = new Dictionary>()
18 | {
19 | {'A', new KeyValuePair(2, 30)}, { 'B', new KeyValuePair(5, 125) }
20 | };
21 |
22 | public static int ScanAndCheckout(string items)
23 | {
24 | var runningTotal = 0;
25 | var itemCounts = items.GroupBy(i => i).Select(group => new { Item = group.Key, Count = group.Count() });
26 | foreach (var itemCount in itemCounts)
27 | {
28 | // if we have an offer then apply it
29 | if (itemOffer.ContainsKey(itemCount.Item) && ((itemCount.Count >= itemOffer[itemCount.Item].Key)))
30 | {
31 | var offer = itemOffer[itemCount.Item];
32 | var offerMultiplier = (itemCount.Count / offer.Key);
33 | // apply offer n number of times where n = itemCount / offerOnNumber
34 | if (offerMultiplier > 0)
35 | {
36 | runningTotal += offerMultiplier * offer.Value;
37 | // then add remainder number of items at regular price
38 | var remainingNoOfferItemCount = itemCount.Count % offer.Key;
39 | runningTotal += remainingNoOfferItemCount * itemPrices[itemCount.Item];
40 | }
41 | }
42 | else
43 | {
44 | runningTotal += itemCount.Count * itemPrices[itemCount.Item];
45 | }
46 | }
47 | return runningTotal;
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/ShoppingCheckout/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("ShoppingCheckout")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("ShoppingCheckout")]
13 | [assembly: AssemblyCopyright("Copyright © 2018")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("0aceea37-92f1-4157-a7a1-fe80f2cef3ea")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/ShoppingCheckout/README.md:
--------------------------------------------------------------------------------
1 | # Shopping Checkout
2 |
3 | Let us assume that the table below represents the prices and offers available on items in this shop.
4 | The shop only has the following items.
5 | Implement a method to perform the checkout at the shop and add unit tests to prove that it works.
6 |
7 |
8 | | Item | Price | Offer |
9 | | ---- | ---- | ---- |
10 | | A | 20 | 2 for 30|
11 | | B | 30 | 5 for 125 |
12 | | C | 10 | |
13 | | D | 25 | |
14 | | E | 15 | |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/ShoppingCheckout/Tests/CheckoutTester.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using System.Collections;
3 |
4 | namespace ShoppingCheckout
5 | {
6 | [TestFixture]
7 | public class CheckoutTester
8 | {
9 | [Test, TestCaseSource(typeof(CheckoutTester), "TestItems")]
10 | public int ScanAndCheckOut(string items)
11 | {
12 | return Checkout.ScanAndCheckout(items);
13 | }
14 |
15 | public static IEnumerable TestItems
16 | {
17 | get
18 | {
19 | yield return new TestCaseData("ABCDE").Returns(100);
20 | yield return new TestCaseData("AABCDE").Returns(110);
21 | yield return new TestCaseData("AAABCDE").Returns(130);
22 | yield return new TestCaseData("AABBBBBCDE").Returns(205);
23 | yield return new TestCaseData("AABBBBBBCDE").Returns(235);
24 | }
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/ShoppingCheckout/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/StackMinimumQuestion/Problem/StackMinQuestion.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Linq;
3 |
4 | namespace StackMinimumQuestion.Problem
5 | {
6 | /*
7 | * Please note that it's Function problem i.e.
8 | * you need to write your solution in the form of Function(s) only.
9 | * Driver Code to call/invoke your function would be added by GfG's Online Judge.
10 | */
11 |
12 | public class StackMinQuestion
13 | {
14 | Stack s = new Stack();
15 | Stack minElements = new Stack();
16 |
17 | ///
18 | /// Returns min element from stack
19 | ///
20 | ///
21 | public int GetMin()
22 | {
23 | if (!s.Any())
24 | {
25 | return -1;
26 | }
27 | return minElements.Peek();
28 | }
29 |
30 | ///
31 | /// Returns popped element from stack
32 | ///
33 | ///
34 | public int Pop()
35 | {
36 | if (!s.Any())
37 | {
38 | return -1;
39 | }
40 | minElements.Pop();
41 | return s.Pop();
42 | }
43 |
44 | ///
45 | /// push element x into the stack
46 | /// if x is greater than the top minelement then
47 | /// push the top min element into the minelement stack again
48 | /// then insert x into stack
49 | /// If x is less or equal to top minelement then just push x into
50 | /// the minelements stack and so into the actual stack
51 | /// In short whether small or not you have to make sure you insert something into the
52 | /// minElement stack so that your pop method is simple.
53 | /// All the complexity of tracking minElement is in push.
54 | ///
55 | ///
56 | public void Push(int x)
57 | {
58 | if (minElements.Any())
59 | {
60 | if (minElements.Peek() < x)
61 | {
62 | minElements.Push(minElements.Peek());
63 | s.Push(x);
64 | }
65 | else
66 | {
67 | minElements.Push(x);
68 | s.Push(x);
69 | }
70 | }
71 | else
72 | {
73 | minElements.Push(x);
74 | s.Push(x);
75 | }
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/StackMinimumQuestion/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("StackMinimumQuestion")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("StackMinimumQuestion")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("3c5ad6e6-b303-459a-867c-59d439b7de76")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/StackMinimumQuestion/README.md:
--------------------------------------------------------------------------------
1 | Implement a Stack in which you can get min element in O(1) time and O(1) space.
2 |
3 | Input (To be used for Expected Output):
4 | The first line of the input contains an integer 'T' denoting the number of test cases. Then T test cases follow.
5 | First line of each test case contains an integer Q denoting the number of queries .
6 | A Query Q is of 3 Types
7 | (i) 1 x (a query of this type means pushing 'x' into the stack)
8 | (ii) 2 (a query of this type means to pop element from stack and print the poped element)
9 | (iii) 3 (a query of this type means to print the minimum element from the stack)
10 |
11 | The second line of each test case contains Q queries seperated by space.
12 |
13 | Output:
14 |
15 | The output for each test case will be space separated integers having -1 if the stack is empty else the element poped out or min element from the stack .
16 | You are required to complete the three methods push which take one argument an integer 'x' to be pushed into the stack , pop which returns a integer poped out from the stack and getMin which returns the min element from the stack.
17 |
18 | Constraints:
19 | 1<=T<=100
20 | 1<=Q<=100
21 | 1<=x<=100
22 |
23 | Example:
24 | Input
25 | 1
26 | 6
27 | 1 2 1 3 2 3 1 1 3
28 |
29 | Output
30 | 3 2 1
31 |
32 |
--------------------------------------------------------------------------------
/StackMinimumQuestion/Tests/StackMinTester.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using StackMinimumQuestion.Problem;
3 |
4 | namespace StackMinimumQuestionTester.Tests
5 | {
6 | [TestFixture]
7 | public class StackMinTester
8 | {
9 | [Test]
10 | public void StackMinTest1()
11 | {
12 | var gfg = new StackMinQuestion();
13 | gfg.Push(10);
14 | gfg.Push(5);
15 | gfg.Push(7);
16 | gfg.Push(9);
17 | gfg.Push(4);
18 | Assert.AreEqual(4, gfg.GetMin());
19 |
20 | gfg.Pop();
21 | Assert.AreEqual(5, gfg.GetMin());
22 | }
23 |
24 | [Test]
25 | public void StackMinTest2()
26 | {
27 | var gfg = new StackMinQuestion();
28 | gfg.Push(10);
29 | gfg.Push(9);
30 | gfg.Push(8);
31 | gfg.Push(7);
32 | gfg.Push(6);
33 | Assert.AreEqual(6, gfg.GetMin());
34 |
35 | gfg.Pop();
36 | Assert.AreEqual(7, gfg.GetMin());
37 |
38 |
39 | gfg.Pop();
40 | Assert.AreEqual(8, gfg.GetMin());
41 |
42 |
43 | gfg.Pop();
44 | Assert.AreEqual(9, gfg.GetMin());
45 | }
46 |
47 | [Test]
48 | public void StackMinTest3()
49 | {
50 | var gfg = new StackMinQuestion();
51 | gfg.Push(10);
52 | Assert.AreEqual(10, gfg.GetMin());
53 | }
54 |
55 | [Test]
56 | public void StackMinTest4()
57 | {
58 | var gfg = new StackMinQuestion();
59 | Assert.AreEqual(-1, gfg.GetMin());
60 | }
61 |
62 | [Test]
63 | public void StackMinTest5()
64 | {
65 | var gfg = new StackMinQuestion();
66 | gfg.Push(10);
67 | Assert.AreEqual(10, gfg.GetMin());
68 | gfg.Pop();
69 | Assert.AreEqual(-1, gfg.GetMin());
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/StackMinimumQuestion/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/SumTree/Problem/Node.cs:
--------------------------------------------------------------------------------
1 | namespace SumTree.Problem
2 | {
3 | public class Node
4 | {
5 | public int data;
6 | public Node left { get; set; }
7 | public Node right { get; set; }
8 |
9 | public Node(int value)
10 | {
11 | data = value;
12 | left = right = null;
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/SumTree/Problem/SumTreeQuestion.cs:
--------------------------------------------------------------------------------
1 | namespace SumTree.Problem
2 | {
3 | public class SumTreeQuestion
4 | {
5 | private static int Sum(Node root)
6 | {
7 | if (root == null)
8 | return 0;
9 | return Sum(root.left) + root.data + Sum(root.right);
10 | }
11 |
12 | public static bool IsSumTree(Node node)
13 | {
14 |
15 | //if null node or leaf node then it is a sumtree.
16 | if ((node == null) || (node.left == null && node.right == null))
17 | return true;
18 |
19 | int leftTreeSum = Sum(node.left);
20 | int rightTreeSum = Sum(node.right);
21 |
22 | if (node.data == (leftTreeSum + rightTreeSum) && IsSumTree(node.left) && IsSumTree(node.right))
23 | {
24 | return true;
25 | }
26 | return false;
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/SumTree/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("SumTree")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("SumTree")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("c89eb85f-83f9-435a-8914-3e3b912e2f53")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/SumTree/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | Write a function that returns true if the given Binary Tree is SumTree else false. A SumTree is a Binary Tree where value of every node x is equal to sum of nodes present in its left subtree and right subtree of x. An empty tree is SumTree and sum of an empty tree can be considered as 0. A leaf node is also considered as SumTree.
4 |
5 | Following is an example of SumTree.
6 |
7 | 26
8 | / \
9 | 10 3
10 | / \ / \
11 | 4 6 1 2
12 |
13 |
14 |
15 | Input:
16 |
17 | The task is to complete the method which takes one argument, root of Binary Tree. There are multiple test cases. For each test case, this method will be called individually.
18 |
19 | Output:
20 | The function should return true if passed tree is Sum Tree, else false
21 |
22 | Constraints:
23 | 1 <=T<= 30
24 | 1 <=Number of nodes<= 1000
25 | 1 <=Data of a node<= 1000
26 |
27 | Example:
28 | Input:
29 | 2
30 | 2
31 | 3 1 L 3 2 R
32 | 4
33 | 10 20 L 10 30 R 20 40 L 20 60 R
34 |
35 | Output:
36 | 1
37 | 0
38 |
39 | There are two test cases. First case represents a tree with 3 nodes and 2 edges where root is 3, left child of 3 is 1 and right child of 3 is 2. Second test case represents a tree with 4 edges and 5 nodes.
--------------------------------------------------------------------------------
/SumTree/Tests/SumTreeTest.cs:
--------------------------------------------------------------------------------
1 | using SumTree.Problem;
2 | using NUnit.Framework;
3 |
4 | namespace SumTreeQuestionTester.Tests
5 | {
6 | [TestFixture]
7 | public class SumTreeTest
8 | {
9 | [Test]
10 | public void IsSumTreeTest_1()
11 | {
12 | var root = new Node(26);
13 | root.left = new Node(10);
14 | root.right = new Node(3);
15 | root.left.left = new Node(4);
16 | root.left.right = new Node(6);
17 | root.right.right = new Node(3);
18 |
19 | Assert.AreEqual(true, SumTreeQuestion.IsSumTree(root));
20 | }
21 |
22 | [Test]
23 | public void IsSumTreeTest_2()
24 | {
25 | var root = new Node(3);
26 | root.left = new Node(1);
27 | root.right = new Node(2);
28 |
29 | Assert.AreEqual(true, SumTreeQuestion.IsSumTree(root));
30 | }
31 |
32 | [Test]
33 | public void IsSumTreeTest_3()
34 | {
35 | var root = new Node(10);
36 | root.left = new Node(20);
37 | root.right = new Node(30);
38 | root.left.left = new Node(40);
39 | root.left.right = new Node(60);
40 |
41 | Assert.AreEqual(false, SumTreeQuestion.IsSumTree(root));
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/SumTree/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/SumTwoNumbers/Improved/Solution.cs:
--------------------------------------------------------------------------------
1 | namespace SumTwoNumbers.Improved
2 | {
3 | public class Solution
4 | {
5 | public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
6 | {
7 | var headL1 = l1;
8 | var headL2 = l2;
9 | var headSum = new ListNode(0);
10 | var current = headSum;
11 | int carryOver = 0;
12 | while (headL1 != null || headL2 != null)
13 | {
14 | int val1 = headL1 != null ? headL1.val : 0;
15 | int val2 = headL2 != null ? headL2.val : 0;
16 | int sumVal = val1 + val2 + carryOver;
17 | carryOver = sumVal / 10;
18 | int newVal = sumVal % 10;
19 | current.val += newVal;
20 |
21 | if (headL1 != null)
22 | {
23 | headL1 = headL1.next;
24 | }
25 |
26 | if (headL2 != null)
27 | {
28 | headL2 = headL2.next;
29 | }
30 | if (headL1 != null || headL2 != null)
31 | {
32 | var next = new ListNode(0);
33 | current.next = next;
34 | current = current.next;
35 | }
36 | }
37 | if (carryOver > 0)
38 | {
39 | current.next = new ListNode(carryOver);
40 | }
41 | return headSum;
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/SumTwoNumbers/Improved/SolutionTestCases.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using System.Collections.Generic;
3 |
4 | namespace SumTwoNumbers.Improved
5 | {
6 | public class SolutionTestCases
7 | {
8 | public static IEnumerable SolutionTestCaseInputAndExpectations
9 | {
10 | get
11 | {
12 | var listNode1 = TestHelper.CreateListNode("243");
13 | var listNode2 = TestHelper.CreateListNode("564");
14 | var resultNode = TestHelper.CreateListNode("708");
15 | yield return new TestCaseData(listNode1, listNode2, resultNode).Returns(true);
16 |
17 | listNode1 = TestHelper.CreateListNode("1");
18 | listNode2 = TestHelper.CreateListNode("2");
19 | resultNode = TestHelper.CreateListNode("3");
20 | yield return new TestCaseData(listNode1, listNode2, resultNode).Returns(true);
21 |
22 | listNode1 = TestHelper.CreateListNode("12");
23 | listNode2 = TestHelper.CreateListNode("13");
24 | resultNode = TestHelper.CreateListNode("25");
25 | yield return new TestCaseData(listNode1, listNode2, resultNode).Returns(true);
26 |
27 | listNode1 = TestHelper.CreateListNode("0");
28 | listNode2 = TestHelper.CreateListNode("0");
29 | resultNode = TestHelper.CreateListNode("0");
30 | yield return new TestCaseData(listNode1, listNode2, resultNode).Returns(true);
31 |
32 | //listNode1 = TestHelper.CreateListNode("9");
33 | //listNode2 = TestHelper.CreateListNode("19999999999");
34 | //resultNode = TestHelper.CreateListNode("000000000001");
35 | //yield return new TestCaseData(listNode1, listNode2, resultNode).Returns(true);
36 |
37 | listNode1 = TestHelper.CreateListNode("9");
38 | listNode2 = TestHelper.CreateListNode("199");
39 | resultNode = TestHelper.CreateListNode("0001");
40 | yield return new TestCaseData(listNode1, listNode2, resultNode).Returns(true);
41 |
42 | listNode1 = TestHelper.CreateListNode("564");
43 | listNode2 = TestHelper.CreateListNode("1000000000000000000000000000001");
44 | resultNode = TestHelper.CreateListNode("6640000000000000000000000000001");
45 | yield return new TestCaseData(listNode1, listNode2, resultNode).Returns(true);
46 | }
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/SumTwoNumbers/Improved/SolutionTests.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 |
3 | namespace SumTwoNumbers.Improved
4 | {
5 | [TestFixture]
6 | public class SolutionTests
7 | {
8 | private Solution _solution = new Solution();
9 | [TestCaseSource(typeof(SolutionTestCases), "SolutionTestCaseInputAndExpectations")]
10 | public bool SumTwoLinkedListNumbersTest(ListNode ln1, ListNode ln2, ListNode resultNode)
11 | {
12 | var sumOfTwoListNodes = _solution.AddTwoNumbers(ln1, ln2);
13 | return TestHelper.AreNodesEqual(sumOfTwoListNodes, resultNode);
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/SumTwoNumbers/ListNode.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text;
3 |
4 | namespace SumTwoNumbers
5 | {
6 | public class ListNode
7 | {
8 | public int val;
9 | public ListNode next;
10 | public ListNode(int val = 0, ListNode next = null)
11 | {
12 | this.val = val;
13 | this.next = next;
14 | }
15 | public override string ToString()
16 | {
17 | if (next == null)
18 | {
19 | return $"|Data:{val}|next:null|";
20 | }
21 | return $"|Data:{val}|next:->|";
22 | }
23 |
24 | public override bool Equals(Object obj)
25 | {
26 | //Check for null and compare run-time types.
27 | if ((obj == null) || !this.GetType().Equals(obj.GetType()))
28 | {
29 | return false;
30 | }
31 | else
32 | {
33 | ListNode ln = (ListNode)obj;
34 | return this.val == ln.val;
35 | }
36 | }
37 |
38 | public override int GetHashCode()
39 | {
40 | return val;
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/SumTwoNumbers/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("SumTwoNumbers")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("SumTwoNumbers")]
13 | [assembly: AssemblyCopyright("Copyright © 2020")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("704fb2d6-ab3a-4080-9e96-b7c1e8324a6c")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/SumTwoNumbers/README.md:
--------------------------------------------------------------------------------
1 | # Markdown File
2 |
3 | You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
4 |
5 | You may assume the two numbers do not contain any leading zero, except the number 0 itself.
6 |
7 | Example:
8 |
9 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
10 | Output: 7 -> 0 -> 8
11 | Explanation: 342 + 465 = 807.
12 |
13 |
--------------------------------------------------------------------------------
/SumTwoNumbers/Solution.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace SumTwoNumbers
4 | {
5 | public class Solution
6 | {
7 | public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
8 | {
9 | // read number from l1
10 | // in the right order
11 | // read number from l2 right order
12 | // add numbers and create final list.
13 |
14 | // read number1
15 | long number1 = GetNumber(l1);
16 |
17 | // read number 2
18 | var numListNode2 = l2;
19 | long number2 = GetNumber(l2);
20 |
21 | long sum = number2 + number1;
22 | return CreateListNode(sum);
23 | }
24 |
25 | private static long GetNumber(ListNode l1)
26 | {
27 | var numListNode1 = l1;
28 | long number1 = 0;
29 | long iterationCounter = 0;
30 | while (numListNode1 != null)
31 | {
32 | number1 += numListNode1.val * (long) Math.Pow(10, iterationCounter);
33 | numListNode1 = numListNode1.next;
34 | iterationCounter++;
35 | }
36 | return number1;
37 | }
38 |
39 | public static ListNode CreateListNode(long numValue)
40 | {
41 | ListNode resultNode = null;
42 | ListNode previousNode = null;
43 | long iterationCounter = 1;
44 | if (numValue == 0)
45 | {
46 | return new ListNode(0);
47 | }
48 | while (numValue > 0)
49 | {
50 | int num = (int)(numValue % 10);
51 | var newNode = new ListNode(num);
52 | if (iterationCounter == 1)
53 | {
54 | resultNode = newNode;
55 | }
56 | if (previousNode != null)
57 | {
58 | previousNode.next = newNode;
59 | previousNode = newNode;
60 | }
61 | else
62 | {
63 | previousNode = newNode;
64 | }
65 | iterationCounter++;
66 | numValue /= 10;
67 | }
68 | return resultNode;
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/SumTwoNumbers/TestHelper.cs:
--------------------------------------------------------------------------------
1 | namespace SumTwoNumbers
2 | {
3 | public class TestHelper
4 | {
5 | // takes in a number in the right format and puts it into ListNode
6 | // "245" => 2-> 4-> 5-> null
7 | public static ListNode CreateListNode(string numValue)
8 | {
9 | ListNode head = null;
10 | ListNode previous = null;
11 | for (int i = 0; i < numValue.Length; i++)
12 | {
13 | var oneChar = numValue[i];
14 | var charInt = int.Parse(oneChar.ToString());
15 | var node = new ListNode(charInt);
16 | if (head == null)
17 | {
18 | head = node;
19 | }
20 | if (previous != null)
21 | {
22 | previous.next = node;
23 | }
24 | previous = node;
25 | }
26 | return head;
27 | }
28 |
29 | public static bool AreNodesEqual(ListNode ln1, ListNode ln2)
30 | {
31 | var list1 = ln1;
32 | var list2 = ln2;
33 |
34 | while (list1 != null && list2 != null)
35 | {
36 | if (!list1.Equals(list2))
37 | {
38 | return false;
39 | }
40 |
41 | list1 = list1.next;
42 | list2 = list2.next;
43 | }
44 | return true;
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/SumTwoNumbers/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/SwapNodes/Node.cs:
--------------------------------------------------------------------------------
1 | namespace SwapNodes
2 | {
3 | public class Node
4 | {
5 | public int data;
6 | public Node next;
7 | public Node(int d)
8 | {
9 | data = d;
10 | next = null;
11 | }
12 |
13 | public override string ToString()
14 | {
15 | if (next == null)
16 | {
17 | return $"|Data:{data}|next:null|";
18 | }
19 | return $"|Data:{data}|next:->|";
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/SwapNodes/NodeSwapper.cs:
--------------------------------------------------------------------------------
1 | namespace SwapNodes
2 | {
3 | public class NodeSwapper
4 | {
5 | public LinkedList demoLinkedList { get; set; }
6 | public NodeSwapper(LinkedList linkedList)
7 | {
8 | demoLinkedList = linkedList;
9 | }
10 | public LinkedList SwapNodes(int x, int y)
11 | {
12 | demoLinkedList.SwapNodes(x, y);
13 | return demoLinkedList;
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/SwapNodes/NodeSwapperTests.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using System.Collections.Generic;
3 |
4 | namespace SwapNodes
5 | {
6 | [TestFixture]
7 | public class NodeSwapperTests
8 | {
9 | [TestCaseSource(typeof(LinkedListSwapTestCases), "TestCaseInputAndExpectations")]
10 | public string SwapNodesTest(LinkedList list, int x, int y)
11 | {
12 | list.SwapNodes(x, y);
13 | return list.ToString();
14 | }
15 |
16 | [Test]
17 | public void ToStringTest()
18 | {
19 | var list = new LinkedList(new int[] { 45 });
20 | Assert.AreEqual(list.ToString(), "|Data:45|next:null|");
21 | }
22 | }
23 |
24 | public class LinkedListSwapTestCases
25 | {
26 | public static IEnumerable TestCaseInputAndExpectations
27 | {
28 | get
29 | {
30 | var inputLinkedList = new LinkedList(new int[] { 1, 2, 3, 4 });
31 | var afterSwap = new LinkedList(new int[] { 1, 3, 2, 4 });
32 | yield return new TestCaseData(inputLinkedList, 2, 3).Returns(afterSwap.ToString());
33 |
34 | inputLinkedList = new LinkedList(new int[] { 1, 2, 5, 3, 4 });
35 | afterSwap = new LinkedList(new int[] { 1, 3, 5, 2, 4 });
36 | yield return new TestCaseData(inputLinkedList, 2, 3).Returns(afterSwap.ToString());
37 |
38 | inputLinkedList = new LinkedList(new int[] { 1 });
39 | afterSwap = new LinkedList(new int[] { 1 });
40 | yield return new TestCaseData(inputLinkedList, 2, 3).Returns(afterSwap.ToString());
41 |
42 | yield return new TestCaseData(inputLinkedList, 1, 1).Returns(afterSwap.ToString());
43 |
44 | inputLinkedList = new LinkedList(new int[] { 1, 2, 5, 3, 4 });
45 | afterSwap = new LinkedList(new int[] { 4, 2, 5, 3, 1 });
46 | yield return new TestCaseData(inputLinkedList, 1, 4).Returns(afterSwap.ToString());
47 |
48 | }
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/SwapNodes/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("SwapNodes")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("SwapNodes")]
13 | [assembly: AssemblyCopyright("Copyright © 2020")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("6c8d937f-fa89-4f57-9a1e-f991e4ad5e62")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/SwapNodes/README.md:
--------------------------------------------------------------------------------
1 | # Markdown File
2 |
3 |
4 | Swap nodes in a linked list without swapping data
5 | Last Updated: 13-02-2020
6 |
7 | Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields.
8 |
9 | It may be assumed that all keys in linked list are distinct.
10 |
11 | Examples:
12 |
13 | Input: 10->15->12->13->20->14, x = 12, y = 20
14 | Output: 10->15->20->13->12->14
15 |
16 | Input: 10->15->12->13->20->14, x = 10, y = 20
17 | Output: 20->15->12->13->10->14
18 |
19 | Input: 10->15->12->13->20->14, x = 12, y = 13
20 | Output: 10->15->13->12->20->14
21 |
22 | https://www.geeksforgeeks.org/swap-nodes-in-a-linked-list-without-swapping-data/
--------------------------------------------------------------------------------
/SwapNodes/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/TheMaximumNumberWithAllDigitsInANumber/Problem/MaxNumberFinder.cs:
--------------------------------------------------------------------------------
1 | using System.Linq;
2 |
3 | namespace TheMaximumNumberWithAllDigitsInANumber.Problem
4 | {
5 | public class MaxNumberFinder
6 | {
7 | public static long MaxNumberWithAllDigitsInANumber(long number)
8 | {
9 | var sortedCharArrayString = string.Join("", number.ToString()
10 | .ToCharArray()
11 | .OrderByDescending(e => e)
12 | .ToArray());
13 | return long.Parse(sortedCharArrayString);
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/TheMaximumNumberWithAllDigitsInANumber/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("TheMaximumNumberWithAllDigitsInANumber")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("TheMaximumNumberWithAllDigitsInANumber")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("c3c2f4de-e3b6-4ce7-9479-31b90ffd8faf")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/TheMaximumNumberWithAllDigitsInANumber/README.txt:
--------------------------------------------------------------------------------
1 | Given a number, write a program to find a maximum number that can be formed using all of the digits of this number.
2 |
3 | Input:
4 |
5 | The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. The first line of each test case contains the number N.
6 |
7 | Output:
8 |
9 | Print the largest number that can be formed using the digits of the given number. Print the answer for each test case in a new line.
10 |
11 |
12 | Constraints:
13 |
14 | 1<= T <=100
15 |
16 | 1<= N <=101000
17 |
18 |
19 | Example:
20 |
21 | Input:
22 |
23 | 2
24 |
25 | 38293367
26 |
27 | 1203465
28 |
29 | Output:
30 |
31 | 98763332
32 |
33 | 6543210
--------------------------------------------------------------------------------
/TheMaximumNumberWithAllDigitsInANumber/Tests/MaxNumberFinderTest.cs:
--------------------------------------------------------------------------------
1 | using TheMaximumNumberWithAllDigitsInANumber.Problem;
2 | using NUnit.Framework;
3 |
4 | namespace TheMaximumNumberWithAllDigitsInANumberTester.Tests
5 | {
6 | [TestFixture]
7 | public class MaxNumberFinderTest
8 | {
9 | [Test, TestCaseSource(typeof(MaxNumberFinderTestInput), "TestCases")]
10 | public long MaxNumberInAnotherNumberTest(long number)
11 | {
12 | return MaxNumberFinder.MaxNumberWithAllDigitsInANumber(number);
13 | }
14 |
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/TheMaximumNumberWithAllDigitsInANumber/Tests/MaxNumberFinderTestInput.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using NUnit.Framework;
3 |
4 | namespace TheMaximumNumberWithAllDigitsInANumberTester.Tests
5 | {
6 | [TestFixture]
7 | public class MaxNumberFinderTestInput
8 | {
9 | public static IEnumerable TestCases
10 | {
11 | get
12 | {
13 | yield return new TestCaseData(38293367).Returns(98763332);
14 | yield return new TestCaseData(1203465).Returns(6543210);
15 | }
16 | }
17 |
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/TheMaximumNumberWithAllDigitsInANumber/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/TimeComplexity:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/UtopianTree/Problem/HeightCalculator.cs:
--------------------------------------------------------------------------------
1 | namespace UtopianTree
2 | {
3 | public class HeightCalculator
4 | {
5 | public static int HeightFinder(int growthCycles)
6 | {
7 | int height = 1;
8 | for(int cycle = 1; cycle <= growthCycles; cycle++)
9 | {
10 | if (cycle % 2 != 0)
11 | {
12 | height = 2 * height;
13 | }
14 | else
15 | {
16 | height = height + 1;
17 | }
18 | }
19 | return height;
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/UtopianTree/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("UtopianTree")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("UtopianTree")]
13 | [assembly: AssemblyCopyright("Copyright © 2018")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("be92673e-8c06-4d11-9970-5f0d682a66c8")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/UtopianTree/README.md:
--------------------------------------------------------------------------------
1 | # Utopian Tree
2 |
3 | Once upon a time in Utopia, there was this wonderful tree that people were fond of.
4 | It had a very interesting growth pattern. Every year, it had `two growth cycles`.
5 | One during monsoon and the other during summer.
6 |
7 | * During monsoon, the tree grew `twice its height`
8 | * During summer, it grew just `1 additional meter`
9 |
10 | If a utopian citizen were to plant a sapling of this tree of `1 meter` height in the onset of monsoon, could you tell what the height of the tree would be after `n` growth cycles would be?
11 |
12 | ## Key concepts
13 |
14 | * Count from the onset of monsoon.
15 | * Initial height is `1 meter`
16 | * During monsoon, it grows twice its height. So by the end of first growth cycle it will be `2 meters` tall.
17 | * During summer, it grows an additional meter. So after 2 growth cycles it will be `3 meters` tall.
18 | * So growth can be categorized into two cycles:
19 | * Odd cycle - `2 x height`
20 | * Even cycle - `height + 1`
21 |
22 |
--------------------------------------------------------------------------------
/UtopianTree/Tests/HeightTester.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using NUnit.Framework;
3 | using UtopianTree;
4 |
5 | namespace UtopianTreeTester
6 | {
7 | [TestFixture]
8 | public class HeightTester
9 | {
10 | [Test, TestCaseSource(typeof(UtopianTreeHeightInput), "TestGrowthCycles")]
11 | public int HeightCalculateTest(int growthCycles)
12 | {
13 | return HeightCalculator.HeightFinder(growthCycles);
14 | }
15 | }
16 |
17 | public class UtopianTreeHeightInput
18 | {
19 | public static IEnumerable TestGrowthCycles
20 | {
21 | get
22 | {
23 | yield return new TestCaseData(2).Returns(3).SetName("Height after 2 cycles");
24 | yield return new TestCaseData(3).Returns(6).SetName("Height after 3 cycles");
25 | yield return new TestCaseData(6).Returns(15).SetName("Height after 6 cycles");
26 | yield return new TestCaseData(10).Returns(63).SetName("Height after 10 cycles");
27 | yield return new TestCaseData(20).Returns(2047).SetName("Height after 20 cycles");
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/UtopianTree/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------