├── Easy - 10 - Alphabet Soup.js ├── Easy - 05 - Simple Adding.js ├── Easy - 09 - Time Convert.js ├── Easy - 26 - Third Greatest.js ├── Easy - 01 - First Reverse.js ├── Easy - 02 - First Factorial.js ├── Easy - 08 - Check Nums.js ├── Easy - 13 - Word Count.js ├── Medium - 05 - Division.js ├── Medium - 24 - Three Five Multiples.js ├── Easy - 27 - Powers of Two.js ├── Medium - 01 - Prime Time.js ├── Medium - 09 - Binary Converter.js ├── Easy - 25 - Number Addition.js ├── Easy - 12 - Vowel Count.js ├── Medium - 30 - Distinct List.js ├── Easy - 06 - Letter Capitalize.js ├── Easy - 14 - Ex Oh.js ├── Easy - 03 - Longest Word.js ├── Medium - 06 - String Scramble.js ├── Medium - 26 - Fibonacci Checker.js ├── Medium - 13 - Consecutive.js ├── Medium - 03 - Prime Mover.js ├── Medium - 21 - Triple Double.js ├── Medium - 31 - Number Encoding ├── Hard - 03 - Calculator ├── Easy - 15 - Palindrome.js ├── Easy - 23 - Dash Insert.js ├── Easy - 07 - Simple Symbols.js ├── Easy - 24 - Swap Case.js ├── Medium - 02 - Run Length.js ├── Easy - 11 - AB Check.js ├── Easy - 19 - Second GreatLow.js ├── README.md ├── Medium - 20 - Number Search.js ├── Easy - 28 - Additive Persistence.js ├── Medium - 04 - Palindrome Two.js ├── Medium - 29 - Look Say Sequence.js ├── Easy - 29 - Multiplicative Persistence.js ├── Easy - 04 - Letter Changes.js ├── Medium - 22 - Bracket Matcher.js ├── Easy - 20 - Division Stringified.js ├── Hard - 02 - Hamiltonian Path ├── Medium - 18 - Dash Insert II.js ├── C# - Find Distinct Numbers In An Array ├── Medium - 12 - Simple Mode.js ├── C# - Buldings Facing Sunset ├── Easy - 17 - Array Addition.js ├── Medium - 07 - Arith Geo II.js ├── Medium - 19 - Swap II.js ├── Easy - 16 - Arith Geo.js ├── C# - Print Numbers Pyramid ├── Medium - 14 - Formatted Division.js ├── Medium - 08 - Array Addition.js ├── C# - Majority Eelement In An Array ├── C# - Merge Sorted Arrays In Sorted Order ├── Easy - 22 - Mean Mode.js ├── Hard - 04 - Pattern Chaser ├── C# - Are Strings Anagrams ├── Medium - 27 - Multiple Brackets.js ├── C# - Find Nth Minimum Value ├── Easy - 18 - Letter Count I.js ├── Medium - 16 - Permutation Step.js ├── Medium - 10 - Letter Count.js ├── Medium - 15 - Counting Minutes.js ├── Easy - 21 - Counting Minutes I.js ├── C# - Find Next Greater Element Using Stack ├── Hard - 05 - Gas Station ├── C# - Find Continuous Sub Array ├── Medium - 11 - Caesar Cipher.js ├── Medium - 23 - String Reduction.js ├── Medium - 25 - Coin Determiner ├── Hard - 09 - Knight Jumps ├── C# - Count Negative Integers In A Sorted Matrix ├── Easy - 30 - Off Line Minimum.js ├── Medium - 17 - Prime Checker.js ├── C# - Product Of Numbers ├── C# - LongRunChar ├── C# - Find Subsets ├── C# - Check If An Array Is Polindrome ├── C# - Addition Between Numbers In Two Arrays ├── C# - Find All Jumping Numbers ├── C# - Common Functions ├── C# - Nth Prime Number ├── Medium - 32 - Overlapping Rectangles ├── C# - Print Matrix In Spiral Form ├── Hard - 11 - Queen Check ├── Hard - 10 - Symmetric Matrix ├── C# - Number To Words ├── Hard - 08 - Optimal Assignments ├── C# - Gas Station ├── Hard - 12 - Shortest Path ├── Medium - 28 - Most Free Time ├── Hard - 07 - Noughts Determiner ├── Hard - 13 - Weighted Path ├── Hard - 06 - Matrix Determinant ├── C# - Convert Number To BaseN Value and Viceversa ├── C# - Remove Comments From Code File ├── Hard - 01 - Alphabet Run Encryption ├── C# - Array Searching Algorithms ├── C# - Event Hit Counter ├── C# - Encoding And Decoding ├── C# - Array Sorting Algorithms ├── C# - Doubly Linked List └── C# - Binary Tree /Easy - 10 - Alphabet Soup.js: -------------------------------------------------------------------------------- 1 | function AlphabetSoup(str) { 2 | var arr=str.split(''); 3 | arr.sort() 4 | return arr.join(''); 5 | } 6 | -------------------------------------------------------------------------------- /Easy - 05 - Simple Adding.js: -------------------------------------------------------------------------------- 1 | function SimpleAdding(num) { 2 | var res=0; 3 | for(var i=1;i<=num;i++) 4 | res+=i; 5 | return res; 6 | } 7 | -------------------------------------------------------------------------------- /Easy - 09 - Time Convert.js: -------------------------------------------------------------------------------- 1 | function TimeConvert(num) { 2 | var minutes=num%60; 3 | var hours=parseInt(num/60); 4 | return hours+':'+minutes; 5 | } 6 | -------------------------------------------------------------------------------- /Easy - 26 - Third Greatest.js: -------------------------------------------------------------------------------- 1 | function ThirdGreatest(strArr) { 2 | strArr.sort(function (a, b) { return b.length - a.length }) 3 | return strArr[2]; 4 | } 5 | -------------------------------------------------------------------------------- /Easy - 01 - First Reverse.js: -------------------------------------------------------------------------------- 1 | function FirstReverse(str) { 2 | var res=''; 3 | for(var i=str.length-1;i>=0;i--) 4 | res+=str[i]; 5 | return res; 6 | } 7 | -------------------------------------------------------------------------------- /Easy - 02 - First Factorial.js: -------------------------------------------------------------------------------- 1 | function FirstFactorial(num) { 2 | if(num==1) 3 | return 1; 4 | else 5 | return num * FirstFactorial(num-1); 6 | } 7 | -------------------------------------------------------------------------------- /Easy - 08 - Check Nums.js: -------------------------------------------------------------------------------- 1 | function CheckNums(num1,num2) { 2 | if(num1==num2) 3 | return '-1'; 4 | else if(num1 < num2) 5 | return 'true'; 6 | else 7 | return 'false' 8 | } 9 | -------------------------------------------------------------------------------- /Easy - 13 - Word Count.js: -------------------------------------------------------------------------------- 1 | function WordCount(str) { 2 | var count=0; 3 | for(var i=0;i num2 ? num2 : num1; 3 | for (var i = lowest; i >= 1; i--) { 4 | if (num1 % i == 0 && num2 % i == 0) 5 | return i; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Medium - 24 - Three Five Multiples.js: -------------------------------------------------------------------------------- 1 | function ThreeFiveMultiples(num) { 2 | var res=0; 3 | for(var i=1;i=0;i--,j++) 4 | { 5 | decimal+=parseInt(str[i])*Math.pow(2,j); 6 | } 7 | return decimal; 8 | } 9 | -------------------------------------------------------------------------------- /Easy - 25 - Number Addition.js: -------------------------------------------------------------------------------- 1 | function NumberAddition(str) { 2 | var matches=str.match(/\d+/g); 3 | var count=0; 4 | for(var i=0;i longestSoFar.length ? currentWord : longestSoFar; 5 | }); 6 | return longestWord; 7 | } 8 | -------------------------------------------------------------------------------- /Medium - 06 - String Scramble.js: -------------------------------------------------------------------------------- 1 | function StringScramble(str1,str2) { 2 | var arr=str1.split(''); 3 | for(var i=0; i= 'a' && c <= 'z') { 6 | var n = str.charCodeAt(i); 7 | encodedStr += n - 96; 8 | } 9 | else 10 | encodedStr += c; 11 | } 12 | return encodedStr; 13 | } 14 | -------------------------------------------------------------------------------- /Hard - 03 - Calculator: -------------------------------------------------------------------------------- 1 | function Calculator(str) { 2 | var arithmeticOperators = ['+', '-', '/', '*']; 3 | var replacedStr = str.replace(/(.)\(/g, function (match, g1) { 4 | if (arithmeticOperators.indexOf(g1) != -1) 5 | return match; 6 | else 7 | return match.replace(g1, g1 + '*'); 8 | }); 9 | return eval(replacedStr); 10 | } 11 | -------------------------------------------------------------------------------- /Easy - 15 - Palindrome.js: -------------------------------------------------------------------------------- 1 | function Palindrome(str) { 2 | var input='',reverse=''; 3 | for(var i=0;i='a' && str[i]<='z') 5 | { 6 | if( (i-1 >=0) && (i+1= 'a' && c <= 'z') { 6 | result += c.toUpperCase(); 7 | } 8 | else if (c >= 'A' && c <= 'Z') { 9 | result += c.toLowerCase(); 10 | } 11 | else 12 | result += c; 13 | } 14 | return result; 15 | } 16 | -------------------------------------------------------------------------------- /Medium - 02 - Run Length.js: -------------------------------------------------------------------------------- 1 | function RunLength(str) { 2 | var runChar = str[0], runCount = 1, res = ''; 3 | for (var i = 1; i < str.length; i++) { 4 | if (runChar == str[i]) { 5 | runCount++; 6 | } 7 | else { 8 | res += runCount + runChar; 9 | runChar = str[i]; 10 | runCount = 1; 11 | } 12 | } 13 | res += runCount + runChar; 14 | return res; 15 | } 16 | -------------------------------------------------------------------------------- /Easy - 11 - AB Check.js: -------------------------------------------------------------------------------- 1 | //Without using regular expressions 2 | function ABCheck(str) { 3 | for (var i = 0; i < str.length - 4; i++) 4 | { 5 | var c1 = str[i].toLowerCase(); 6 | var c2 = str[i + 4].toLowerCase(); 7 | if (c1 == 'a' && c2 == 'b') 8 | return 'true'; 9 | else if (c1 == 'b' && c2 == 'a') 10 | return 'true'; 11 | } 12 | return 'false'; 13 | } 14 | -------------------------------------------------------------------------------- /Easy - 19 - Second GreatLow.js: -------------------------------------------------------------------------------- 1 | function SecondGreatLow(arr) { 2 | var distinct=[]; 3 | for(var i=0;i='a' && c<='z') || (c>='A' && c<='Z')) 8 | letterCount++; 9 | else 10 | { 11 | var n=parseInt(c); 12 | if(n) 13 | numbers.push(n); 14 | } 15 | } 16 | var sum=numbers.reduce(function(pv,v){return pv+v;}) 17 | return Math.round(sum/letterCount); 18 | } 19 | -------------------------------------------------------------------------------- /Easy - 28 - Additive Persistence.js: -------------------------------------------------------------------------------- 1 | function AdditivePersistence(num) { 2 | var additiveCount = 0; 3 | function Add(num) { 4 | var result = 0; 5 | var arr = num.toString().split(''); 6 | for (var i = 0; i < arr.length; i++) { 7 | result += parseInt(arr[i]); 8 | } 9 | additiveCount++; 10 | if (result > 9) 11 | Add(result); 12 | } 13 | 14 | if (num <= 9) 15 | return 0; 16 | else { 17 | Add(num); 18 | return additiveCount; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Medium - 04 - Palindrome Two.js: -------------------------------------------------------------------------------- 1 | function PalindromeTwo(str) { 2 | var input = '', reverse = ''; 3 | for (var i = 0; i < str.length; i++) { 4 | var c = str[i]; 5 | //to ignore spaces and symbols in the input string 6 | if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { 7 | input = input + c; 8 | reverse = c + reverse; 9 | } 10 | } 11 | 12 | if (input.toLowerCase() === reverse.toLowerCase()) 13 | return 'true'; 14 | else 15 | return 'false'; 16 | } 17 | -------------------------------------------------------------------------------- /Medium - 29 - Look Say Sequence.js: -------------------------------------------------------------------------------- 1 | function LookSaySequence(num) { 2 | var result = ""; 3 | num = num.toString(); 4 | var previousNum = num[0], count = 1; 5 | for (var i = 1; i < num.length; i++) { 6 | var n = num[i]; 7 | if (previousNum == n) { 8 | count++; 9 | } else { 10 | result += count + '' + previousNum; 11 | previousNum = n; 12 | count = 1; 13 | } 14 | } 15 | //to concatenate last digit result 16 | result += count + '' + previousNum; 17 | return result; 18 | } 19 | -------------------------------------------------------------------------------- /Easy - 29 - Multiplicative Persistence.js: -------------------------------------------------------------------------------- 1 | function MultiplicativePersistence(num) { 2 | var multiplicativeCount = 0; 3 | function Multiply(num) { 4 | var result = 1; 5 | var arr = num.toString().split(''); 6 | for (var i = 0; i < arr.length; i++) { 7 | result *= parseInt(arr[i]); 8 | } 9 | multiplicativeCount++; 10 | if (result > 9) 11 | Multiply(result); 12 | } 13 | 14 | if (num <= 9) 15 | return 0; 16 | else { 17 | Multiply(num); 18 | return multiplicativeCount; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Easy - 04 - Letter Changes.js: -------------------------------------------------------------------------------- 1 | function LetterChanges(str) { 2 | var vowels = 'aeiou', result = '', changedChar; 3 | for (i = 0; i < str.length; i++) { 4 | var c = str.charCodeAt(i); 5 | if (c >= 97 && c < 122) 6 | changedChar = String.fromCharCode(c + 1); 7 | else if (c == 122) 8 | changedChar = String.fromCharCode(97); 9 | else 10 | changedChar = str[i]; 11 | 12 | if (vowels.indexOf(changedChar) != -1) 13 | changedChar = changedChar.toUpperCase(); 14 | 15 | result += changedChar; 16 | } 17 | return result; 18 | } 19 | -------------------------------------------------------------------------------- /Medium - 22 - Bracket Matcher.js: -------------------------------------------------------------------------------- 1 | function BracketMatcher(str) { 2 | var openBrackets = []; 3 | for (var i = 0; i < str.length; i++) { 4 | var c = str[i]; 5 | if (c == '(' || c == '[') { 6 | openBrackets.push(c); 7 | } 8 | else if (c == ')' || c == ']') { 9 | var lastOpenBracket = openBrackets.pop(); 10 | if ((c == ')' && lastOpenBracket != '(') || 11 | (c == ']' && lastOpenBracket != '[') ) 12 | return 0; 13 | } 14 | } 15 | 16 | if (openBrackets.length > 0) 17 | return 0; 18 | else 19 | return 1; 20 | } 21 | -------------------------------------------------------------------------------- /Easy - 20 - Division Stringified.js: -------------------------------------------------------------------------------- 1 | function DivisionStringified(num1,num2) { 2 | var res = Math.round(num1 / num2); 3 | var str = res.toString(); 4 | var output = ''; 5 | if (str.length < 4) { 6 | output = str; 7 | } 8 | else { 9 | var commaPos = 4; 10 | for (var i = str.length - 1, pos = 1; i >= 0; i--, pos++) { 11 | if (pos == commaPos) { 12 | output = str[i] + ',' + output; 13 | commaPos += 3; 14 | } 15 | else { 16 | output = str[i] + output; 17 | } 18 | } 19 | } 20 | return output; 21 | } 22 | -------------------------------------------------------------------------------- /Hard - 02 - Hamiltonian Path: -------------------------------------------------------------------------------- 1 | function HamiltonianPath(strArr) { 2 | var inVertices = strArr[0].replace(/[\(,\)]/g, '').split(''); 3 | var edges= strArr[1].replace(/[\(\)]/g, '').split(','); 4 | var outVertices = strArr[2].replace(/[\(,\)]/g, '').split(''); 5 | for (var i = 0; i < outVertices.length - 1; i++) { 6 | var edgeR = outVertices[i] + '-' + outVertices[i + 1]; 7 | var edgeL = outVertices[i + 1] + '-' + outVertices[i]; 8 | if (edges.indexOf(edgeR) == -1 && edges.indexOf(edgeL) == -1) 9 | return outVertices[i]; 10 | } 11 | return 'yes'; 12 | } 13 | -------------------------------------------------------------------------------- /Medium - 18 - Dash Insert II.js: -------------------------------------------------------------------------------- 1 | function DashInsertII(num) { 2 | var arr = num.toString().split(''); 3 | var result = ''; 4 | for (var i = 0; i < arr.length - 1; i++) { 5 | var i1 = parseInt(arr[i]); 6 | var i2 = parseInt(arr[i + 1]); 7 | if (i1 != 0 && i2 != 0) { 8 | if (i1 % 2 == 0 && i2 % 2 == 0) 9 | result += i1 + '*'; 10 | else if (i1 % 2 != 0 && i2 % 2 != 0) 11 | result += i1 + '-'; 12 | else 13 | result += i1; 14 | } 15 | else 16 | result += i1; 17 | } 18 | return result + arr[arr.length - 1]; 19 | } 20 | -------------------------------------------------------------------------------- /C# - Find Distinct Numbers In An Array: -------------------------------------------------------------------------------- 1 | static int[] FindDistinctNumbersInArray(int[] a) 2 | { 3 | List distinctNumbers = new List(); 4 | for (int i = 0; i < a.Length; i++) 5 | { 6 | int c = 1; 7 | for (int j = 0; j < a.Length; j++) 8 | { 9 | if (i != j && a[i] == a[j]) 10 | { 11 | c++; 12 | break; 13 | } 14 | } 15 | 16 | if (c == 1) 17 | { 18 | distinctNumbers.Add(a[i]); 19 | } 20 | } 21 | 22 | return distinctNumbers.ToArray(); 23 | } 24 | -------------------------------------------------------------------------------- /Medium - 12 - Simple Mode.js: -------------------------------------------------------------------------------- 1 | function SimpleMode(arr) { 2 | arr.sort(function (a, b) { return a - b; }); 3 | var runChar = arr[0], runCount = 1; 4 | var longRunChar = arr[0], longRunCount = 1; 5 | for (var i = 1; i < arr.length; i++) { 6 | var v = arr[i]; 7 | if (runChar == v) 8 | runCount++; 9 | else { 10 | if (runCount > longRunCount) { 11 | longRunCount = runCount; 12 | longRunChar = runChar; 13 | } 14 | runChar = v; 15 | runCount = 1; 16 | } 17 | } 18 | 19 | if (longRunCount > 1) 20 | return longRunChar; 21 | else 22 | return -1; 23 | } 24 | -------------------------------------------------------------------------------- /C# - Buldings Facing Sunset: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array representing heights of buildings. count number of buildings facing the sunset from left to right. 3 | */ 4 | public static int BuldingsFacingSunset2(int[] a) 5 | { 6 | // first building always sees sunlight 7 | int count = 1; 8 | int curr_max = a[0]; 9 | for (int i = 1; i < a.Length; i++) 10 | { 11 | // If curr_element is maximum, 12 | // update maximum and increment count 13 | if (a[i] > curr_max) 14 | { 15 | count++; 16 | curr_max = a[i]; 17 | } 18 | } 19 | 20 | return count; 21 | } 22 | -------------------------------------------------------------------------------- /Easy - 17 - Array Addition.js: -------------------------------------------------------------------------------- 1 | function ArrayAdditionI(arr) { 2 | var largest = arr.sort(function (a, b) { 3 | return a - b; 4 | }).pop(); 5 | 6 | //to iterate through all possible subsets of the array 7 | var ps = [[]]; 8 | for (var i = 0; i < arr.length; i++) { 9 | for (var j = 0, len = ps.length; j < len; j++) { 10 | var subset = ps[j].concat(arr[i]); 11 | if (subset.length > 1 && subset.reduce(function (pv, v) { return pv + v; }) === largest) { 12 | return true; 13 | } 14 | else { 15 | ps.push(subset); 16 | } 17 | } 18 | } 19 | 20 | return false; 21 | } 22 | -------------------------------------------------------------------------------- /Medium - 07 - Arith Geo II.js: -------------------------------------------------------------------------------- 1 | function ArithGeoII(arr) { 2 | var diff = arr[1] - arr[0]; 3 | var arithmetic = true; 4 | for (var i = 0; i < arr.length - 1; i++) { 5 | if (arr[i + 1] - arr[i] != diff) 6 | arithmetic = false; 7 | } 8 | 9 | var geometric = true; 10 | if (!arithmetic) { 11 | diff = arr[1] / arr[0]; 12 | for (var i = 0; i < arr.length - 1; i++) { 13 | if (arr[i + 1] / arr[i] != diff) 14 | geometric = false; 15 | } 16 | } 17 | 18 | if (arithmetic) 19 | return 'Arithmetic'; 20 | else if (geometric) 21 | return 'Geometric'; 22 | else 23 | return -1; 24 | } 25 | -------------------------------------------------------------------------------- /Medium - 19 - Swap II.js: -------------------------------------------------------------------------------- 1 | function SwapII(inputStr) { 2 | var parts = inputStr.split(' '); 3 | var result = []; 4 | 5 | for (var i = 0; i < parts.length; i++) { 6 | var part = parts[i]; 7 | var str = ''; 8 | for (var j = 0; j < part.length; j++) { 9 | var c = part[j]; 10 | if (c >= 'a' && c <= 'z') 11 | str += c.toUpperCase(); 12 | else if (c >= 'A' && c <= 'Z') 13 | str += c.toLowerCase(); 14 | else 15 | str += c; 16 | } 17 | var replacedStr=str.replace(/(\d)(\D+)(\d)/i, '$3$2$1'); 18 | result.push(replacedStr); 19 | } 20 | return result.join(' '); 21 | } 22 | -------------------------------------------------------------------------------- /Easy - 16 - Arith Geo.js: -------------------------------------------------------------------------------- 1 | function ArithGeo(arr) { 2 | var diff = arr[1] - arr[0]; 3 | var arithmetic = true; 4 | for (var i = 0; i < arr.length - 1; i++) { 5 | if (arr[i + 1] - arr[i] != diff) { 6 | arithmetic = false; 7 | } 8 | } 9 | 10 | var geometric = true; 11 | if (!arithmetic) { 12 | var diff = arr[1] / arr[0]; 13 | for (var i = 0; i < arr.length - 1; i++) { 14 | if (arr[i + 1] / arr[i] != diff) { 15 | geometric = false; 16 | } 17 | } 18 | } 19 | 20 | if (arithmetic) 21 | return 'Arithmetic'; 22 | else if (geometric) 23 | return 'Geometric'; 24 | else 25 | return -1; 26 | } 27 | -------------------------------------------------------------------------------- /C# - Print Numbers Pyramid: -------------------------------------------------------------------------------- 1 | // 1 2 | // 121 3 | // 12321 4 | //1234321 5 | static void PrintNumbersPyramid() 6 | { 7 | for (int i = 1; i <= 4; i++) 8 | { 9 | for (int space = 1; space <= (4 - i); space++) 10 | { 11 | Console.Write(" "); 12 | } 13 | for (int j = 1; j < i; j++) 14 | { 15 | Console.Write(string.Format("{0} ", j)); 16 | } 17 | for (int j = i; j >= 1; j--) 18 | { 19 | Console.Write(string.Format("{0} ", j)); 20 | } 21 | Console.WriteLine(); 22 | } 23 | Console.WriteLine("------------------------------------------------------"); 24 | } 25 | -------------------------------------------------------------------------------- /Medium - 14 - Formatted Division.js: -------------------------------------------------------------------------------- 1 | function FormattedDivision(num1,num2) { 2 | var res = num1 / num2; 3 | res = res.toFixed(4); 4 | var arr = res.toString().split('.'); 5 | var str = arr[0], output = ''; 6 | if (str.length < 4) { 7 | output = str; 8 | } 9 | else { 10 | var commaPos = 4; 11 | for (var i = str.length - 1, pos = 1; i >= 0; i--, pos++) { 12 | if (pos == commaPos) { 13 | output = str[i] + ',' + output; 14 | commaPos += 3; 15 | } 16 | else { 17 | output = str[i] + output; 18 | } 19 | } 20 | } 21 | var outputWIthDecimals = output + '.' + arr[1]; 22 | return outputWIthDecimals; 23 | } 24 | -------------------------------------------------------------------------------- /Medium - 08 - Array Addition.js: -------------------------------------------------------------------------------- 1 | function ArrayAddition(arr) { 2 | var largest = arr.sort(function (a, b) { 3 | return a - b; 4 | }).pop(); 5 | 6 | //to iterate through all possible subsets of the array 7 | var ps = [[]]; 8 | for (var i = 0; i < arr.length; i++) { 9 | for (var j = 0, len = ps.length; j < len; j++) { 10 | var subset = ps[j].concat(arr[i]); 11 | if (subset.length > 1 && subset.reduce(function (pv, v) { return pv + v; }) === largest) { 12 | return true; 13 | } 14 | else { 15 | ps.push(subset); 16 | } 17 | } 18 | } 19 | 20 | return false; 21 | } 22 | -------------------------------------------------------------------------------- /C# - Majority Eelement In An Array: -------------------------------------------------------------------------------- 1 | /*Given an array A of N elements. Find the majority element in the array. 2 | A majority element in an array A of size N is an element that appears more than N/2 times.*/ 3 | public static int MajorityEelementInAnArray(int[] a) 4 | { 5 | int len = a.Length; 6 | for (int i = 0; i < len; i++) 7 | { 8 | int e = a[i], c = 1; 9 | for (int j = 0; j < len; j++) 10 | { 11 | if (i != j && e == a[j]) 12 | { 13 | c++; 14 | } 15 | 16 | if (c > len / 2) 17 | { 18 | return e; 19 | } 20 | } 21 | } 22 | 23 | return -1; 24 | } 25 | -------------------------------------------------------------------------------- /C# - Merge Sorted Arrays In Sorted Order: -------------------------------------------------------------------------------- 1 | static void MergeSortedArraysInSortedOrder() 2 | { 3 | int[] array1 = { 1, 5, 9, 15 }; 4 | int[] array2 = { 2, 3, 7, 11, 14 }; 5 | var mergedArray = new int[array1.Length + array2.Length]; 6 | int i = 0, j = 0; 7 | while (i + j < mergedArray.Length) 8 | { 9 | //if array2 index goes out of bounds or if array1 value is less than array2 value 10 | //then take value from array1, otherwise take from array 2 11 | if (j == array2.Length || (i < array1.Length && array1[i] < array2[j])) 12 | mergedArray[i + j] = array1[i++]; 13 | else 14 | mergedArray[i + j] = array2[j++]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Easy - 22 - Mean Mode.js: -------------------------------------------------------------------------------- 1 | function MeanMode(arr) { 2 | arr.sort(function (a, b) { return a - b; }); 3 | var runChar = arr[0], runCount = 1; 4 | var longRunChar = arr[0], longRunCount = 1; 5 | for (var i = 1; i < arr.length; i++) { 6 | var v = arr[i]; 7 | if (runChar == v) 8 | runCount++; 9 | else { 10 | if (runCount > longRunCount) { 11 | longRunChar = runChar; 12 | longRunCount = runCount; 13 | } 14 | runChar = v; 15 | runCount = 1; 16 | } 17 | } 18 | 19 | var mode = longRunChar; 20 | var mean = arr.reduce(function (pv, v) { return pv + v; }) / arr.length; 21 | 22 | if (mode == mean) 23 | return 1; 24 | else 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /Hard - 04 - Pattern Chaser: -------------------------------------------------------------------------------- 1 | function PatternChaser(str) { 2 | var patterns = []; 3 | var i = 2; j = Math.floor(str.length / 2); 4 | while (i <= j) { 5 | FindPattern(i++); 6 | } 7 | 8 | function FindPattern(num) { 9 | for (var i = 0; i < str.length - num; i++) { 10 | var pattern = str.slice(i, i + num); 11 | var index = str.lastIndexOf(pattern); 12 | if (index != -1 && index != i) { 13 | patterns.push(pattern); 14 | break; 15 | } 16 | } 17 | } 18 | 19 | var largestPattern = patterns.sort(function (a, b) { return a.length - b.length }).pop(); 20 | if (largestPattern) 21 | return 'yes ' + largestPattern; 22 | else 23 | return 'no null'; 24 | } 25 | -------------------------------------------------------------------------------- /C# - Are Strings Anagrams: -------------------------------------------------------------------------------- 1 | //word formed from another by rearranging its letters: “Angel” is an anagram of “glean” 2 | public static bool AreStringsAnagrams(string a, string b) 3 | { 4 | if (string.IsNullOrWhiteSpace(a) || string.IsNullOrWhiteSpace(b) || a.Length != b.Length) 5 | return false; 6 | 7 | a = a.ToLower(); 8 | b = b.ToLower(); 9 | 10 | if (a.Equals(b)) 11 | return false; 12 | 13 | char[] ac = a.ToCharArray(); 14 | char[] bc = b.ToCharArray(); 15 | Array.Sort(ac); 16 | Array.Sort(bc); 17 | for (int i = 0; i < ac.Length; i++) 18 | { 19 | if (ac[i] != bc[i]) 20 | { 21 | return false; 22 | } 23 | } 24 | return true; 25 | } 26 | -------------------------------------------------------------------------------- /Medium - 27 - Multiple Brackets.js: -------------------------------------------------------------------------------- 1 | function MultipleBrackets(str) { 2 | var openBrackets = [], unmatchedBracketfound = false, bracketsCount = 0; 3 | for (var i = 0; i < str.length; i++) { 4 | var c = str[i]; 5 | if (c == '(' || c == '[') { 6 | openBrackets.push(c); 7 | bracketsCount++; 8 | } 9 | else if (c == ')' || c == ']') { 10 | var lastOpenBracket = openBrackets.pop(); 11 | if ((c == ')' && lastOpenBracket != '(') || 12 | (c == ']' && lastOpenBracket != '[')) 13 | unmatchedBracketfound = true; 14 | } 15 | } 16 | 17 | if (unmatchedBracketfound || openBrackets.length > 0) 18 | return 0; 19 | else 20 | return 1 + ' ' + bracketsCount; 21 | } 22 | -------------------------------------------------------------------------------- /C# - Find Nth Minimum Value: -------------------------------------------------------------------------------- 1 | public int FindNthMinimumValue(int[] a, int n) 2 | { 3 | if (n > a.Length) 4 | { 5 | return -1; 6 | } 7 | 8 | List alreadyFoundMinValueIndices = new List(); 9 | for (int i = 1; i <= n; i++) 10 | { 11 | int min = int.MaxValue; int minIndex = -1; 12 | for (int j = 0; j < a.Length; j++) 13 | { 14 | if (!alreadyFoundMinValueIndices.Contains(j) && a[j] < min) 15 | { 16 | min = a[j]; 17 | minIndex = j; 18 | } 19 | } 20 | alreadyFoundMinValueIndices.Add(minIndex); 21 | 22 | if (i == n) 23 | { 24 | return min; 25 | } 26 | } 27 | 28 | return -1; 29 | } 30 | -------------------------------------------------------------------------------- /Easy - 18 - Letter Count I.js: -------------------------------------------------------------------------------- 1 | function LetterCountI(str) { 2 | var arr = str.match(/\w+/g); 3 | var duplicateCount = 0, largestDuplicateCount = 0, largestDuplicateIndex = 0; 4 | for (var i = 0; i < arr.length; i++) { 5 | var distinctArray = [] 6 | for (var j = 0; j < arr[i].length; j++) { 7 | var char = arr[i][j]; 8 | if (distinctArray.indexOf(char) == -1) 9 | distinctArray.push(char); 10 | } 11 | duplicateCount = arr[i].length - distinctArray.length; 12 | if (duplicateCount > largestDuplicateCount) { 13 | largestDuplicateCount = duplicateCount; 14 | largestDuplicateIndex = i; 15 | } 16 | } 17 | 18 | if (largestDuplicateCount == 0) 19 | return -1; 20 | else 21 | return arr[largestDuplicateIndex]; 22 | } 23 | -------------------------------------------------------------------------------- /Medium - 16 - Permutation Step.js: -------------------------------------------------------------------------------- 1 | function PermutationStep(num) { 2 | var arr = num.toString().split(''); 3 | var usedChars = []; 4 | var greaterNumbers = []; 5 | function permute() { 6 | var i, ch; 7 | for (i = 0; i < arr.length; i++) { 8 | ch = arr.splice(i, 1)[0]; 9 | usedChars.push(ch); 10 | if (arr.length == 0) { 11 | var n = parseInt(usedChars.join('')) 12 | if (n > num) { 13 | greaterNumbers.push(n); 14 | } 15 | } 16 | permute(arr); 17 | arr.splice(i, 0, ch); 18 | usedChars.pop(); 19 | } 20 | } 21 | 22 | permute(); 23 | var result = greaterNumbers.sort(function (a, b) { return b - a; }).pop(); 24 | if (result) 25 | return result; 26 | else 27 | return -1; 28 | } 29 | -------------------------------------------------------------------------------- /Medium - 10 - Letter Count.js: -------------------------------------------------------------------------------- 1 | function LetterCount(str) { 2 | var words = str.match(/\w+/g); 3 | var duplicateCount = 0, largestDuplicateCount = 0, largestDuplicateIndex = 0; 4 | for (var i = 0; i < words.length; i++) { 5 | var distinct = [] 6 | var word=words[i]; 7 | for (var j = 0; j < word.length; j++) { 8 | var char = word[j]; 9 | if (distinct.indexOf(char) == -1) 10 | distinct.push(char); 11 | } 12 | duplicateCount = word.length - distinct.length; 13 | if (duplicateCount > largestDuplicateCount) { 14 | largestDuplicateCount = duplicateCount; 15 | largestDuplicateIndex = i; 16 | } 17 | } 18 | 19 | if (largestDuplicateCount == 0) 20 | return -1; 21 | else 22 | return words[largestDuplicateIndex]; 23 | } 24 | -------------------------------------------------------------------------------- /Medium - 15 - Counting Minutes.js: -------------------------------------------------------------------------------- 1 | function CountingMinutes(str) { 2 | 3 | function ParseTime(time) { 4 | var timeParts = time.split(':'); 5 | var hours = parseInt(timeParts[0]); 6 | var minutes = parseInt(timeParts[1].substr(0, 2)); 7 | var totalMinutes = hours * 60 + minutes; 8 | var AMPM = timeParts[1].substr(2, 2).toUpperCase(); 9 | return { AMPM: AMPM, minutes: totalMinutes }; 10 | } 11 | 12 | var times = str.split('-') 13 | var time1 = ParseTime(times[0]); 14 | var time2 = ParseTime(times[1]); 15 | 16 | if (time1.AMPM != time2.AMPM) { 17 | time2.minutes += 12 * 60; 18 | } 19 | else if (time1.AMPM == time2.AMPM && time1.minutes > time2.minutes) { 20 | time2.minutes += 24 * 60; 21 | } 22 | 23 | return time2.minutes - time1.minutes; 24 | } 25 | -------------------------------------------------------------------------------- /Easy - 21 - Counting Minutes I.js: -------------------------------------------------------------------------------- 1 | function CountingMinutesI(str) { 2 | 3 | function ParseTime(time) { 4 | var timeParts = time.split(':'); 5 | var hours = parseInt(timeParts[0]); 6 | var minutes = parseInt(timeParts[1].substr(0, 2)); 7 | var totalMinutes = hours * 60 + minutes; 8 | var AMPM = timeParts[1].substr(2, 2).toUpperCase(); 9 | return { AMPM: AMPM, minutes: totalMinutes }; 10 | } 11 | 12 | var times = str.split('-') 13 | var time1 = ParseTime(times[0]); 14 | var time2 = ParseTime(times[1]); 15 | 16 | if (time1.AMPM != time2.AMPM) { 17 | time2.minutes += 12 * 60; 18 | } 19 | else if (time1.AMPM == time2.AMPM && time1.minutes > time2.minutes) { 20 | time2.minutes += 24 * 60; 21 | } 22 | 23 | return time2.minutes - time1.minutes; 24 | } 25 | -------------------------------------------------------------------------------- /C# - Find Next Greater Element Using Stack: -------------------------------------------------------------------------------- 1 | //Find next greater element for each element in an array 2 | public void FindNextGreaterElementUsingStack() 3 | { 4 | int[] a = { 1, 5, 2, 7, 12, 8, 10, 6 }; 5 | Stack stack = new Stack(); 6 | 7 | for (int i = 0; i < a.Length; i++) 8 | { 9 | int n = a[i]; 10 | while (stack.Count > 0 && n > stack.Peek()) 11 | { 12 | Console.WriteLine("{0} Next greater element is:{1}", stack.Pop(), n); 13 | } 14 | stack.Push(n); 15 | } 16 | 17 | /*if any elements left in stack, that means there are 18 | * no greater elements for them in the array */ 19 | while (stack.Count > 0) 20 | { 21 | Console.WriteLine("{0} Next greater element is:{1}", stack.Pop(), -1); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Hard - 05 - Gas Station: -------------------------------------------------------------------------------- 1 | function GasStation(strArr) { 2 | var gasStationCount = parseInt(strArr.splice(0, 1)[0]); 3 | 4 | for (var i = 0; i < strArr.length; i++) { 5 | var startIndex = i, count = 0; inputGas = 0; //gallons 6 | 7 | while (count < strArr.length) { 8 | var station1 = strArr[startIndex].split(':'); 9 | inputGas += parseInt(station1[0]); 10 | var gasNeeded = parseInt(station1[1]); 11 | 12 | if (inputGas < gasNeeded) 13 | break; 14 | else { 15 | inputGas -= parseInt(station1[1]); 16 | 17 | startIndex = startIndex + 1 == strArr.length ? 0 : startIndex + 1; 18 | count++; 19 | } 20 | } 21 | 22 | if (count == strArr.length) 23 | return i + 1; 24 | } 25 | 26 | return 'impossible'; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /C# - Find Continuous Sub Array: -------------------------------------------------------------------------------- 1 | /* 2 | Given an unsorted array A of size N of non-negative integers, 3 | find a continuous sub-array which adds to a given number. 4 | */ 5 | static int[] FindContinuousSubArray(int[] a, int x) 6 | { 7 | List ContinuousSubAarray = new List(); 8 | for (int i = 0; i < a.Length; i++) 9 | { 10 | int sum = a[i]; 11 | for (int j = i + 1; j < a.Length; j++) 12 | { 13 | sum = sum + a[j]; 14 | if (sum == x) 15 | { 16 | for (int k = i; k <= j; k++) 17 | { 18 | ContinuousSubAarray.Add(a[k]); 19 | } 20 | 21 | return ContinuousSubAarray.ToArray(); 22 | } 23 | } 24 | } 25 | 26 | return ContinuousSubAarray.ToArray(); 27 | } 28 | -------------------------------------------------------------------------------- /Medium - 11 - Caesar Cipher.js: -------------------------------------------------------------------------------- 1 | function CaesarCipher(str, num) { 2 | var res = ''; 3 | for (var i = 0; i < str.length; i++) { 4 | var c = str[i]; 5 | if (c >= 'a' && c <= 'z') { 6 | res += ReturnEncodedChar(c, 97, 122, num); 7 | } 8 | else if (c >= 'A' && c <= 'Z') { 9 | res += ReturnEncodedChar(c, 65, 90, num); 10 | } 11 | else 12 | res += c; 13 | } 14 | return res; 15 | } 16 | 17 | function ReturnEncodedChar(char, aCode, zCode, num) { 18 | var code = char.charCodeAt(0); 19 | var newCode; 20 | if (code == zCode) 21 | newCode = aCode - 1 + num; 22 | else { 23 | var newCode = code + num; 24 | if (newCode > zCode) { 25 | newCode = aCode - 1 + (newCode - zCode); 26 | } 27 | } 28 | return String.fromCharCode(newCode); 29 | } 30 | -------------------------------------------------------------------------------- /Medium - 23 - String Reduction.js: -------------------------------------------------------------------------------- 1 | function StringReduction(str) { 2 | var arr = str.split(''); 3 | 4 | function Reduce() { 5 | var reduceCount = 0,c3; 6 | for (var i = 0; i < arr.length - 1; i++) { 7 | var c1 = arr[i]; 8 | var c2 = arr[i + 1]; 9 | if (c1 == 'a' && (c2 == 'b' || c2 == 'c')) { 10 | c3 = (c2 == 'b') ? 'c' : 'b'; 11 | } 12 | else if (c1 == 'b' && (c2 == 'c' || c2 == 'a')) { 13 | c3 = (c2 == 'c') ? 'a' : 'c'; 14 | } 15 | else if (c1 == 'c' && (c2 == 'a' || c2 == 'b')) { 16 | c3 = (c2 == 'a') ? 'b' : 'a'; 17 | } 18 | 19 | if (c3) { 20 | reduceCount++; 21 | arr.splice(i, 2, c3); 22 | } 23 | } 24 | 25 | if (reduceCount == 0) 26 | return; 27 | else 28 | Reduce(); 29 | } 30 | 31 | Reduce(); 32 | return arr.length; 33 | } 34 | -------------------------------------------------------------------------------- /Medium - 25 - Coin Determiner: -------------------------------------------------------------------------------- 1 | function CoinDeterminer(num) { 2 | var arr = [1, 5, 7, 9, 11]; 3 | var ps = [[]]; 4 | for (var i = 0; i < arr.length; i++) { 5 | for (var j = 0, len = ps.length; j < len; j++) { 6 | var subset = ps[j].concat(arr[i]); 7 | if (subset.reduce(function (pv, v) { return pv + v; }) == num) 8 | return subset.length; 9 | else 10 | ps.push(subset) 11 | } 12 | } 13 | 14 | var divTimes = []; leastDivTimes = 0; 15 | for (var i = 0; i < arr.length; i++) { 16 | var n = arr[i]; 17 | var rem = num % n; 18 | var dividedTimes = parseInt(num / n); 19 | if (rem == 0) { 20 | divTimes.push(dividedTimes); 21 | } 22 | else if (arr.indexOf(rem) != -1) { 23 | divTimes.push(dividedTimes + 1); 24 | } 25 | } 26 | 27 | return divTimes.sort(function (a, b) { return b - a; }).pop(); 28 | } 29 | -------------------------------------------------------------------------------- /Hard - 09 - Knight Jumps: -------------------------------------------------------------------------------- 1 | function KnightJumps(str) { 2 | var s = str.replace(/[\(\)]/g, '').split(' '); 3 | var x = Number(s[0]); 4 | var y = Number(s[1]); 5 | 6 | var expressions = ["x + 2 < 9", "x - 2 > 0", "y + 2 < 9", "y - 2 > 0"]; 7 | var results = []; 8 | for (var i = 0; i < expressions.length; i++) { 9 | results.push(eval(expressions[i])); 10 | } 11 | 12 | var trueCount = results.filter(function (v) { return v == true; }).length; 13 | if (trueCount == 4) 14 | return 8; 15 | else { 16 | results = []; 17 | for (var i = 0; i < expressions.length; i++) { 18 | results.push(eval(expressions[i].replace('2', '1'))); 19 | } 20 | var modifiedTrueCount = results.filter(function (v) { return v == true; }).length; 21 | if (trueCount == 3) 22 | return modifiedTrueCount == 4 ? 6 : 4; 23 | else 24 | return modifiedTrueCount; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /C# - Count Negative Integers In A Sorted Matrix: -------------------------------------------------------------------------------- 1 | public void CountNegativeIntegersInASortedMatrix() 2 | { 3 | int[,] a = { { -3, -2, -1, -1 }, { -2, 2, 3, 4 }, { -4, -5, -7, -8 } }; 4 | 5 | int negativeNumberCount = 0; 6 | int rowLength = a.GetLength(0), colLength = a.GetLength(1); 7 | int row = 0, col = colLength - 1; 8 | while (row < rowLength && col >= 0) 9 | { 10 | if (a[row, col] < 0) 11 | { 12 | /*since array is sorted and we are traversing in reverse order, 13 | * once negative valus is found in a column, all the numbers till that index 14 | * must be negative. so, just increment count and move to the next row */ 15 | negativeNumberCount = negativeNumberCount + (col + 1); 16 | row++; 17 | col = colLength - 1; 18 | } 19 | else 20 | { 21 | col--; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Easy - 30 - Off Line Minimum.js: -------------------------------------------------------------------------------- 1 | function OffLineMinimum(strArr) { 2 | var output = []; 3 | recursion(); 4 | return output.join(','); 5 | 6 | function recursion() { 7 | for (var i = 0; i < strArr.length; i++) { 8 | var v = strArr[i]; 9 | if (v == 'E') { 10 | //to create subset with all integers before 'E' 11 | var arr = strArr.slice(0, i); 12 | //to sort in descending order and return minimum value 13 | var item = arr.sort(function (a, b) { return parseInt(b) - parseInt(a); }).pop(); 14 | output.push(item); 15 | //to remove 'E' element 16 | strArr.splice(i, 1); 17 | //to remove minimum integer found in the subset from inpur array 18 | strArr.splice(strArr.indexOf(item), 1); 19 | break; 20 | } 21 | } //for end 22 | if (strArr.indexOf('E') == -1) 23 | return; 24 | else 25 | recursion(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Medium - 17 - Prime Checker.js: -------------------------------------------------------------------------------- 1 | function IsPrimeNumber(num) { 2 | if (num <= 1) 3 | return false; 4 | for (var i = 2; i < num; i++) { 5 | if (num % i == 0) 6 | return false; 7 | } 8 | return true; 9 | } 10 | 11 | function PrimeChecker(num) { 12 | var arr = num.toString().split(''); 13 | var usedChars = []; 14 | var prime = false; 15 | function permute() { 16 | 17 | if (prime) 18 | return; 19 | 20 | var ch; 21 | for (var i = 0; i < arr.length; i++) { 22 | ch = arr.splice(i, 1)[0]; 23 | usedChars.push(ch); 24 | if (arr.length == 0) { 25 | var n = parseInt(usedChars.join('')) 26 | prime = IsPrimeNumber(n); 27 | if (prime) 28 | return; 29 | } 30 | permute(arr); 31 | arr.splice(i, 0, ch); 32 | usedChars.pop(); 33 | } 34 | } 35 | 36 | permute(); 37 | 38 | if (prime) 39 | return 1; 40 | else 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /C# - Product Of Numbers: -------------------------------------------------------------------------------- 1 | // find product of 2 integers without using * or / operators 2 | public int ProductOfNumbers(int a, int b) 3 | { 4 | if (a == 0 || b == 0) 5 | { 6 | return 0; 7 | } 8 | 9 | int smaller = a < b ? a : b; 10 | int bigger = a < b ? b : a; 11 | 12 | return ProductOfNumbersRecursion(smaller, bigger); 13 | } 14 | 15 | public int ProductOfNumbersRecursion(int smaller, int bigger) 16 | { 17 | if (smaller == 1) 18 | { 19 | return bigger; 20 | } 21 | 22 | int s = smaller >> 1; //right shift once to devide by 2 23 | int halfProd = ProductOfNumbersRecursion(s, bigger); 24 | 25 | if (smaller % 2 == 0) 26 | { 27 | return halfProd + halfProd; 28 | } 29 | else 30 | { 31 | // if a=11 and b=20 32 | // find product for a=10, b=20 then add bigger number 33 | // 10*20=200, 11*20=10*20+20 34 | return halfProd + halfProd + bigger; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /C# - LongRunChar: -------------------------------------------------------------------------------- 1 | //to find long run char in a string. ex: "abbbccccccd" output:c 2 | public static char LongRunChar(string s) 3 | { 4 | char currentChar = s[0], longRunChar = s[0]; 5 | int currentCharCount = 1, longRunCharCount = 1; 6 | for (int i = 1; i < s.Length; i++) 7 | { 8 | var nextChar = s[i]; 9 | if (currentChar == nextChar) 10 | { 11 | currentCharCount++; 12 | } 13 | else 14 | { 15 | if (currentCharCount > longRunCharCount) 16 | { 17 | longRunChar = currentChar; 18 | longRunCharCount = currentCharCount; 19 | } 20 | 21 | currentChar = nextChar; 22 | currentCharCount = 1; 23 | } 24 | } 25 | 26 | if (currentCharCount > longRunCharCount) 27 | { 28 | longRunChar = currentChar; 29 | longRunCharCount = currentCharCount; 30 | } 31 | 32 | return longRunChar; 33 | } 34 | -------------------------------------------------------------------------------- /C# - Find Subsets: -------------------------------------------------------------------------------- 1 | public List GetSubsets(string s) 2 | { 3 | List subsets = new List() { "" }; 4 | for (int i = 0; i < s.Length; i++) 5 | { 6 | int count = subsets.Count; 7 | for (int j = 0; j < count; j++) 8 | { 9 | subsets.Add(subsets[j] + s[i]); 10 | } 11 | } 12 | 13 | return subsets; 14 | } 15 | 16 | public IEnumerable> GetSubsets(T[] array) 17 | { 18 | //var possibleSubsetsCount = (int)Math.Pow(2, array.Length); 19 | List> subsets = new List>() { new List() }; 20 | 21 | for (int i = 0; i < array.Length; i++) 22 | { 23 | int count = subsets.Count; 24 | for (int j = 0; j < count; j++) 25 | { 26 | var subset = new List(subsets[j]); 27 | subset.Add(array[i]); 28 | subsets.Add(subset); 29 | } 30 | } 31 | 32 | //return powerset.Where(subset => subset.Count > 1); 33 | return subsets; 34 | } 35 | -------------------------------------------------------------------------------- /C# - Check If An Array Is Polindrome: -------------------------------------------------------------------------------- 1 | public bool CheckIfAnArrayIsPolindrome() 2 | { 3 | int[] a = { 1, 23, 45, 43, 2, 1 }; 4 | 5 | /* idea: convert all array values (right-left) into a single decimal number 6 | * if number and its reverse number are equal, then array is polindrome */ 7 | int powerIndex = 0; 8 | int number = 0; 9 | for (int i = a.Length - 1; i >= 0; i--) 10 | { 11 | int n = a[i]; 12 | while (n > 0) 13 | { 14 | int rem = n % 10; 15 | number = number + rem * (int)Math.Pow(10, powerIndex++); 16 | n = n / 10; 17 | } 18 | } 19 | 20 | int reverseNumber = ReverseNumber(number); 21 | if (number == ReverseNumber(number)) 22 | { 23 | return true; 24 | } 25 | 26 | return false; 27 | } 28 | 29 | public int ReverseNumber(int n) 30 | { 31 | int result = 0; 32 | while (n > 0) 33 | { 34 | int rem = n % 10; 35 | result = result * 10 + rem; 36 | n = n / 10; 37 | } 38 | 39 | return result; 40 | } 41 | -------------------------------------------------------------------------------- /C# - Addition Between Numbers In Two Arrays: -------------------------------------------------------------------------------- 1 | public int AdditionBetweenNumbersInTwoArrays() 2 | { 3 | int[] a = { 1, 10, 8, 9, 7 }; 4 | int[] b = { 1, 6, 4 }; 5 | 6 | /* 1 10 8 9 7 7 | * 1 6 4 8 | * ----------- 9 | 2 1 0 6 1 */ 10 | 11 | int result = 0, power = 0; 12 | int addition = 0, division = 0, remainder = 0; 13 | int aIndex = a.Length - 1, bIndex = b.Length - 1; 14 | while (aIndex >= 0 || bIndex >= 0) 15 | { 16 | if (aIndex >= 0 && bIndex >= 0) 17 | { 18 | addition = a[aIndex--] + b[bIndex--] + division; 19 | } 20 | else if (aIndex >= 0) 21 | { 22 | addition = a[aIndex--] + division; 23 | } 24 | else 25 | { 26 | addition = b[bIndex--] + division; 27 | } 28 | 29 | division = addition / 10; //this value will be carried over for next addition 30 | remainder = addition % 10; 31 | result = result + remainder * (int)Math.Pow(10, power++); 32 | } 33 | 34 | return result; 35 | } 36 | -------------------------------------------------------------------------------- /C# - Find All Jumping Numbers: -------------------------------------------------------------------------------- 1 | /* 2 | Given a positive number X. Find all Jumping Numbers smaller than or equal to X. 3 | Jumping Number: A number is called Jumping Number if all adjacent digits in it differ by only 1. 4 | All single digit numbers are considered as Jumping Numbers. 5 | For example 7, 8987 and 4343456 are Jumping numbers but 796 and 89098 are not. 6 | */ 7 | static int[] FindAllJumpingNumbers(int x) 8 | { 9 | List jumpingNumbers = new List(); 10 | for (int i = 0; i <= x; i++) 11 | { 12 | bool isJumbingNumber = true; 13 | var digits = i.ToString().ToCharArray().Select(c => int.Parse(c.ToString())).ToArray(); 14 | for (int j = 0; j < digits.Length - 1; j++) 15 | { 16 | if (Math.Abs(digits[j] - digits[j + 1]) != 1) 17 | { 18 | isJumbingNumber = false; 19 | break; 20 | } 21 | } 22 | 23 | if (isJumbingNumber) 24 | { 25 | jumpingNumbers.Add(i); 26 | } 27 | } 28 | 29 | return jumpingNumbers.ToArray(); 30 | } 31 | -------------------------------------------------------------------------------- /C# - Common Functions: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Web; 6 | 7 | namespace AddAppAPI.Helpers 8 | { 9 | public class CommonFunctions 10 | { 11 | public static bool IsNullableType(Type input) 12 | { 13 | if (!input.IsValueType) return true; // Reference Type 14 | if (Nullable.GetUnderlyingType(input) != null) return true; // Nullable 15 | return false; // Value Type 16 | } 17 | 18 | public static Type GetType(Type type) 19 | { 20 | if (type.IsGenericType && IsNullableType(type)) 21 | { // If Nullable<>, this is how we get the underlying Type... 22 | return type.GenericTypeArguments.FirstOrDefault(); 23 | } 24 | else 25 | { 26 | return type; 27 | } 28 | } 29 | 30 | public static bool IsCollectionEmpty(IEnumerable iInput) 31 | { 32 | return (iInput == null || iInput.Count() < 1) ? true : false; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /C# - Nth Prime Number: -------------------------------------------------------------------------------- 1 | public long NthPrimeNumber(int n) 2 | { 3 | int primeCount = 0; 4 | int number = 2; //first prime number 5 | while (true) 6 | { 7 | bool isPrimeNumber = true; 8 | // to check if a number is prime, we dont need to check until that number 9 | // checking up to square root is enough. 10 | // example to check 100 is prime or not. 100 can be represented in many ways 11 | // 2x50, 5x20, 10x10 12 | // in all cases, one of the factor is <= square of 100, which is 10 13 | // so we can find a prime number just by checking till its last factor 14 | for (int i = 2; i <= Math.Sqrt(number); i++) 15 | { 16 | if (number % i == 0) 17 | { 18 | isPrimeNumber = false; 19 | break; 20 | } 21 | } 22 | 23 | if (isPrimeNumber) 24 | { 25 | primeCount++; 26 | if (primeCount == n) 27 | { 28 | Console.WriteLine($"{n}th Prime Number is {number}"); 29 | return number; 30 | } 31 | } 32 | 33 | number++; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Medium - 32 - Overlapping Rectangles: -------------------------------------------------------------------------------- 1 | function OverlappingRectangles(strArr) { 2 | var matches = strArr[0].match(/-?\d+,-?\d+/g); 3 | var rectangle1 = matches.splice(0, 4).map(function (e) { return e.split(',').map(Number); }); 4 | rectangle1.sort(function (a, b) { return a[0] - b[0]; }); 5 | var rectangle2 = matches.map(function (e) { return e.split(',').map(Number); }); 6 | rectangle2.sort(function (a, b) { return a[0] - b[0]; }); 7 | 8 | var r1 = parseRectangle(rectangle1); 9 | var r2 = parseRectangle(rectangle2); 10 | var r1Width = r1.right - r1.left; 11 | var r1Height = r1.bottom - r1.top; 12 | var overlapWidth = (r1.right > r2.right) ? r2.right - r1.left : r1.right - r2.left; 13 | var overlapHeight = (r1.bottom > r2.bottom) ? r2.bottom - r1.top : r1.bottom - r2.top; 14 | var overlapArea = overlapWidth * overlapHeight; 15 | 16 | if (overlapArea < 0) 17 | return 0; 18 | else 19 | return Math.floor(r1Width / overlapWidth) * Math.floor(r1Height / overlapHeight); 20 | } 21 | 22 | // X-Axis:left-----------------right 23 | // Y-Axis: 24 | //top 25 | //' 26 | //' 27 | //bottom 28 | function parseRectangle(rectangle) { 29 | var arr = [rectangle[0][1], rectangle[1][1]].sort(); 30 | return { left: rectangle[0][0], right: rectangle[2][0], top: arr[0], bottom: arr[1] }; 31 | } 32 | -------------------------------------------------------------------------------- /C# - Print Matrix In Spiral Form: -------------------------------------------------------------------------------- 1 | public void PrintMatrixInSpiralForm() 2 | { 3 | char[,] a = { { 'a','b','c','d','e'}, 4 | { 'f','g','h','i','j'}, 5 | { 'k','l','m','n','o'}, 6 | { 'p','q','r','s','t'} 7 | }; 8 | //output: ->a->b->c->d->e->j->o->t->s->r->q->p->k->f->g->h->i->n->m->l 9 | 10 | int row = 0, column = 0; 11 | int lastrow = a.GetLength(0) - 1, lastColumn = a.GetLength(1) - 1; 12 | string str = string.Empty; 13 | while (row <= lastrow && column <= lastColumn) 14 | { 15 | for (int i = column; i <= lastColumn; i++) 16 | { 17 | str = str + "->" + a[row, i]; 18 | } 19 | row++; 20 | 21 | for (int i = row; i <= lastrow; i++) 22 | { 23 | str = str + "->" + a[i, lastColumn]; 24 | } 25 | lastColumn--; 26 | 27 | if (row <= lastrow) 28 | { 29 | for (int i = lastColumn; i >= column; i--) 30 | { 31 | str = str + "->" + a[lastrow, i]; 32 | } 33 | lastrow--; 34 | } 35 | 36 | if (column <= lastColumn) 37 | { 38 | for (int i = lastrow; i >= row; i--) 39 | { 40 | str = str + "->" + a[i, column]; 41 | } 42 | column++; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Hard - 11 - Queen Check: -------------------------------------------------------------------------------- 1 | function QueenCheck(strArr) { 2 | var arr = strArr[0].replace(/[\(\)]/g, '').split(','); 3 | var queen = { x: Number(arr[0]), y: Number(arr[1]) }; 4 | arr = strArr[1].replace(/[\(\)]/g, '').split(','); 5 | var king = { x: Number(arr[0]), y: Number(arr[1]) }; 6 | 7 | function isKingInCheck(king) { 8 | if (king.x == queen.x && king.y == queen.y) //queen captured, not in check 9 | return false; 10 | if (king.x == queen.x || king.y == queen.y || 11 | (Math.abs(king.x - queen.x) == Math.abs(king.y - queen.y))) 12 | return true; 13 | return false; 14 | } 15 | 16 | function isMoveOnBoard(a) { 17 | if (a.x > 0 && a.x < 9 && a.y > 0 && a.y < 9) 18 | return true; 19 | return false; 20 | } 21 | 22 | function getKingMovesCount() { 23 | var moves = []; 24 | //to iterate through all 8 places around the king 25 | for (var i = -1; i < 2; i++) { 26 | for (var j = -1; j < 2; j++) { 27 | if (i == 0 && j == 0) 28 | continue; //it gives the existing location of x 29 | var move = { x: king.x + i, y: king.y + j }; 30 | if (isMoveOnBoard(move) && !isKingInCheck(move)) 31 | moves.push(move); 32 | } 33 | } 34 | return moves.length; 35 | } 36 | 37 | if (isKingInCheck(king)) 38 | return getKingMovesCount(); 39 | else 40 | return -1; 41 | } 42 | -------------------------------------------------------------------------------- /Hard - 10 - Symmetric Matrix: -------------------------------------------------------------------------------- 1 | function SymmetricMatrix(strArr) { 2 | var arr = [], startIndex = 0, prevRowLength = 0; 3 | for (var i = 0; i < strArr.length; i++) { 4 | var item = strArr[i]; 5 | if (item == '<>') { 6 | var row = strArr.slice(startIndex, i); 7 | prevRowLength = (prevRowLength == 0) ? row.length : prevRowLength; 8 | //to determine if input matrix is a square matrix 9 | if (row.length == 1 || row.length != prevRowLength) 10 | return 'not possible'; 11 | else { 12 | arr.push(row); 13 | startIndex = i + 1; 14 | } 15 | } 16 | } 17 | //to add last row as there wont be '<>' symbol at end 18 | var row = strArr.slice(startIndex); 19 | if (row.length == 1 || row.length != prevRowLength) 20 | return 'not possible'; 21 | else { 22 | arr.push(row); 23 | } 24 | //to check if no.of rows and columns are euual 25 | if (arr[0].length != arr.length) 26 | return 'not possible'; 27 | 28 | //if a matrix equal to its transpose, then its symmetric 29 | //to compare if nth row values are equal to nth column values 30 | for (var rowIndex = 0; rowIndex < arr.length; rowIndex++) { 31 | var arrRow = arr[rowIndex]; 32 | for (var colIndex = 0; colIndex < arr.length; colIndex++) { 33 | if (arrRow[colIndex] != arr[colIndex][rowIndex]) 34 | return 'not symmetric'; 35 | } 36 | } 37 | 38 | return 'symmetric'; 39 | } 40 | -------------------------------------------------------------------------------- /C# - Number To Words: -------------------------------------------------------------------------------- 1 | static string[] OnesMap = { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; 2 | static string[] TensMap = { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; 3 | public static string NumberToWords(int number) 4 | { 5 | string words = ""; 6 | 7 | int millions = number / 1000000; 8 | if (millions > 0) 9 | { 10 | words += NumberToWords(millions) + " million "; 11 | number %= 1000000; 12 | } 13 | 14 | int thousands = number / 1000; 15 | if (thousands > 0) 16 | { 17 | words += NumberToWords(thousands)+ " thousand "; 18 | number %= 1000; 19 | } 20 | 21 | int hundreds = number / 100; 22 | if (hundreds > 0) 23 | { 24 | words += NumberToWords(hundreds) + " hundred "; 25 | number %= 100; 26 | } 27 | 28 | if (number > 0) 29 | { 30 | if (words != "") 31 | { 32 | words += "and "; 33 | } 34 | 35 | if (number < 20) 36 | { 37 | words += OnesMap[number]; 38 | } 39 | else 40 | { 41 | words += TensMap[number / 10] + " " + OnesMap[number % 10]; 42 | } 43 | } 44 | 45 | return words; 46 | } 47 | 48 | public static void Main(string[] args) 49 | { 50 | var NumberInWords = NumberToWords(7654321).TrimEnd(); 51 | } 52 | -------------------------------------------------------------------------------- /Hard - 08 - Optimal Assignments: -------------------------------------------------------------------------------- 1 | function GetPermutations(num) { 2 | function permute(input) { 3 | var i, ch; 4 | for (i = 0; i < input.length; i++) { 5 | ch = input.splice(i, 1)[0]; 6 | usedChars.push(ch); 7 | if (input.length == 0) { 8 | permutations.push(usedChars.slice()); 9 | } 10 | permute(input); 11 | input.splice(i, 0, ch); 12 | usedChars.pop(); 13 | } 14 | return permutations; 15 | }; 16 | var permutations = [], usedChars = []; 17 | permute(num); 18 | return permutations; 19 | } 20 | 21 | function OptimalAssignments(strArr) { 22 | var arr = []; 23 | for (var i = 0; i < strArr.length; i++) { 24 | arr.push(strArr[i].replace(/[\(\)]/g, '').split(',')); 25 | } 26 | 27 | var input = []; //machine's default order 28 | for (var i = 0; i < arr.length; i++) { 29 | input.push(i); 30 | } 31 | 32 | var permutations = GetPermutations(input); 33 | var minCost = null, minCostCombination = null; 34 | permutations.forEach(function (element, index, array) { // check cost of each permutation 35 | var cost = 0; 36 | for (var i = 0; i < element.length; i++) { 37 | cost += Number(arr[i][element[i]]); 38 | } 39 | if (minCost == null || cost < minCost) { 40 | minCost = cost; 41 | minCostCombination = element; 42 | } 43 | }); 44 | 45 | var assignment = ""; 46 | for (var i = 0; i < minCostCombination.length; i++) { 47 | assignment += '(' + Number(i + 1) + '-' + Number(minCostCombination[i] + 1) + ')'; 48 | } 49 | return assignment; 50 | } 51 | -------------------------------------------------------------------------------- /C# - Gas Station: -------------------------------------------------------------------------------- 1 | /* 2 | There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. 3 | You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to 4 | its next station (i+1). You begin the journey with an empty tank at one of the gas stations. 5 | Return the starting gas station's index if you can travel around the circuit once, otherwise return -1. 6 | */ 7 | public static int GasStation(int[] gas, int[] cost) 8 | { 9 | for (var i = 0; i < gas.Length; i++) 10 | { 11 | int startingStationIndex = i, stationsCovered = 0, totalGas = 0; 12 | while (stationsCovered < gas.Length) 13 | { 14 | //fill the gas 15 | totalGas += gas[i]; 16 | 17 | //check if gas is enough to reach next station 18 | int gasNeeded = cost[i]; 19 | if (totalGas < gasNeeded) 20 | { 21 | //no enough gas. so circuit can't be completed from this station. 22 | break; 23 | } 24 | else 25 | { 26 | totalGas = totalGas - gasNeeded; 27 | stationsCovered++; 28 | startingStationIndex++; 29 | 30 | if (startingStationIndex == gas.Length) 31 | { 32 | startingStationIndex = 0; 33 | } 34 | } 35 | } 36 | 37 | if (stationsCovered == gas.Length) 38 | { 39 | return i + 1; //station index is i and i+1 is station number 40 | } 41 | } 42 | 43 | return -1; 44 | } 45 | -------------------------------------------------------------------------------- /Hard - 12 - Shortest Path: -------------------------------------------------------------------------------- 1 | //Referred and improved the following solution https://github.com/wezleytsai/coderbyte/edit/master/hard%2003%20-%20shortest%20path.js 2 | function ShortestPath(strArr) { 3 | var nodeCount = Number(strArr.splice(0, 1)); 4 | var nodes = strArr.splice(0, nodeCount); 5 | var connections = strArr.map(function (v) { return v.split('-'); }) 6 | var startNode = nodes[0]; 7 | var endNode = nodes[nodes.length - 1]; 8 | 9 | var bestPath = startNode + '-' + endNode; 10 | if (strArr.indexOf(bestPath) != -1) 11 | return bestPath; 12 | 13 | var paths = []; 14 | findPaths([startNode]); 15 | 16 | function findPaths(pathSoFar) { 17 | // pathSoFar = [a, b, ... n] where a is starting point and n is current node 18 | var currentNode = pathSoFar[pathSoFar.length - 1]; 19 | if (currentNode === endNode) { // if(current == endNode), path complete 20 | paths.push(pathSoFar.slice()); 21 | return; 22 | } 23 | 24 | for (var i = 0; i < connections.length; i++) { 25 | var connection = connections[i]; 26 | if (currentNode === connection[0] || currentNode === connection[1]) { 27 | var nextNode = (currentNode === connection[0]) ? connection[1] : connection[0]; 28 | if (pathSoFar.indexOf(nextNode) === -1) { 29 | pathSoFar.push(nextNode); 30 | findPaths(pathSoFar.slice()); 31 | pathSoFar.pop(); 32 | } 33 | } 34 | } 35 | }; 36 | 37 | var shortestPathNodes = paths.sort(function (a, b) { return b.length - a.length; }).pop(); 38 | if (shortestPathNodes) 39 | return shortestPathNodes.join('-'); 40 | else 41 | return -1; 42 | } 43 | -------------------------------------------------------------------------------- /Medium - 28 - Most Free Time: -------------------------------------------------------------------------------- 1 | function ParseTime(time) { 2 | var timeParts = time.split(':'); 3 | var hours = parseInt(timeParts[0]); 4 | var minutes = parseInt(timeParts[1].substr(0, 2)); 5 | var AMPM = timeParts[1].substr(2, 2).toUpperCase(); 6 | var totalMinutes = hours * 60 + minutes; 7 | if (AMPM == 'PM' && hours < 12) 8 | totalMinutes += 12 * 60; 9 | 10 | return { hours: hours, minutes: minutes, AMPM: AMPM, totalMinutes: totalMinutes }; 11 | } 12 | 13 | function FormatTime(time) { 14 | return (time < 10) ? '0' + time : time; 15 | } 16 | 17 | function MostFreeTime(strArr) { 18 | var startTimes = []; 19 | for (var i = 0; i < strArr.length; i++) { 20 | var period = strArr[i]; 21 | var times = period.split('-') 22 | var time1 = ParseTime(times[0]); 23 | var time2 = ParseTime(times[1]); 24 | time1.endTime = time2 25 | startTimes.push(time1); 26 | } 27 | startTimes.sort(function (a, b) { return a.totalMinutes - b.totalMinutes }); 28 | 29 | //to find difference between times 30 | var diff = 0; mostDiff = 0; 31 | for (var i = 0; i < startTimes.length - 1; i++) { 32 | var endTimeOfEvent = startTimes[i].endTime; 33 | var startTimeOfNextEvent = startTimes[i + 1]; 34 | var diff = startTimeOfNextEvent.totalMinutes - endTimeOfEvent.totalMinutes; 35 | if (diff > mostDiff) 36 | mostDiff = diff; 37 | } 38 | 39 | var output; 40 | if (mostDiff < 60) 41 | output = '00:' + FormatTime(mostDiff); 42 | else { 43 | var hours = parseInt(mostDiff / 60); 44 | var minutes = mostDiff % 60; 45 | output = FormatTime(hours) + ':' + FormatTime(minutes); 46 | } 47 | return output; 48 | } 49 | -------------------------------------------------------------------------------- /Hard - 07 - Noughts Determiner: -------------------------------------------------------------------------------- 1 | function NoughtsDeterminer(strArr) { 2 | var arr = [], startIndex = 0; 3 | for (var i = 0; i < strArr.length; i++) { 4 | var item = strArr[i]; 5 | if (item == '<>') { 6 | arr.push(strArr.slice(startIndex, i)); 7 | startIndex = i + 1; 8 | } 9 | 10 | } 11 | //to add last row as there wont be '<>' symbol at end 12 | arr.push(strArr.slice(startIndex)); 13 | 14 | function MatchCheck(input) { 15 | var match = input.replace(/[\-]/, 'O').match(/O{3}/); 16 | match = (match) ? match : input.replace(/[\-]/, 'X').match(/X{3}/); 17 | return (match) ? true : false; 18 | } 19 | 20 | //diagnol check 21 | var diagnol1 = [arr[0][0], arr[1][1], arr[2][2]]; 22 | var str = diagnol1.join(''); 23 | var index = str.indexOf('-'); 24 | if (index != -1 && MatchCheck(str)) { 25 | return index * (arr.length) + index + index; 26 | } 27 | 28 | var diagnol2 = [arr[0][2], arr[1][1], arr[2][0]]; 29 | str = diagnol2.join(''); 30 | index = str.indexOf('-'); 31 | if (index != -1 && MatchCheck(str)) { 32 | return index * (arr.length) + (2 - index) + index; 33 | } 34 | 35 | //horizontal check 36 | for (var rowIndex = 0; rowIndex < 3; rowIndex++) { 37 | var row = arr[rowIndex]; 38 | var str = row.join(''); 39 | index = str.indexOf('-'); 40 | if (index != -1 && MatchCheck(str)) { 41 | return rowIndex * (row.length) + index + rowIndex; 42 | } 43 | } 44 | 45 | //Vertical check 46 | for (var colIndex = 0; colIndex < 3; colIndex++) { 47 | var col = [arr[0][colIndex], arr[1][colIndex], arr[2][colIndex]]; 48 | var str = col.join(''); 49 | index = str.indexOf('-'); 50 | if (index != -1 && MatchCheck(str)) { 51 | return index * (arr.length) + index + colIndex; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Hard - 13 - Weighted Path: -------------------------------------------------------------------------------- 1 | function WeightedPath(strArr) { 2 | var nodeCount = Number(strArr.splice(0, 1)); 3 | var nodes = strArr.splice(0, nodeCount); 4 | var connections = strArr.map(function (v) { return v.split('|'); }) 5 | var startNode = nodes[0]; 6 | var endNode = nodes[nodes.length - 1]; 7 | 8 | var paths = [], pathWeights = []; 9 | findPaths([startNode], []); 10 | 11 | function findPaths(pathSoFar, weightSoFar) { 12 | // pathSoFar = [a, b, ... n] where a is start node and n is current node 13 | var currentNode = pathSoFar[pathSoFar.length - 1]; 14 | if (currentNode === endNode) { // if(current == endNode), path complete 15 | paths.push(pathSoFar.slice()); 16 | pathWeights.push(weightSoFar.slice()); 17 | return; 18 | } 19 | 20 | for (var i = 0; i < connections.length; i++) { 21 | var connection = connections[i]; 22 | if (currentNode === connection[0] || currentNode === connection[1]) { 23 | var nextNode = (currentNode === connection[0]) ? connection[1] : connection[0]; 24 | if (pathSoFar.indexOf(nextNode) === -1) { 25 | pathSoFar.push(nextNode); 26 | weightSoFar.push(Number(connection[2])); 27 | findPaths(pathSoFar.slice(), weightSoFar.slice()); 28 | pathSoFar.pop(); 29 | weightSoFar.pop(); 30 | } 31 | } 32 | } 33 | }; 34 | 35 | if (paths.length > 0) { 36 | pathWeights = pathWeights.map(function (element) { 37 | return element.reduce(function (pv, v) { return pv + v; }); 38 | }); 39 | 40 | var minWeight = pathWeights[0]; minWeightIndex = 0; 41 | for (var i = 1; i < pathWeights.length; i++) { 42 | var weight = pathWeights[i]; 43 | if (weight < minWeight) { 44 | minWeight = weight 45 | minWeightIndex = i; 46 | } 47 | } 48 | return paths[minWeightIndex].join('-'); 49 | } 50 | else 51 | return -1; 52 | } 53 | -------------------------------------------------------------------------------- /Hard - 06 - Matrix Determinant: -------------------------------------------------------------------------------- 1 | //to find determinant of nxn square matrix 2 | function MatrixDeterminant(strArr) { 3 | var arr = [], startIndex = 0, prevRowLength = 0; 4 | for (var i = 0; i < strArr.length; i++) { 5 | var item = strArr[i]; 6 | if (item == '<>') { 7 | var row = strArr.slice(startIndex, i); 8 | prevRowLength = (prevRowLength == 0) ? row.length : prevRowLength; 9 | //to determine if input matrix is a square matrix 10 | if (row.length == 1 || row.length != prevRowLength) 11 | return -1; 12 | else { 13 | arr.push(row); 14 | startIndex = i + 1; 15 | } 16 | } 17 | } 18 | //to add last row as there wont be '<>' symbol at end 19 | var row = strArr.slice(startIndex); 20 | if (row.length != prevRowLength) 21 | return -1; 22 | else { 23 | arr.push(row); 24 | } 25 | //to check if no.of rows and columns are equal 26 | if (arr[0].length != arr.length) 27 | return -1; 28 | 29 | var res = ''; 30 | FindDeterminant(arr); 31 | var determinant = eval(res); 32 | return determinant; 33 | 34 | //recursive function to find Determinant of a matrix 35 | function FindDeterminant(array) { 36 | if (array.length == 2) { 37 | res += '(' + array[0][0] + ')*(' + array[1][1] + ')-(' + array[0][1] + ')*(' + array[1][0] + ')'; //ad-bc 38 | return; 39 | } 40 | 41 | var len = array[0].length; 42 | for (var i = 0; i < len; i++) { 43 | var ele = array[0][i]; 44 | var subDetArray = []; 45 | for (var rowIndex = 1; rowIndex < array.length; rowIndex++) { 46 | var row = array[rowIndex]; 47 | var temp = []; 48 | for (var col = 0; col < len; col++) { 49 | if (col != i) 50 | temp.push(row[col]); 51 | } 52 | subDetArray.push(temp); 53 | } 54 | var even = ((i + 1) % 2 == 0); 55 | res += (even ? '-(' : '+(') + ele + ')*('; 56 | FindDeterminant(subDetArray); 57 | res += ')'; 58 | } 59 | } 60 | } 61 | 62 | // keep this function call here 63 | // to see how to enter arguments in JavaScript scroll down 64 | MatrixDeterminant(readline()); 65 | -------------------------------------------------------------------------------- /C# - Convert Number To BaseN Value and Viceversa: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace TempConsoleApp 8 | { 9 | class BaseConversion 10 | { 11 | private char[] GetMap(int baseN) 12 | { 13 | char[] map = null; 14 | 15 | if (baseN == 2) 16 | { 17 | map = "01".ToCharArray(); 18 | } 19 | else if (baseN == 10) 20 | { 21 | map = "0123456789".ToCharArray(); 22 | } 23 | else if (baseN == 16) 24 | { 25 | map = "0123456789abcdef".ToCharArray(); 26 | } 27 | else if (baseN == 62) 28 | { 29 | // Map to store 62 possible characters 30 | map = ("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").ToCharArray(); 31 | } 32 | 33 | return map; 34 | } 35 | 36 | public string NumberToBaseNValue(long n, int baseN) 37 | { 38 | var map = GetMap(baseN); 39 | string result = string.Empty; 40 | 41 | // Convert given integer id to a base N value 42 | while (n > 0) 43 | { 44 | result += map[n % baseN]; 45 | n = n / baseN; 46 | } 47 | 48 | // Reverse result to complete base conversion 49 | return string.Join("", result.Reverse()); 50 | } 51 | 52 | public long BaseNValueToNumber(string n, int baseN) 53 | { 54 | var map = GetMap(baseN); 55 | long number = 0; 56 | for (int i = n.Length - 1, j = 0; i >= 0; i--, j++) 57 | { 58 | number += Array.IndexOf(map, n[i]) * (long)Math.Pow(baseN, j); 59 | } 60 | 61 | return number; 62 | } 63 | 64 | } 65 | 66 | class BaseConversionTest 67 | { 68 | static void Main(string[] args) 69 | { 70 | BaseConversion obj = new BaseConversion(); 71 | int number = 12345, baseN = 62; 72 | var numberToBaseN = obj.NumberToBaseNValue(number, baseN); 73 | var baseNValueToNumber = obj.BaseNValueToNumber(numberToBaseN, baseN); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /C# - Remove Comments From Code File: -------------------------------------------------------------------------------- 1 | public static void RemoveCommentsFromFile() 2 | { 3 | var inputFilepath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "../../Files/CodeFileWithComments.txt"); 4 | var outputFilepath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "../../Files/CodeFileWithoutComments.txt"); 5 | var data = File.ReadAllText(inputFilepath); 6 | var lines = data.Split(new[] { Environment.NewLine }, StringSplitOptions.None); 7 | List outputLines = new List(); 8 | bool multilineCommentFound = false; 9 | 10 | for (int i = 0; i < lines.Length; i++) 11 | { 12 | var line = lines[i]; 13 | for (int c = 0; c < line.Length - 1; c++) 14 | { 15 | if (!multilineCommentFound) 16 | { 17 | if (line[c] == '/' && line[c + 1] == '/') 18 | { 19 | line = line.Substring(0, (c == 0) ? 0 : c - 1); 20 | break; 21 | } 22 | 23 | if (line[c] == '/' && line[c + 1] == '*') 24 | { 25 | //dont break multi line comment may end on the same line 26 | multilineCommentFound = true; 27 | } 28 | } 29 | else if (line[c] == '*' && line[c + 1] == '/') 30 | { 31 | multilineCommentFound = false; 32 | line = line.Substring((c + 2 == line.Length - 1) ? line.Length - 1 : c + 2); 33 | break; 34 | } 35 | } 36 | 37 | if (!multilineCommentFound) 38 | { 39 | outputLines.Add(line); 40 | } 41 | } 42 | 43 | File.WriteAllText(outputFilepath, string.Join(Environment.NewLine, outputLines)); 44 | } 45 | 46 | public static void RemoveCommentsFromFileUsingRegex() 47 | { 48 | var inputFilepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../Files/CodeFileWithComments.txt"); 49 | var outputFilepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../Files/CodeFileWithoutComments.txt"); 50 | 51 | var data = File.ReadAllText(inputFilepath); 52 | 53 | var lineComments = @"//(.*?)\r?\n"; 54 | Regex regex = new Regex(lineComments); 55 | data = regex.Replace(data, ""); 56 | 57 | var blockComments = @"/\*(.*?)\*/"; 58 | regex = new Regex(blockComments, RegexOptions.Singleline); 59 | data = regex.Replace(data, ""); 60 | 61 | File.WriteAllText(outputFilepath, string.Join(Environment.NewLine, data)); 62 | } 63 | -------------------------------------------------------------------------------- /Hard - 01 - Alphabet Run Encryption: -------------------------------------------------------------------------------- 1 | function ReturnSequenceStartChar(arr) { 2 | var code1 = arr[0].charCodeAt(0); 3 | var code2 = arr[1].charCodeAt(0); 4 | var result; 5 | if (code1 + 1 == code2) { 6 | result = String.fromCharCode(code1 - 1); 7 | } 8 | else { 9 | result = String.fromCharCode(code1 + 1); 10 | } 11 | return result; 12 | } 13 | 14 | function ReturnSequenceEndChar(arr) { 15 | var code1 = arr[arr.length - 2].charCodeAt(0); 16 | var code2 = arr[arr.length - 1].charCodeAt(0); 17 | var result; 18 | if (code1 + 1 == code2) { 19 | result = String.fromCharCode(code2 + 1); 20 | } 21 | else { 22 | result = String.fromCharCode(code2 - 1); 23 | } 24 | return result; 25 | } 26 | 27 | function AlphabetRunEncryption(str) { 28 | var arr = [str[0]], prevCode = str.charCodeAt(0); 29 | var decoded = '', nextChar; 30 | for (var i = 1; i < str.length; i++) { 31 | var c = str[i]; 32 | var code = str.charCodeAt(i); 33 | var len = arr.length; 34 | if (c == 'S') { 35 | if (len > 2) { 36 | decoded += ReturnSequenceStartChar(arr.slice(0, len - 2)); 37 | decoded += arr[len - 2]; 38 | nextChar = arr[len - 1]; 39 | } 40 | else { 41 | decoded += arr[0]; 42 | nextChar = arr[1]; 43 | } 44 | arr = []; 45 | } 46 | else if (c == 'N') { 47 | if (len > 1) { 48 | decoded += ReturnSequenceStartChar(arr.slice(0, len - 1)); 49 | decoded += arr[len - 1]; 50 | nextChar = arr[len - 1]; 51 | } 52 | else { 53 | decoded += arr[0]; 54 | nextChar = arr[0]; 55 | } 56 | arr = []; 57 | } 58 | else if (c == 'R') { 59 | decoded += String.fromCharCode(arr[0].charCodeAt(0) - 1); 60 | nextChar = String.fromCharCode(arr[0].charCodeAt(0) + 1); 61 | arr = []; 62 | } 63 | else if (c == 'L') { 64 | decoded += String.fromCharCode(arr[0].charCodeAt(0) + 1); 65 | nextChar = String.fromCharCode(arr[0].charCodeAt(0) - 1); 66 | arr = []; 67 | } 68 | else if (prevCode + 1 != code && prevCode - 1 != code && len > 2) { 69 | decoded += ReturnSequenceStartChar(arr); 70 | nextChar = ReturnSequenceEndChar(arr); 71 | arr = []; 72 | prevCode = code; 73 | arr.push(c); 74 | } 75 | else if (i == str.length - 1) { 76 | arr.push(c); 77 | decoded += ReturnSequenceStartChar(arr); 78 | nextChar = ReturnSequenceEndChar(arr); 79 | arr = []; 80 | } 81 | else { 82 | prevCode = code; 83 | arr.push(c); 84 | } 85 | } 86 | 87 | return decoded + nextChar; 88 | } 89 | -------------------------------------------------------------------------------- /C# - Array Searching Algorithms: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace TestConsoleApp 8 | { 9 | class SearchingAlgorithms 10 | { 11 | //Find x using binary search 12 | public int BinarySearch(int[] a, int x) 13 | { 14 | int start = 0, end = a.Length - 1; 15 | while (start <= end) 16 | { 17 | int mid = (start + end) / 2; 18 | if (x == a[mid]) 19 | { 20 | return mid; 21 | } 22 | else if (x < a[mid]) 23 | { 24 | end = mid - 1; 25 | } 26 | else 27 | { 28 | start = mid + 1; 29 | } 30 | } 31 | 32 | return -1; 33 | } 34 | 35 | /* 36 | * Jump search also works for ordered lists. It selects a block and tries to find the element 37 | * in that block. If the element is not found, then it goes o the next block. The block size is 38 | * square root of the array size (√arrayLength). After finding a correct 39 | * block, it finds the element using a linear search technique. The jump search lies between linear search 40 | * and binary search according to its performance. 41 | */ 42 | public int JumpSearch(int[] a, int x) 43 | { 44 | int blocksize = (int)Math.Sqrt(a.Length); 45 | int start = 0, end = blocksize; 46 | while (end < a.Length && a[end] <= x) 47 | { 48 | start = end; 49 | end = end + blocksize; 50 | 51 | if (end > a.Length - 1) 52 | { 53 | //set end to array length to break the loop 54 | end = a.Length; 55 | } 56 | } 57 | 58 | //linear search from start to end 59 | for (int i = start; i < end; i++) 60 | { 61 | if (a[i] == x) 62 | { 63 | return i; 64 | } 65 | } 66 | 67 | return -1; 68 | } 69 | } 70 | 71 | class SearchingAlgorithmsTest 72 | { 73 | static void Main() 74 | { 75 | SearchingAlgorithms obj = new SearchingAlgorithms(); 76 | var indexByJumpSearch = obj.JumpSearch(new[] { 2, 6, 13, 21, 36, 47, 63, 81, 97 }, 97); 77 | var indexByBinarySearch = obj.BinarySearch(new[] { 2, 6, 13, 21, 36, 47, 63, 81, 97 }, 97); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /C# - Event Hit Counter: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace TempConsoleApp 9 | { 10 | //counter to find no.of times event/operation occured within last 5 mins 11 | class HitCounter 12 | { 13 | private enum EventType 14 | { 15 | Get, 16 | Put, 17 | Post, 18 | Delete 19 | } 20 | 21 | private Dictionary EventCounter = new Dictionary(); 22 | private int SlidingWindowInSeconds = 300; //5 mins 23 | 24 | public void Hit(string eventTypeName) 25 | { 26 | var eventType = (EventType)Enum.Parse(typeof(EventType), eventTypeName, true); 27 | var timestamp = GetTimestamp(); 28 | var bucketIndex = timestamp % SlidingWindowInSeconds; 29 | 30 | if (EventCounter.ContainsKey(eventType)) 31 | { 32 | long[,] timestampsAndHits = EventCounter[eventType]; 33 | if(timestampsAndHits[0, bucketIndex] == timestamp) 34 | { 35 | timestampsAndHits[1, bucketIndex]++; 36 | } 37 | else 38 | { 39 | //if timestamp doesn't match, set new timestamp and reset counter to 1; 40 | timestampsAndHits[0, bucketIndex] = timestamp; 41 | timestampsAndHits[1, bucketIndex] = 1; 42 | } 43 | } 44 | else 45 | { 46 | long[,] timestampsAndHits = new long[2, SlidingWindowInSeconds]; 47 | //for storing timestamps 48 | timestampsAndHits[0, bucketIndex] = timestamp; 49 | //for storing hits 50 | timestampsAndHits[1, bucketIndex] = 1; 51 | EventCounter.Add(eventType, timestampsAndHits); 52 | } 53 | } 54 | 55 | public long GetHits(string eventTypeName) 56 | { 57 | var eventType = (EventType)Enum.Parse(typeof(EventType), eventTypeName, true); 58 | var timestamp = GetTimestamp(); 59 | if (EventCounter.ContainsKey(eventType)) 60 | { 61 | long[,] timestampsAndHits = EventCounter[eventType]; 62 | long sum = 0; 63 | for (int i = 0; i < 300; i++) 64 | { 65 | //to find hits within last 300 seconds 66 | if (timestamp - timestampsAndHits[0, i] < 300) 67 | { 68 | sum = sum + timestampsAndHits[1, i]; 69 | } 70 | } 71 | 72 | return sum; 73 | } 74 | 75 | return -1; 76 | } 77 | 78 | private long GetTimestamp() 79 | { 80 | return Convert.ToInt64(DateTime.UtcNow.ToString("yyyyMMddHHmmss")); 81 | } 82 | } 83 | 84 | class HitCounterTest 85 | { 86 | static void Main() 87 | { 88 | HitCounter counter = new HitCounter(); 89 | counter.Hit("Get"); 90 | counter.Hit("GET"); 91 | counter.Hit("get"); 92 | counter.Hit("put"); 93 | counter.Hit("post"); 94 | counter.Hit("delete"); 95 | 96 | Console.WriteLine("No.of hits for event GET within last 5 mins:{0}", counter.GetHits("get")); 97 | Console.ReadLine(); 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /C# - Encoding And Decoding: -------------------------------------------------------------------------------- 1 | public void ASCIIEncodingAndDecodingTest() 2 | { 3 | //encode and write file 4 | string filesFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../Files/"); 5 | var ASCIIText = File.ReadAllText(filesFolder + "ASCIIText.txt"); 6 | var byteArray = Encoding.ASCII.GetBytes(ASCIIText); 7 | string[] b = byteArray.Select(x => Convert.ToString(x, 2).PadLeft(8, '0')).ToArray(); 8 | File.WriteAllText(filesFolder + "EncodedASCIIText.txt", string.Join("", b)); 9 | 10 | //read and decode file without using ASCII decoder 11 | var encodedASCIIText = File.ReadAllText(filesFolder + "EncodedASCIIText.txt"); 12 | var blockSize = 8; 13 | var noOf8BitBlocks = encodedASCIIText.Length / blockSize; 14 | var decodedString = ""; 15 | int blockIndex = 0; 16 | while(blockIndex < noOf8BitBlocks) 17 | { 18 | var bytestring = encodedASCIIText.Substring(blockIndex * blockSize, blockSize); 19 | decodedString = decodedString + (char)Convert.ToInt32(bytestring, 2); 20 | 21 | blockIndex++; 22 | } 23 | } 24 | 25 | public void UTF8EncodingAndDecodingTest() 26 | { 27 | //encode and write file 28 | string filesFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../Files/"); 29 | var ASCIIText = File.ReadAllText(filesFolder + "UTF8Text.txt"); 30 | var byteArray = Encoding.UTF8.GetBytes(ASCIIText); 31 | string[] b = byteArray.Select(x => Convert.ToString(x, 2).PadLeft(8, '0')).ToArray(); 32 | File.WriteAllText(filesFolder + "EncodedUTF8Text.txt", string.Join("", b)); 33 | 34 | //read and decode file without using UTF8 decoder 35 | var encodedText = File.ReadAllText(filesFolder + "EncodedUTF8Text.txt"); 36 | var blockSize = 8; 37 | var noOf8BitBlocks = encodedText.Length / blockSize; 38 | var decodedString = ""; 39 | int blockIndex = 0; 40 | while (blockIndex < noOf8BitBlocks) 41 | { 42 | int startIndex = blockIndex * blockSize; 43 | var bytestring = encodedText.Substring(startIndex, blockSize); 44 | if (bytestring.StartsWith("110")) //this starting byte is for a 2-byte char 45 | { 46 | bytestring = encodedText.Substring(startIndex, 2 * blockSize); 47 | blockIndex = blockIndex + 2; 48 | } 49 | else if (bytestring.StartsWith("1110")) //this starting byte is for a 3-byte char 50 | { 51 | bytestring = encodedText.Substring(startIndex, 3 * blockSize); 52 | blockIndex = blockIndex + 3; 53 | } 54 | else if (bytestring.StartsWith("11110")) //this starting byte is for a 4-byte char 55 | { 56 | bytestring = encodedText.Substring(startIndex, 4 * blockSize); 57 | blockIndex = blockIndex + 4; 58 | } 59 | else 60 | { 61 | blockIndex = blockIndex + 1; 62 | } 63 | decodedString = decodedString + (char)ConvertUTF8BinaryToDecimal(bytestring); 64 | } 65 | } 66 | 67 | public int ConvertUTF8BinaryToDecimal(string bytestring) 68 | { 69 | var resultBits = ""; 70 | // ignore header bits which are used to determine no.of bytes required to represent a char 71 | // and take bits which actually reperesent the unicode char 72 | if (bytestring.StartsWith("110")) //char needs 2 bytes 73 | { 74 | resultBits = bytestring.Substring(3, 5) + bytestring.Substring(10, 6); 75 | } 76 | else if (bytestring.StartsWith("1110")) //char needs 3 bytes 77 | { 78 | resultBits = bytestring.Substring(4, 4) + bytestring.Substring(10, 6) + bytestring.Substring(18, 6); 79 | } 80 | else if (bytestring.StartsWith("11110")) //char needs 4 bytes 81 | { 82 | resultBits = bytestring.Substring(5, 3) + bytestring.Substring(10, 6) + bytestring.Substring(26, 6); 83 | } 84 | else 85 | { 86 | resultBits = bytestring; 87 | } 88 | 89 | return Convert.ToInt32(resultBits, 2); 90 | } 91 | -------------------------------------------------------------------------------- /C# - Array Sorting Algorithms: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace TestConsoleApp 8 | { 9 | class SortingAlgorithms 10 | { 11 | public void BubbleSort(int[] a) 12 | { 13 | int temp; 14 | for (int i = 0; i < a.Length; i++) 15 | { 16 | bool swapped = false; 17 | for (int j = 0; j < a.Length - 1; j++) 18 | { 19 | if (a[j] > a[j + 1]) 20 | { 21 | temp = a[j]; 22 | a[j] = a[j + 1]; 23 | a[j + 1] = temp; 24 | 25 | swapped = true; 26 | } 27 | } 28 | 29 | /*if no number was swapped that means 30 | array is sorted now, break the loop.*/ 31 | if (!swapped) 32 | { 33 | break; 34 | } 35 | } 36 | } 37 | 38 | public void InsertionSort(int[] a) 39 | { 40 | int temp; 41 | for (int i = 1; i < a.Length; i++) 42 | { 43 | temp = a[i]; 44 | int j = i - 1; 45 | while (j >= 0 && a[j] > temp) 46 | { 47 | a[j + 1] = a[j]; 48 | j--; 49 | } 50 | a[j + 1] = temp; 51 | } 52 | } 53 | 54 | public void QuickSort(int[] a, int start, int end) 55 | { 56 | if (start >= end) 57 | { 58 | return; 59 | } 60 | 61 | int pIndex = Partition(a, start, end); 62 | QuickSort(a, start, pIndex - 1); 63 | QuickSort(a, pIndex + 1, end); 64 | } 65 | 66 | public int Partition(int[] a, int start, int end) 67 | { 68 | int pIndex = start; 69 | int pivot = a[end]; 70 | for (int i = start; i < end; i++) 71 | { 72 | if (a[i] <= pivot) 73 | { 74 | Swap(a, pIndex, i); 75 | pIndex++; 76 | } 77 | } 78 | 79 | Swap(a, pIndex, end); 80 | return pIndex; 81 | } 82 | 83 | void Swap(int[] a, int i, int j) 84 | { 85 | int temp = a[i]; 86 | a[i] = a[j]; 87 | a[j] = temp; 88 | } 89 | 90 | /*Given an array A[] consisting 0s, 1s and 2s, write a function that sorts A[]. 91 | * The functions should put all 0s first, then all 1s and all 2s in last. 92 | * */ 93 | public int[] ThreeTypeElementSort(int[] a) 94 | { 95 | int zerosIndex = 0, onesIndex = 0; 96 | int twosIndex = a.Length - 1; 97 | while (onesIndex <= twosIndex) 98 | { 99 | if (a[onesIndex] == 0) 100 | { 101 | Swap(a, onesIndex, zerosIndex); 102 | zerosIndex++; 103 | onesIndex++; 104 | } 105 | else if (a[onesIndex] == 1) 106 | { 107 | onesIndex++; 108 | } 109 | else if (a[onesIndex] == 2) 110 | { 111 | Swap(a, onesIndex, twosIndex); 112 | twosIndex--; 113 | } 114 | } 115 | 116 | return a; 117 | } 118 | 119 | //2 type element sort { -1, 1, -4, -3, 2, 3 } 120 | public int[] TwoTypeElementSort(int[] a) 121 | { 122 | int negativesIndex = 0; 123 | int positivesIndex = a.Length - 1; 124 | while (negativesIndex <= positivesIndex) 125 | { 126 | if (a[negativesIndex] < 0) 127 | { 128 | //negative exists in negative position, just move forward 129 | negativesIndex++; 130 | } 131 | else if (a[negativesIndex] > -1) 132 | { 133 | Swap(a, negativesIndex, positivesIndex); 134 | positivesIndex--; 135 | 136 | if (a[negativesIndex] < 0) 137 | { 138 | //after swapping, if value comes to the negatives index location is negative 139 | negativesIndex++; 140 | } 141 | } 142 | } 143 | 144 | return a; 145 | } 146 | } 147 | 148 | class SortingAlgorithmsTest 149 | { 150 | static void Main1() 151 | { 152 | SortingAlgorithms obj = new SortingAlgorithms(); 153 | int[] a = new[] { 7, 2, 1, 6, 8, 5, 3, 4 }; 154 | 155 | obj.QuickSort(a, 0, a.Length - 1); 156 | obj.BubbleSort(a); 157 | obj.InsertionSort(a); 158 | 159 | int[] rearrangedArray = obj.TwoTypeElementSort(new[] { -1, 1, -4, -3, 2, 3 }); 160 | var sortArray = obj.ThreeTypeElementSort(new[] { 2, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }); 161 | } 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /C# - Doubly Linked List: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace TempConsoleApp.Nodes 8 | { 9 | class DNode 10 | { 11 | public int data; 12 | public DNode next; 13 | public DNode prev; 14 | public DNode(int data) 15 | { 16 | this.data = data; 17 | } 18 | } 19 | 20 | class DoubleLinkedList 21 | { 22 | public DNode head; 23 | 24 | public void AddFirst(DNode newNode) 25 | { 26 | newNode.next = head; 27 | if (head != null) 28 | { 29 | head.prev = newNode; 30 | } 31 | head = newNode; 32 | } 33 | 34 | public void AddLast(DNode newNode) 35 | { 36 | var lastNode = GetLast(); 37 | if (lastNode == null) 38 | { 39 | head = newNode; 40 | } 41 | else 42 | { 43 | lastNode.next = newNode; 44 | newNode.prev = lastNode; 45 | } 46 | } 47 | 48 | public DNode GetLast() 49 | { 50 | if (head == null) 51 | { 52 | return null; 53 | } 54 | 55 | var current = head; 56 | while (current.next != null) 57 | { 58 | current = current.next; 59 | } 60 | 61 | return current; 62 | } 63 | 64 | public DNode Find(int data) 65 | { 66 | if (head == null) 67 | { 68 | return null; 69 | } 70 | 71 | var current = head; 72 | while (current != null) 73 | { 74 | if (current.data == data) 75 | { 76 | return current; 77 | } 78 | current = current.next; 79 | } 80 | 81 | return null; 82 | } 83 | 84 | public void Remove(DNode node) 85 | { 86 | if (node != null) 87 | { 88 | var prev = node.prev; 89 | var next = node.next; 90 | if (prev != null) 91 | { 92 | prev.next = next; 93 | } 94 | 95 | if (next != null) 96 | { 97 | next.prev = prev; 98 | } 99 | } 100 | } 101 | 102 | public void Swap(DNode n1, DNode n2) 103 | { 104 | // Nothing to do if x and y are same 105 | if (n1 == n2) return; 106 | 107 | var n1prev = n1.prev; 108 | var n2prev = n2.prev; 109 | var n1next = n1.next; 110 | var n2next = n2.next; 111 | 112 | if (n1.next == n2) 113 | { 114 | // If n1 is not head of linked list 115 | if (n1prev != null) 116 | { 117 | n1prev.next = n2; 118 | } 119 | else 120 | { 121 | //make n2 the new head 122 | head = n2; 123 | } 124 | n2.next = n1; 125 | n1.next = n2next; 126 | if (n2next != null) 127 | { 128 | n2next.prev = n1; 129 | } 130 | n1.prev = n2; 131 | n2.prev = n1prev; 132 | } 133 | else if (n1.prev == n2) 134 | { 135 | if (n2prev != null) 136 | { 137 | n2prev.next = n1; 138 | } 139 | else 140 | { 141 | head = n1; 142 | } 143 | n1.next = n2; 144 | n2.next = n1next; 145 | if (n1next != null) 146 | { 147 | n1next.prev = n2; 148 | } 149 | n2.prev = n1; 150 | n1.prev = n2prev; 151 | } 152 | else 153 | { 154 | if (n1prev != null) 155 | { 156 | n1prev.next = n2; 157 | } 158 | else 159 | { 160 | head = n2; 161 | } 162 | 163 | if (n2prev != null) 164 | { 165 | n2prev.next = n1; 166 | } 167 | else 168 | { 169 | head = n1; 170 | } 171 | 172 | // Swap next pointers 173 | n1.next = n2next; 174 | n2.next = n1next; 175 | 176 | if (n1next != null) 177 | { 178 | n1next.prev = n2; 179 | } 180 | 181 | if (n2next != null) 182 | { 183 | n2next.prev = n1; 184 | } 185 | 186 | // Swap prev pointers 187 | n1.prev = n2prev; 188 | n2.prev = n1prev; 189 | } 190 | } 191 | 192 | public void PrintNodes() 193 | { 194 | if (head == null) 195 | { 196 | return; 197 | } 198 | 199 | var current = head; 200 | while (current != null) 201 | { 202 | Console.Write(current.data + " "); 203 | current = current.next; 204 | } 205 | } 206 | 207 | public void PrintNodesInReverseOrder() 208 | { 209 | if (head == null) 210 | { 211 | return; 212 | } 213 | 214 | var current = GetLast(); 215 | while (current != null) 216 | { 217 | Console.Write(current.data + " "); 218 | current = current.prev; 219 | } 220 | } 221 | } 222 | 223 | class DoubleLinkedListTest 224 | { 225 | static void Run(Action action, string actionName, bool addNewLineAfterTitle = false) 226 | { 227 | Console.Write($"{actionName}: "); 228 | if (addNewLineAfterTitle) 229 | { 230 | Console.WriteLine(); 231 | } 232 | action(); 233 | Console.WriteLine(); 234 | Console.WriteLine(); 235 | } 236 | 237 | static void Main() 238 | { 239 | DoubleLinkedList list = new DoubleLinkedList(); 240 | list.AddLast(new DNode(10)); 241 | list.AddLast(new DNode(15)); 242 | list.AddLast(new DNode(12)); 243 | list.AddLast(new DNode(13)); 244 | list.AddLast(new DNode(20)); 245 | list.AddLast(new DNode(14)); 246 | 247 | string values = "10 14"; 248 | while (!string.IsNullOrEmpty(values)) 249 | { 250 | Run(() => list.PrintNodes(), "BeforeSwap-PrintNodes"); 251 | var nodes = values.Split(' ').Select(v => int.Parse(v)).ToArray(); 252 | list.Swap(list.Find(nodes[0]), list.Find(nodes[1])); 253 | //to ensure next connections are set properly 254 | Run(() => list.PrintNodes(), "AfterSwap-PrintNodes"); 255 | //to ensure prev connections are set properly 256 | Run(() => list.PrintNodesInReverseOrder(), "AfterSwap-PrintNodesInReverse"); 257 | Console.Write("Swap Nodes:"); 258 | values = Console.ReadLine(); 259 | } 260 | 261 | //list.Remove(list.Find(3)); 262 | 263 | Console.ReadLine(); 264 | } 265 | } 266 | } 267 | -------------------------------------------------------------------------------- /C# - Binary Tree: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace TempConsoleApp.Nodes 8 | { 9 | class BTNode 10 | { 11 | public int data; 12 | public BTNode left; 13 | public BTNode right; 14 | 15 | public BTNode(int data) 16 | { 17 | this.data = data; 18 | } 19 | } 20 | 21 | class BinaryTree 22 | { 23 | public BTNode root; 24 | 25 | public void InsertLeft(BTNode node, int data) 26 | { 27 | var newNode = new BTNode(data); 28 | 29 | if (node.left == null) 30 | { 31 | node.left = newNode; 32 | } 33 | { 34 | newNode.left = node.left; 35 | node.left = newNode; 36 | } 37 | } 38 | 39 | public int Height(BTNode root) 40 | { 41 | if (root == null) 42 | { 43 | return 0; 44 | } 45 | 46 | return Math.Max(Height(root.left), Height(root.right)) + 1; 47 | } 48 | 49 | public void LeafNodes(BTNode root, List nodes) 50 | { 51 | if (root == null) 52 | { 53 | return; 54 | } 55 | 56 | if (root.left == null && root.right == null) 57 | { 58 | nodes.Add(root); 59 | return; 60 | } 61 | 62 | LeafNodes(root.left, nodes); 63 | LeafNodes(root.right, nodes); 64 | } 65 | 66 | public void NodesWithOneChild(BTNode root, List nodes) 67 | { 68 | if (root == null) 69 | { 70 | return; 71 | } 72 | 73 | if ((root.left == null && root.right != null) || (root.right == null && root.left != null)) 74 | { 75 | //when left or right is null but not both 76 | nodes.Add(root); 77 | return; 78 | } 79 | 80 | NodesWithOneChild(root.left, nodes); 81 | NodesWithOneChild(root.right, nodes); 82 | } 83 | 84 | public void PrintNodesAtLevel(BTNode root, int level) 85 | { 86 | if (root == null) 87 | { 88 | return; 89 | } 90 | 91 | if (level == 0) 92 | { 93 | Console.Write(root.data + " "); 94 | } 95 | else 96 | { 97 | PrintNodesAtLevel(root.left, level - 1); 98 | PrintNodesAtLevel(root.right, level - 1); 99 | } 100 | } 101 | 102 | public void PrintNodesInLevelOrder(BTNode root) 103 | { 104 | int height = Height(root); 105 | for (int i = 0; i < height; i++) 106 | { 107 | PrintNodesAtLevel(root, i); 108 | } 109 | } 110 | 111 | public void PrintNodesInLevelOrderUsingBFS(BTNode root) 112 | { 113 | List list = BFS(root); 114 | foreach (var item in list) 115 | { 116 | Console.Write(item.data + " "); 117 | } 118 | } 119 | 120 | public List BFS(BTNode root) 121 | { 122 | if (root == null) 123 | { 124 | return null; 125 | } 126 | 127 | List list = new List(); 128 | Queue q = new Queue(); 129 | q.Enqueue(root); 130 | 131 | while (q.Count > 0) 132 | { 133 | var current = q.Dequeue(); 134 | list.Add(current); 135 | 136 | if (current.left != null) 137 | { 138 | q.Enqueue(current.left); 139 | } 140 | 141 | if (current.right != null) 142 | { 143 | q.Enqueue(current.right); 144 | } 145 | } 146 | 147 | return list; 148 | } 149 | 150 | public int HeightUsingBFS(BTNode root) 151 | { 152 | if (root == null) 153 | { 154 | return 0; 155 | } 156 | 157 | Queue q = new Queue(); 158 | q.Enqueue(root); 159 | int height = 0; 160 | 161 | while (q.Count > 0) 162 | { 163 | int nodeCountAtCurrentLevel = q.Count; 164 | while (nodeCountAtCurrentLevel > 0) 165 | { 166 | var current = q.Dequeue(); 167 | 168 | if (current.left != null) 169 | { 170 | q.Enqueue(current.left); 171 | } 172 | 173 | if (current.right != null) 174 | { 175 | q.Enqueue(current.right); 176 | } 177 | 178 | nodeCountAtCurrentLevel--; 179 | } 180 | 181 | height++; 182 | } 183 | 184 | return height; 185 | } 186 | 187 | public void PrintNodesAtLevelUsingBFS(BTNode root, int level) 188 | { 189 | if (root == null) 190 | { 191 | return; 192 | } 193 | 194 | Queue q = new Queue(); 195 | q.Enqueue(root); 196 | int height = 0; 197 | 198 | while (q.Count > 0) 199 | { 200 | int nodeCountAtCurrentLevel = q.Count; 201 | while (nodeCountAtCurrentLevel > 0) 202 | { 203 | var current = q.Dequeue(); 204 | 205 | if (height == level) 206 | { 207 | Console.Write(current.data + " "); 208 | } 209 | 210 | if (current.left != null) 211 | { 212 | q.Enqueue(current.left); 213 | } 214 | 215 | if (current.right != null) 216 | { 217 | q.Enqueue(current.right); 218 | } 219 | 220 | nodeCountAtCurrentLevel--; 221 | } 222 | 223 | height++; 224 | 225 | if (height > level) 226 | { 227 | return; 228 | } 229 | } 230 | } 231 | 232 | // Pre-Order: in any subtree, traverse middle->left->right 233 | public void PreOrder(BTNode root, List list = null) 234 | { 235 | if (root == null) 236 | { 237 | return; 238 | } 239 | 240 | if (list != null) 241 | { 242 | list.Add(root.data); 243 | } 244 | else 245 | { 246 | Console.Write(root.data + " "); 247 | } 248 | 249 | PreOrder(root.left, list); 250 | PreOrder(root.right, list); 251 | } 252 | 253 | // In-Order: in any subtree, traverse left->middle->right 254 | public void InOrder(BTNode root) 255 | { 256 | if (root == null) 257 | { 258 | return; 259 | } 260 | 261 | InOrder(root.left); 262 | Console.Write(root.data + " "); 263 | InOrder(root.right); 264 | } 265 | 266 | // Post-Order: in any subtree, traverse left->right->middle 267 | public void PostOrder(BTNode root) 268 | { 269 | if (root == null) 270 | { 271 | return; 272 | } 273 | 274 | PostOrder(root.left); 275 | PostOrder(root.right); 276 | Console.Write(root.data + " "); 277 | } 278 | 279 | public BTNode LowestCommonAncestor(BTNode root, int a, int b) 280 | { 281 | if (root == null) 282 | { 283 | return null; 284 | } 285 | 286 | if (root.data == a || root.data == b) 287 | { 288 | return root; 289 | } 290 | 291 | var left = LowestCommonAncestor(root.left, a, b); 292 | var right = LowestCommonAncestor(root.right, a, b); 293 | 294 | if (left != null && right != null) 295 | { 296 | return root; 297 | } 298 | else 299 | { 300 | return left ?? right; 301 | } 302 | } 303 | 304 | public BTNode FindParent(BTNode root, int a) 305 | { 306 | if (root == null) 307 | { 308 | return null; 309 | } 310 | 311 | if ((root.left != null && root.left.data == a) || (root.right != null && root.right.data == a)) 312 | { 313 | return root; 314 | } 315 | 316 | var left = FindParent(root.left, a); 317 | if (left != null) 318 | { 319 | return left; 320 | } 321 | 322 | return FindParent(root.right, a); 323 | } 324 | 325 | public BTNode Find(BTNode root, int a) 326 | { 327 | if (root == null) 328 | { 329 | return null; 330 | } 331 | 332 | if (root.data == a) 333 | { 334 | return root; 335 | } 336 | 337 | var left = Find(root.left, a); 338 | if (left != null) 339 | { 340 | return left; 341 | } 342 | 343 | return Find(root.right, a); 344 | } 345 | 346 | 347 | public bool FindAncestors(BTNode root, int a, List list) 348 | { 349 | if (root == null) 350 | { 351 | return false; 352 | } 353 | 354 | if (root.data == a) 355 | { 356 | return true; 357 | } 358 | 359 | if (FindAncestors(root.left, a, list) || FindAncestors(root.right, a, list)) 360 | { 361 | list.Add(root.data); 362 | return true; 363 | } 364 | 365 | return false; 366 | } 367 | 368 | public int LowestCommonAncestorUsingAncestor(BTNode root, int a, int b) 369 | { 370 | var aAncestors = new List(); 371 | FindAncestors(root, a, aAncestors); 372 | 373 | var bAncestors = new List(); 374 | FindAncestors(root, b, bAncestors); 375 | 376 | return aAncestors.Intersect(bAncestors).FirstOrDefault(); 377 | } 378 | 379 | public void DeepestNode(BTNode root) 380 | { 381 | List list = BFS(root); 382 | Console.Write(list[list.Count - 1].data); 383 | } 384 | 385 | public void LeftMostNode(BTNode root) 386 | { 387 | var current = root; 388 | while (current.left != null) 389 | { 390 | current = current.left; 391 | } 392 | Console.Write(current.data); 393 | } 394 | 395 | public void RightMostNode(BTNode root) 396 | { 397 | var current = root; 398 | while (current.right != null) 399 | { 400 | current = current.right; 401 | } 402 | Console.Write(current.data); 403 | } 404 | 405 | public bool IsIdentical(BTNode x, BTNode y) 406 | { 407 | if (x == null && y == null) 408 | return true; 409 | 410 | if (x == null || y == null) 411 | return false; 412 | 413 | return (x.data == y.data) && IsIdentical(x.left, y.left) && IsIdentical(x.right, y.right); 414 | } 415 | 416 | public void PrintPaths(BTNode root, String path, List paths) 417 | { 418 | if (root == null) 419 | { 420 | return; 421 | } 422 | 423 | path = (string.IsNullOrEmpty(path) ? string.Empty : path + ",") + root.data; 424 | 425 | if (root.left == null && root.right == null) 426 | { 427 | paths.Add(path); 428 | return; 429 | } 430 | 431 | PrintPaths(root.left, path, paths); 432 | PrintPaths(root.right, path, paths); 433 | } 434 | 435 | 436 | } 437 | 438 | class BinaryTreeTest 439 | { 440 | public static void Populate(BinaryTree tree) 441 | { 442 | tree.root = new BTNode(1); 443 | tree.root.left = new BTNode(2); 444 | tree.root.right = new BTNode(3); 445 | tree.root.left.left = new BTNode(4); 446 | tree.root.left.right = new BTNode(5); 447 | tree.root.left.right.left = new BTNode(8); 448 | tree.root.right.left = new BTNode(6); 449 | tree.root.right.right = new BTNode(7); 450 | tree.root.right.right.right = new BTNode(9); 451 | 452 | tree.root.left.left.left = new BTNode(10); 453 | tree.root.left.left.left.left = new BTNode(11); 454 | } 455 | 456 | public static void Run(Action action, string actionName) 457 | { 458 | Console.Write($"{actionName}: "); 459 | action(); 460 | Console.WriteLine(); 461 | Console.WriteLine(); 462 | } 463 | 464 | public static void Main(string[] args) 465 | { 466 | BinaryTree tree = new BinaryTree(); 467 | Populate(tree); 468 | 469 | var paths = new List(); 470 | tree.PrintPaths(tree.root, string.Empty, paths); 471 | 472 | Run(() => 473 | { 474 | Console.WriteLine(); 475 | foreach (var path in paths) 476 | { 477 | Console.WriteLine(path.Replace(",","-->")); 478 | } 479 | 480 | }, "AllPaths"); 481 | 482 | Run(() => Console.Write(paths.OrderBy(p => p.Split(',').Length).Last()), "LongestPath"); 483 | 484 | 485 | Run(() => Console.Write(tree.Height(tree.root)), "Height"); 486 | Run(() => Console.Write(tree.HeightUsingBFS(tree.root)), "HeightUsingBFS"); 487 | Run(() => tree.PreOrder(tree.root), "PreOrder"); 488 | Run(() => tree.InOrder(tree.root), "InOrder"); 489 | Run(() => tree.PostOrder(tree.root), "PostOrder"); 490 | Run(() => tree.PrintNodesInLevelOrder(tree.root), "PrintNodesInLevelOrder"); 491 | Run(() => tree.PrintNodesInLevelOrderUsingBFS(tree.root), "PrintNodesInLevelOrderUsingBFS"); 492 | Run(() => tree.PrintNodesAtLevelUsingBFS(tree.root, 3), "PrintNodesAtLevelUsingBFS"); 493 | Run(() => tree.DeepestNode(tree.root), "DeepestNode"); 494 | Run(() => tree.LeftMostNode(tree.root), "LeftMostNode"); 495 | Run(() => tree.RightMostNode(tree.root), "RightMostNode"); 496 | Run(() => Console.Write(tree.FindParent(tree.root, 6).data), "Parent of 6"); 497 | Run(() => 498 | { 499 | List list = new List(); 500 | tree.FindAncestors(tree.root, 8, list); 501 | foreach (var item in list) 502 | { 503 | Console.Write(item + " "); 504 | } 505 | }, "FindAncestors"); 506 | Run(() => 507 | { 508 | List list = new List(); 509 | tree.FindAncestors(tree.root, 8, list); 510 | var nthParent = 3; 511 | if (nthParent <= list.Count) 512 | { 513 | Console.Write(list[nthParent - 1]); 514 | } 515 | 516 | }, "FindNthParent"); 517 | Run(() => 518 | { 519 | List list = new List(); 520 | tree.LeafNodes(tree.root, list); 521 | foreach (var item in list) 522 | { 523 | Console.Write(item.data + " "); 524 | } 525 | 526 | }, "LeafNodes"); 527 | Run(() => 528 | { 529 | List list = new List(); 530 | tree.NodesWithOneChild(tree.root, list); 531 | foreach (var item in list) 532 | { 533 | Console.Write(item.data + " "); 534 | } 535 | 536 | }, "NodesWithOneChild"); 537 | Run(() => Console.Write(tree.LowestCommonAncestor(tree.root, 8, 9).data), "LowestCommonAncestor"); 538 | Run(() => 539 | { 540 | var lca = tree.LowestCommonAncestorUsingAncestor(tree.root, 6, 7); 541 | Console.Write(lca + " "); 542 | }, "LowestCommonAncestorUsingAncestor"); 543 | 544 | var tree2 = new BinaryTree(); 545 | Populate(tree2); 546 | tree2.root.data = 2; 547 | Run(() => Console.Write(tree.IsIdentical(tree.root, tree2.root)), "IsIdentical"); 548 | 549 | Console.ReadLine(); 550 | } 551 | } 552 | } 553 | --------------------------------------------------------------------------------