├── coding-problems ├── .gitignore ├── src │ ├── codewars │ │ ├── DigPow.java │ │ ├── TwoCubeSums.java │ │ ├── BinaryRegexp.java │ │ ├── ValidPerfectSquare.java │ │ ├── SmallestValueOfAnArray.java │ │ ├── FindThePosition.java │ │ ├── SquareDigit.java │ │ ├── DeltaBits.java │ │ ├── SquashTheBugs.java │ │ ├── TrailingZeroes.java │ │ ├── StringyString.java │ │ ├── MonkeyCounter.java │ │ ├── HumanReadableTime.java │ │ ├── NumberFun.java │ │ ├── AgeRangeCompatibilityEquation.java │ │ ├── Scramblies.java │ │ ├── SpinWords.java │ │ ├── DigitalRoot.java │ │ ├── ReversePolishNotationCalc.java │ │ ├── DeodorantEvaporator.java │ │ ├── AckermannFunction.java │ │ ├── JadenCase.java │ │ ├── PersistentBugger.java │ │ ├── QuickCals.java │ │ ├── BeforeAfterPrimes.java │ │ ├── AlternateSquareSum.java │ │ ├── CircularlySortedArray.java │ │ ├── CalculateStringRotation.java │ │ ├── SumSquaredDivisors.java │ │ ├── Consecutives.java │ │ ├── WordPattern.java │ │ ├── JosephusSurvivor.java │ │ ├── RevRot.java │ │ ├── DivisibleInts.java │ │ ├── EqualSidesOfAnArray.java │ │ ├── EANValidator.java │ │ └── TwoStrings.java │ ├── algorithms │ │ ├── QuickSort.java │ │ ├── EuclideanAlgorithm.java │ │ ├── NaivePatternMatchingAlgorithm.java │ │ ├── OptimizedNaivePatternMatchingAlgorithm.java │ │ ├── JugglingAlgorithm.java │ │ ├── ReversalAlgorithm.java │ │ ├── ZAlgorithm.java │ │ └── RabinKarpAlgorithm.java │ ├── datastructures │ │ ├── Stack │ │ │ ├── CustomStackInLinkedList.java │ │ │ └── CustomStackInArray.java │ │ ├── Recursion │ │ │ ├── NaturalNumberSum.java │ │ │ ├── Factorial.java │ │ │ ├── RecursionExampleOne.java │ │ │ ├── RecursionExampleTwo.java │ │ │ └── FibnonacciNumber.java │ │ ├── BITManipulation │ │ │ ├── NumberIsPowerOf2.java │ │ │ ├── FindLog2BaseNumber.java │ │ │ ├── FindXOR.java │ │ │ ├── AlternateSetBits.java │ │ │ ├── XORSum.java │ │ │ ├── ComputeXOR1ToN.java │ │ │ ├── FlippingBits.java │ │ │ ├── SwapANumber.java │ │ │ ├── EqualSumAndXOR.java │ │ │ ├── CountSetBits.java │ │ │ ├── Program10.java │ │ │ ├── Program9.java │ │ │ ├── Program8.java │ │ │ ├── Program7.java │ │ │ ├── Program11.java │ │ │ ├── Program5.java │ │ │ ├── Program6.java │ │ │ ├── BitwiseHacks.java │ │ │ ├── Program12.java │ │ │ ├── Program4.java │ │ │ ├── Program3.java │ │ │ ├── Program1.java │ │ │ └── Program2.java │ │ ├── BinaryHeap │ │ │ ├── ExecuteCode.java │ │ │ └── MinHeap.java │ │ ├── Math │ │ │ ├── CelsiusToFahrenheit.java │ │ │ ├── AbsoluteValue.java │ │ │ ├── FindingNoofDigitsInANumber.java │ │ │ └── QuadraticEquationRoots.java │ │ ├── Array │ │ │ ├── SumAndAverage.java │ │ │ ├── ArraySortedOrNot.java │ │ │ ├── PerfectArrays.java │ │ │ ├── ValueEqualToIndexValue.java │ │ │ ├── NumberOfNumbers.java │ │ │ ├── LeaderInArray.java │ │ │ ├── FascinatingNumber.java │ │ │ ├── GetPairsCount.java │ │ │ ├── GreaterOnRightSide.java │ │ │ ├── PlayWithAnArray.java │ │ │ ├── CheckMergeArray.java │ │ │ ├── ReverseAnArray.java │ │ │ └── CheckRemoveEven.java │ │ ├── Hashing │ │ │ ├── UnionArray.java │ │ │ ├── IntersectionArray.java │ │ │ ├── MyHash.java │ │ │ ├── CountDistinctElements.java │ │ │ └── LinearProbingHashing.java │ │ ├── String │ │ │ ├── Problem6.java │ │ │ ├── Problem4.java │ │ │ └── Problem5.java │ │ └── Trie │ │ │ └── TrieOperations.java │ ├── namasteDSA │ │ ├── LargestNumber.java │ │ ├── SmallestNumber.java │ │ ├── LinearSearch.java │ │ ├── SecondLargest.java │ │ └── EvenOrOdd.java │ ├── leetcode │ │ ├── MissingNumber.java │ │ ├── MoveZeroes.java │ │ ├── HIndexPartTwo.java │ │ ├── MaxConsecutiveOnes.java │ │ ├── ContainsDuplicate.java │ │ ├── MergeSortedArray.java │ │ ├── BuyAndSellStock.java │ │ ├── PowerOfTwo.java │ │ ├── ReverseString.java │ │ ├── topIntQuests │ │ │ ├── SubarraySumK.java │ │ │ ├── PowerOfThree.java │ │ │ └── DailyTemperatures.java │ │ ├── PlusOne.java │ │ ├── RemoveElement.java │ │ ├── ConsecutiveCharacters.java │ │ ├── DominantIndex.java │ │ ├── TitleToNumber.java │ │ ├── HIndexPartOne.java │ │ ├── TwoSum.java │ │ └── PivotIndex.java │ ├── hackerearth │ │ ├── FindProduct.java │ │ ├── LifeTheUniverseAndEverything.java │ │ ├── ASCIIValue.java │ │ ├── Factorial.java │ │ ├── TrickWithTheCards.java │ │ ├── CountDivisors.java │ │ ├── IntelligentGirl.java │ │ ├── PalindromicString.java │ │ ├── PrimeNumber.java │ │ ├── ToggleString.java │ │ ├── RoyAndProfilePicture.java │ │ ├── SeatingArrangement.java │ │ ├── TwoStrings.java │ │ └── PlayWIthNumbersSimple.java │ ├── company │ │ ├── nearbuy │ │ │ ├── MaximumDifference.java │ │ │ ├── UsernameDisparitySimpleLogic.java │ │ │ └── CountDuplicates.java │ │ ├── HSBC │ │ │ ├── HelpJohn.java │ │ │ └── SamHeight.java │ │ ├── fidelityInternational │ │ │ ├── DistBetTwoPoints.java │ │ │ └── AnimalInheritance.java │ │ └── thoughtWorks │ │ │ ├── TrickWithTheCards.java │ │ │ └── IntelligentGirl.java │ └── hackerrank │ │ └── ReverseArray.java ├── .settings │ ├── org.eclipse.core.resources.prefs │ └── org.eclipse.jdt.core.prefs ├── .classpath ├── .project └── PendingSols │ ├── GyanMatrix │ ├── SubsetMaximization.txt │ └── Gifts.txt │ ├── VivitriCapital │ ├── Partial Digit Subsequence.txt │ └── VowelQuery.txt │ ├── SamsungR_D │ └── BobAndBeautyOfTheArray.txt │ └── PayPal │ ├── Bob and Forest.txt │ ├── Even Length Palindromic Number.txt │ └── Maximize the Value.txt └── .gitignore /coding-problems/.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/DigPow.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pgeek92/code-problems/HEAD/coding-problems/src/codewars/DigPow.java -------------------------------------------------------------------------------- /coding-problems/src/codewars/TwoCubeSums.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pgeek92/code-problems/HEAD/coding-problems/src/codewars/TwoCubeSums.java -------------------------------------------------------------------------------- /coding-problems/src/algorithms/QuickSort.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | public class QuickSort { 4 | 5 | public static void main(String[] args) { 6 | 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Stack/CustomStackInLinkedList.java: -------------------------------------------------------------------------------- 1 | package datastructures.Stack; 2 | 3 | public class CustomStackInLinkedList { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /coding-problems/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/algorithms/MOsAlgorithm.java=UTF-8 3 | encoding//src/codewars/DigPow.java=UTF-8 4 | encoding//src/codewars/EANValidator.java=UTF-8 5 | encoding//src/codewars/Line.java=UTF-8 6 | -------------------------------------------------------------------------------- /coding-problems/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Recursion/NaturalNumberSum.java: -------------------------------------------------------------------------------- 1 | package datastructures.Recursion; 2 | 3 | public class NaturalNumberSum { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(getSum(4)); 7 | } 8 | 9 | public static int getSum(int n) { 10 | if(n == 0) { 11 | return 0; 12 | } 13 | 14 | return n + getSum(n-1); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/NumberIsPowerOf2.java: -------------------------------------------------------------------------------- 1 | package datastructures.BITManipulation; 2 | 3 | public class NumberIsPowerOf2 { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(isNumPowerOfTwo(64)); 7 | } 8 | 9 | public static boolean isNumPowerOfTwo(int num) { 10 | return num != 0 && ((num & (num - 1)) == 0); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.ear 17 | *.zip 18 | *.tar.gz 19 | *.rar 20 | 21 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 22 | hs_err_pid* 23 | /.metadata/ 24 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Recursion/Factorial.java: -------------------------------------------------------------------------------- 1 | package datastructures.Recursion; 2 | 3 | public class Factorial { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(factorialOfANumber(4)); 7 | } 8 | 9 | public static int factorialOfANumber(int num) { 10 | if(num == 1) { 11 | return 1; 12 | } 13 | return num * factorialOfANumber(num - 1); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Recursion/RecursionExampleOne.java: -------------------------------------------------------------------------------- 1 | package datastructures.Recursion; 2 | 3 | public class RecursionExampleOne { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(sumOfNNumbers(5)); 7 | 8 | } 9 | 10 | public static int sumOfNNumbers(int num) { 11 | if(num == 0) { 12 | return 0; 13 | } 14 | return num + sumOfNNumbers(num-1); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/FindLog2BaseNumber.java: -------------------------------------------------------------------------------- 1 | package datastructures.BITManipulation; 2 | 3 | public class FindLog2BaseNumber { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(log2BaseNum(7)); 7 | } 8 | 9 | public static int log2BaseNum (int num) { 10 | int count = 0; 11 | while (num > 1) { 12 | num >>= 1; 13 | count++; 14 | } 15 | return count; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BinaryHeap/ExecuteCode.java: -------------------------------------------------------------------------------- 1 | package datastructures.BinaryHeap; 2 | 3 | public class ExecuteCode { 4 | public static void main(String[] args) { 5 | MinHeap minHeap = new MinHeap(6); 6 | int[] array = minHeap.initialize(6); 7 | for(int i = 0; i < array.length; i++) { 8 | System.out.println(array[i]); 9 | } 10 | int left = minHeap.right(1); 11 | System.out.println(left); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/BinaryRegexp.java: -------------------------------------------------------------------------------- 1 | package codewars; 2 | 3 | import java.util.regex.Pattern; 4 | 5 | public class BinaryRegexp { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(multipleOf3()); 9 | } 10 | 11 | public static Pattern multipleOf3() { 12 | // Regular expression that matches binary inputs that are multiple of 3 13 | return Pattern.compile("(0|1(01*0)*1)*"); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/FindXOR.java: -------------------------------------------------------------------------------- 1 | package datastructures.BITManipulation; 2 | 3 | public class FindXOR { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(findXOR(new int[] {1, 2, 3, 4})); 7 | 8 | } 9 | 10 | public static int findXOR(int[] arr) { 11 | int arrL = arr.length; 12 | if(arrL == 1) { 13 | return arr[0]; 14 | } else { 15 | return 0; 16 | } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/AlternateSetBits.java: -------------------------------------------------------------------------------- 1 | package datastructures.BITManipulation; 2 | 3 | public class AlternateSetBits { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(bitsAreInAltOrder(5)); 7 | 8 | } 9 | 10 | public static boolean bitsAreInAltOrder(int n) { 11 | int num = n ^ (n >> 1); 12 | if(((num + 1) & num) == 0) { 13 | return true; 14 | } 15 | return false; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Recursion/RecursionExampleTwo.java: -------------------------------------------------------------------------------- 1 | package datastructures.Recursion; 2 | 3 | public class RecursionExampleTwo { 4 | 5 | public static void main(String[] args) { 6 | int[] arr = {5,2,6,1,3}; 7 | System.out.println(sum(arr.length-1, arr)); 8 | 9 | } 10 | 11 | public static int sum(int n, int[] arr) { 12 | if(n == 0) { 13 | return arr[0]; 14 | } 15 | return arr[n] + sum(n-1, arr); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /coding-problems/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | coding-problems 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Recursion/FibnonacciNumber.java: -------------------------------------------------------------------------------- 1 | package datastructures.Recursion; 2 | 3 | public class FibnonacciNumber { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(fib(100)); 7 | 8 | } 9 | 10 | /** 11 | * Time Complexity : O(2^N) 12 | * Space Complexity : O(N) 13 | * @param n 14 | * @return 15 | */ 16 | public static int fib(int n) { 17 | if(n <= 1) return n; 18 | return fib(n-1) + fib(n-2); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /coding-problems/src/namasteDSA/LargestNumber.java: -------------------------------------------------------------------------------- 1 | package namasteDSA; 2 | 3 | public class LargestNumber { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(findLargest(new int[] {2, -6, 4, 8, 1, -9})); 7 | } 8 | 9 | public static int findLargest(int[] arr) { 10 | int largest = Integer.MIN_VALUE; 11 | for(int number : arr) { 12 | if(number > largest) { 13 | largest = number; 14 | } 15 | } 16 | 17 | return largest; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /coding-problems/src/namasteDSA/SmallestNumber.java: -------------------------------------------------------------------------------- 1 | package namasteDSA; 2 | 3 | public class SmallestNumber { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(smallestNumber(new int[] {-1, -2, -3, 5, 6, 9, 0})); 7 | 8 | } 9 | 10 | public static int smallestNumber(int[] arr) { 11 | int smallest = Integer.MAX_VALUE; 12 | for(int number : arr) { 13 | if(number < smallest) { 14 | smallest = number; 15 | } 16 | } 17 | return smallest; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/XORSum.java: -------------------------------------------------------------------------------- 1 | package datastructures.BITManipulation; 2 | 3 | public class XORSum { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(xorSum(new int[] {1, 2, 3})); 7 | 8 | } 9 | 10 | public static int xorSum(int[] arr) { 11 | int arrL = arr.length; 12 | int num = 0; 13 | 14 | for(int i = 0; i < arrL; i++) { 15 | num |= arr[i]; 16 | } 17 | 18 | return num * (int)Math.pow(2, arrL-1); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Math/CelsiusToFahrenheit.java: -------------------------------------------------------------------------------- 1 | package datastructures.Math; 2 | 3 | import java.util.Scanner; 4 | 5 | public class CelsiusToFahrenheit { 6 | 7 | public static void main(String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | int testCases = sc.nextInt(); 10 | while(testCases--> 0) { 11 | int number = sc.nextInt(); 12 | System.out.println(cToF(number)); 13 | } 14 | } 15 | 16 | public static double cToF(int C) { 17 | return (9*C + 160) / 5; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/ComputeXOR1ToN.java: -------------------------------------------------------------------------------- 1 | package datastructures.BITManipulation; 2 | 3 | public class ComputeXOR1ToN { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(computeXORFrom1ToN(12)); 7 | } 8 | 9 | public static int computeXORFrom1ToN(int num) { 10 | if(num % 4 == 0) { 11 | return num; 12 | } 13 | if(num % 4 == 1) { 14 | return 1; 15 | } 16 | if(num % 4 == 2) { 17 | return num + 1; 18 | } else { 19 | return 0; 20 | } 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/MissingNumber.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/articles/missing-number/ 3 | */ 4 | package leetcode; 5 | 6 | public class MissingNumber { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(missingNumber(new int[] {1, 2, 3})); 10 | } 11 | 12 | public static int missingNumber(int[] nums) { 13 | int expectedSum = nums.length*(nums.length + 1)/2; 14 | int actualSum = 0; 15 | for (int num : nums) actualSum += num; 16 | return expectedSum - actualSum; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /coding-problems/src/namasteDSA/LinearSearch.java: -------------------------------------------------------------------------------- 1 | package namasteDSA; 2 | 3 | public class LinearSearch { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(linearSearch(new int[] {1,2,3,0,9}, 5)); 7 | } 8 | 9 | /** 10 | * Time Complexity : O(N) 11 | * Space Complexity : O(1) 12 | * @param arr 13 | * @param n 14 | * @return 15 | */ 16 | public static int linearSearch(int[] arr, int n) { 17 | for(int i = 0; i < arr.length; i++) { 18 | if(arr[i] == n) { 19 | return i; 20 | } 21 | } 22 | return -1; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /coding-problems/src/algorithms/EuclideanAlgorithm.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://www.geeksforgeeks.org/java-program-for-basic-and-extended-euclidean-algorithms/ 3 | */ 4 | package algorithms; 5 | 6 | public class EuclideanAlgorithm { 7 | public static void main(String[] args) { 8 | System.out.println(gcd(60, 36)); 9 | } 10 | 11 | /** 12 | * This method will take O(log(min (a, b))) time 13 | * @param a 14 | * @param b 15 | * @return 16 | */ 17 | public static int gcd(int a, int b) { 18 | if (a == 0) 19 | return b; 20 | return gcd(b % a, a); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/MoveZeroes.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | public class MoveZeroes { 4 | 5 | public static void main(String[] args) { 6 | moveZeroes(new int[] {1,0,2,3,0}); 7 | 8 | } 9 | 10 | public static void moveZeroes(int[] nums) { 11 | int p1 = 0; 12 | for(int p2 = 0; p2 < nums.length; p2++) { 13 | if(nums[p2] != 0) { 14 | nums[p1] = nums[p2]; 15 | p1++; 16 | } 17 | } 18 | for(int p2 = p1; p2 < nums.length; p2++) { 19 | nums[p2] = 0; 20 | } 21 | 22 | for(Integer i : nums) { 23 | System.out.println(i); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Math/AbsoluteValue.java: -------------------------------------------------------------------------------- 1 | package datastructures.Math; 2 | 3 | import java.util.Scanner; 4 | 5 | public class AbsoluteValue { 6 | 7 | public static void main(String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | int testCases = sc.nextInt(); 10 | while(testCases--> 0) { 11 | int number = sc.nextInt(); 12 | System.out.println(absolute(number)); 13 | } 14 | } 15 | 16 | public static int absolute(int number) { 17 | if(number >= 0) { 18 | return number; 19 | } else { 20 | return number * -1; 21 | } 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/ValidPerfectSquare.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a positive integer num, write a function which returns True 3 | * if num is a perfect square else False. 4 | * 5 | * Note: Do not use any built-in library function such as sqrt. 6 | */ 7 | 8 | package codewars; 9 | 10 | public class ValidPerfectSquare { 11 | public static void main(String[] args) { 12 | System.out.println(isPerfectSquare(65984451)); 13 | } 14 | public static boolean isPerfectSquare(int num) { 15 | for(int i = 1;num > 0;i+=2) 16 | num -= i; 17 | return 0 == num; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/FlippingBits.java: -------------------------------------------------------------------------------- 1 | package datastructures.BITManipulation; 2 | 3 | public class FlippingBits { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(flippingBits(11)); 7 | } 8 | 9 | /** 10 | * Time Complexity : O(log N) 11 | * Space Complexity : O(1) 12 | * 13 | * @param num 14 | * @return 15 | */ 16 | public static int flippingBits(int num) { 17 | int totalBits = (int)(Math.log(num) / Math.log(2)); 18 | int M = 0; 19 | M = 1 << totalBits; 20 | M |= M - 1; 21 | 22 | return M ^ num; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/SmallestValueOfAnArray.java: -------------------------------------------------------------------------------- 1 | package codewars; 2 | 3 | public class SmallestValueOfAnArray 4 | { 5 | public static int findSmallest( final int[] numbers, final String toReturn ) 6 | { 7 | //TODO: Add solution here 8 | int smallestValue = numbers[0]; 9 | int index = 0; 10 | for(int i = 1; i < numbers.length; i++) 11 | { 12 | if(numbers[i] < smallestValue) 13 | { 14 | smallestValue = numbers[i]; 15 | index = i; 16 | } 17 | } 18 | if(toReturn.equals("index")) 19 | return index; 20 | else 21 | return smallestValue; 22 | } 23 | } -------------------------------------------------------------------------------- /coding-problems/src/hackerearth/FindProduct.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/find-product/ 3 | */ 4 | package hackerearth; 5 | 6 | import java.util.Scanner; 7 | 8 | public class FindProduct { 9 | 10 | public static void main(String[] args) { 11 | Scanner s = new Scanner(System.in); 12 | int N = s.nextInt(); 13 | long answer = 1; 14 | for(int i = 0; i < N; i++){ 15 | answer = (answer*s.nextLong()) % 1000000007; 16 | } 17 | System.out.println(answer); 18 | s.close(); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BinaryHeap/MinHeap.java: -------------------------------------------------------------------------------- 1 | package datastructures.BinaryHeap; 2 | 3 | public class MinHeap { 4 | int [] arr; 5 | int size; 6 | int capacity; 7 | 8 | public MinHeap(int c) { 9 | this.arr = new int[c]; 10 | this.size = 0; 11 | this.capacity = c; 12 | } 13 | 14 | int[] initialize(int c) { 15 | for(int i = 0;i < c; i++) { 16 | this.arr[i] = 10+i; 17 | } 18 | return this.arr; 19 | } 20 | 21 | int left(int i) { 22 | return this.arr[2*i + 1]; 23 | } 24 | int right(int i) { 25 | return this.arr[2*i + 2]; 26 | } 27 | int parent(int i) { 28 | return this.arr[(i - 1) / 2]; 29 | } 30 | } 31 | 32 | 33 | -------------------------------------------------------------------------------- /coding-problems/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.8 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=1.8 12 | -------------------------------------------------------------------------------- /coding-problems/src/hackerearth/LifeTheUniverseAndEverything.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/life-the-universe-and-everything/ 3 | */ 4 | package hackerearth; 5 | 6 | import java.util.*; 7 | 8 | public class LifeTheUniverseAndEverything { 9 | 10 | public static void main(String[] args) { 11 | Scanner s = new Scanner(System.in); 12 | while(true){ 13 | int number = s.nextInt(); 14 | if(number == 42){ 15 | break; 16 | } 17 | System.out.println(number); 18 | } 19 | s.close(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/HIndexPartTwo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * This is a follow up problem of H Index Part I 3 | */ 4 | package leetcode; 5 | 6 | public class HIndexPartTwo { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(hIndex(new int[] {0,1,2,5,6})); 10 | } 11 | 12 | public static int hIndex(int[] arr) { 13 | int n = arr.length; 14 | int mid, left = 0, right = n - 1; 15 | while (left <= right) { 16 | mid = left + (right - left) / 2; 17 | if (arr[mid] == n - mid) 18 | return n - mid; 19 | else if (arr[mid] < n - mid) 20 | left = mid + 1; 21 | else 22 | right = mid - 1; 23 | } 24 | return n - left; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /coding-problems/src/hackerearth/ASCIIValue.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://www.hackerearth.com/practice/algorithms/string-algorithm/z-algorithm/practice-problems/algorithm/ascii-value/ 3 | */ 4 | package hackerearth; 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.io.InputStreamReader; 9 | 10 | public class ASCIIValue { 11 | 12 | public static void main(String[] args) throws IOException { 13 | //BufferedReader 14 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 15 | String name = br.readLine(); 16 | char character = name.charAt(0); // This gives the character 'a' 17 | System.out.println((int) character); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /coding-problems/src/company/nearbuy/MaximumDifference.java: -------------------------------------------------------------------------------- 1 | package company.nearbuy; 2 | 3 | public class MaximumDifference { 4 | 5 | public static void main(String[] args) { 6 | int[] inputArr = new int[] {1, 2, 90, 10, 110}; 7 | int arrLen = inputArr.length; 8 | int maxDiffInArr = inputArr[1] - inputArr[0]; 9 | int minArrEle = inputArr[0]; 10 | for(int i = 1; i < arrLen; i++) { 11 | if(inputArr[i] - minArrEle > maxDiffInArr) { 12 | maxDiffInArr = inputArr[i] - minArrEle; 13 | } 14 | if(inputArr[i] < minArrEle) { 15 | minArrEle = inputArr[i]; 16 | } 17 | } 18 | if(maxDiffInArr <= 0) { 19 | System.out.println(-1); 20 | }else { 21 | System.out.println(maxDiffInArr); 22 | } 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/FindThePosition.java: -------------------------------------------------------------------------------- 1 | /** 2 | * When provided with a letter, return its position in the alphabet. 3 | * 4 | * Input :: "a" 5 | * 6 | * Ouput :: "Position of alphabet: 1" 7 | * 8 | */ 9 | 10 | package codewars; 11 | 12 | public class FindThePosition { 13 | public static String position(char alphabet) { 14 | String alphabetString = "abcdefghijklmnopqrstuvwxyz"; 15 | int position = 0; 16 | for (int i = 0; i < alphabetString.length(); i++) { 17 | if (alphabet == alphabetString.charAt(i)) { 18 | position = i + 1; 19 | } 20 | } 21 | return "Position of alphabet: " + position; 22 | } 23 | 24 | public static void main(String[] args) { 25 | System.out.println(position('p')); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/SquareDigit.java: -------------------------------------------------------------------------------- 1 | /** 2 | * you are asked to square every digit of a number. 3 | * 4 | * For example, if we run 9119 through the function, 811181 will come out, 5 | * because 92 is 81 and 12 is 1. 6 | * 7 | * Note: The function accepts an integer and returns an integer 8 | * 9 | */ 10 | 11 | package codewars; 12 | 13 | public class SquareDigit { 14 | 15 | public static void main(String[] args) { 16 | System.out.println(squareDigits(34)); 17 | } 18 | 19 | public static int squareDigits(int n) { 20 | int remainder = 0; 21 | String s = ""; 22 | while (n != 0) { 23 | remainder = n % 10; 24 | n /= 10; 25 | s = remainder * remainder + s; 26 | } 27 | return Integer.valueOf(s); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/DeltaBits.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a function convertBits to determine the number of bits required to convert 3 | * positive integer A to positive integer B. 4 | * 5 | * For example, you can change 31 to 14 by flipping the 4th and 0th bit: 6 | * 7 | * 31 0 0 0 1 1 1 1 1 8 | * 14 0 0 0 0 1 1 1 0 9 | * --- --------------- 10 | * bit 7 6 5 4 3 2 1 0 11 | * Thus 31 and 14 should return 2. 12 | * 13 | */ 14 | 15 | package codewars; 16 | 17 | public class DeltaBits { 18 | 19 | public static void main(String[] args) { 20 | System.out.println(convertBits(1, 2)); 21 | } 22 | 23 | public static int convertBits(int a, int b) { 24 | int bitwiseExclusive = a ^ b; 25 | return Integer.bitCount(bitwiseExclusive); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /coding-problems/src/algorithms/NaivePatternMatchingAlgorithm.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | public class NaivePatternMatchingAlgorithm { 4 | 5 | public static void main(String[] args) { 6 | String text = "ABCABCD"; 7 | String pattern = "ABCE"; 8 | patternSearch(text, pattern); 9 | } 10 | 11 | public static void patternSearch(String text, String pattern) { 12 | int textLength = text.length(); 13 | int patternLength = pattern.length(); 14 | for(int i = 0; i <= (textLength-patternLength); i++) { 15 | int j; 16 | for(j = 0; j < patternLength; j++) { 17 | if(text.charAt(i+j) != pattern.charAt(j)) { 18 | break; 19 | } 20 | } 21 | if(j == patternLength) { 22 | System.out.println("Found index is : " + i); 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Array/SumAndAverage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://practice.geeksforgeeks.org/problems/java-arrays-set-1/0 3 | */ 4 | package datastructures.Array; 5 | 6 | import java.util.Scanner; 7 | 8 | public class SumAndAverage { 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int noOfTests = in.nextInt(); 13 | for (int i = 0; i < noOfTests; i++) { 14 | int n = in.nextInt(); 15 | int sum = 0; 16 | int arr[] = new int[n]; 17 | for (int j = 0; j < n; j++) { 18 | arr[j] = in.nextInt(); 19 | sum += arr[j]; 20 | } 21 | float avg = (float)sum/n; 22 | System.out.print(sum + " "); 23 | System.out.printf("%.2f", avg); 24 | System.out.println(); 25 | } 26 | in.close(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/SquashTheBugs.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Simple challenge - eliminate all bugs from the supplied code so that the code runs and outputs the expected value. 3 | * Output should be the length of the longest word, as a number. 4 | * 5 | * There will only be one 'longest' word. 6 | * 7 | */ 8 | 9 | package codewars; 10 | 11 | public class SquashTheBugs { 12 | 13 | public static void main(String[] args) { 14 | System.out.println(findLongest("Hi, How are you ?")); 15 | } 16 | 17 | public static int findLongest(final String str) { 18 | String[] spl = str.split(" "); 19 | int longest = 0; 20 | for (int i = 0; i < spl.length; i++) { 21 | if (spl[i].length() > longest) { 22 | longest = spl[i].length(); 23 | } 24 | } 25 | return longest; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /coding-problems/src/company/nearbuy/UsernameDisparitySimpleLogic.java: -------------------------------------------------------------------------------- 1 | package company.nearbuy; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.InputStreamReader; 5 | 6 | public class UsernameDisparitySimpleLogic { 7 | public static void main(String[] args) throws Exception { 8 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 9 | int tests = Integer.parseInt(br.readLine()); 10 | while(tests-->0) { 11 | char[] charArray = br.readLine().toCharArray(); 12 | int value = 0; 13 | int len = charArray.length; 14 | for(int i = 0; i < len; i++) { 15 | for(int j = i; j < len; j++) { 16 | if(charArray[j - i] == charArray[j]) { 17 | value++; 18 | }else { 19 | break; 20 | } 21 | } 22 | } 23 | System.out.println(value); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Array/ArraySortedOrNot.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://practice.geeksforgeeks.org/problems/check-if-an-array-is-sorted/0 3 | */ 4 | package datastructures.Array; 5 | 6 | import java.util.Scanner; 7 | 8 | public class ArraySortedOrNot { 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int noOfTests = in.nextInt(); 13 | for(int i = 0; i < noOfTests; i++) { 14 | int sizeOfArray = in.nextInt(); 15 | int[] array = new int[sizeOfArray]; 16 | int flag = 1; 17 | for(int j = 0; j < sizeOfArray; j++) { 18 | array[j] = in.nextInt(); 19 | } 20 | 21 | for(int k = 0; k < sizeOfArray-1; k++) { 22 | if(!(array[k+1] >= array[k])) { 23 | flag = 0; 24 | break; 25 | } 26 | } 27 | System.out.println(flag); 28 | } 29 | in.close(); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/MaxConsecutiveOnes.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/max-consecutive-ones/description/ 3 | */ 4 | package leetcode; 5 | 6 | public class MaxConsecutiveOnes { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(findMaxConsecutiveOnes(new int[] {1,0,1,1,1,1,0,1})); 10 | } 11 | 12 | /** 13 | * Algorithm : One Pass 14 | * Time Complexity : O(N) 15 | * Space Complexity : O(1) 16 | * @param nums 17 | * @return 18 | */ 19 | public static int findMaxConsecutiveOnes(int[] nums) { 20 | int count = 0; 21 | int maxCount = 0; 22 | 23 | for(int i = 0; i < nums.length; i++) { 24 | if(nums[i] == 1) { 25 | count++; 26 | } else { 27 | maxCount = Math.max(maxCount, count); 28 | count = 0; 29 | } 30 | } 31 | 32 | return Math.max(maxCount, count); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/TrailingZeroes.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a program that will calculate the number of trailing zeros in a factorial of a given number. 3 | * 4 | * N! = 1 * 2 * 3 * ... * N 5 | * 6 | * Be careful 1000! has 2568 digits... 7 | * 8 | * For more info, see: http://mathworld.wolfram.com/Factorial.html 9 | * 10 | * Examples 11 | * zeros(6) = 1 12 | * # 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero 13 | * 14 | * zeros(12) = 2 15 | * # 12! = 479001600 --> 2 trailing zeros 16 | * 17 | */ 18 | 19 | package codewars; 20 | 21 | public class TrailingZeroes { 22 | 23 | public static void main(String[] args) { 24 | System.out.println(zeros(10)); 25 | } 26 | 27 | public static int zeros(int n) { 28 | int count = 0; 29 | for (int i = 5; n / i >= 1; i *= 5) { 30 | count += n / i; 31 | } 32 | return count; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /coding-problems/src/company/nearbuy/CountDuplicates.java: -------------------------------------------------------------------------------- 1 | package company.nearbuy; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class CountDuplicates { 7 | 8 | public static void main(String[] args) { 9 | Map numberToCountMap = new HashMap(); 10 | int[] inputArr = new int[] {1, 2, 1, 3, 4, 2, 1, 4, 3}; 11 | int arrLen = inputArr.length; 12 | int count = 0; 13 | for(int i = 0; i < arrLen; i++) { 14 | if(numberToCountMap.get(inputArr[i]) != null) { 15 | numberToCountMap.put(inputArr[i], numberToCountMap.get(inputArr[i]) + 1); 16 | }else { 17 | numberToCountMap.put(inputArr[i], 1); 18 | } 19 | } 20 | for(Map.Entry entry : numberToCountMap.entrySet()) { 21 | if(entry.getValue() > 1) { 22 | count++; 23 | } 24 | } 25 | System.out.println(count); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Hashing/UnionArray.java: -------------------------------------------------------------------------------- 1 | package datastructures.Hashing; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class UnionArray { 7 | 8 | public static void main(String[] args) { 9 | int[] arr1 = new int[] {15, 20, 5, 15}; 10 | int[] arr2 = new int[] {15, 15, 15, 5, 20, 10}; 11 | System.out.println(unionArr(arr1, arr2)); 12 | } 13 | 14 | /** 15 | * Time complexity : O(M+N) 16 | * Space Complexity : O(M+N) 17 | * 18 | * @param arr1 19 | * @param arr2 20 | * @return 21 | */ 22 | private static int unionArr(int[] arr1, int[] arr2) { 23 | Set set = new HashSet(); 24 | for(int i = 0; i < arr1.length; i++) { 25 | set.add(arr1[i]); 26 | } 27 | 28 | for(int j = 0; j < arr2.length; j++) { 29 | set.add(arr2[j]); 30 | } 31 | 32 | return set.size(); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /coding-problems/src/namasteDSA/SecondLargest.java: -------------------------------------------------------------------------------- 1 | package namasteDSA; 2 | 3 | public class SecondLargest { 4 | 5 | public static void main(String[] args) { 6 | int[] arr = {5, 6, 6}; 7 | System.out.println(secondLargest(arr)); 8 | } 9 | 10 | public static String secondLargest(int[] arr) { 11 | if(arr.length < 2) { 12 | return "Array should have at least two numbers"; 13 | } 14 | 15 | int firstLargest = Integer.MIN_VALUE; 16 | int secondLargest = Integer.MIN_VALUE; 17 | for(int number : arr) { 18 | if(number > firstLargest) { 19 | secondLargest = firstLargest; 20 | firstLargest = number; 21 | } else if (number > secondLargest && number != firstLargest) { 22 | secondLargest = number; 23 | } 24 | } 25 | 26 | return (secondLargest == Integer.MIN_VALUE) ? "No second largest found" : String.valueOf(secondLargest); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Array/PerfectArrays.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://practice.geeksforgeeks.org/problems/perfect-arrays/0 3 | */ 4 | package datastructures.Array; 5 | 6 | import java.util.Scanner; 7 | 8 | public class PerfectArrays { 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int noOfTests = in.nextInt(); 13 | for(int i = 0; i < noOfTests; i++) { 14 | int sizeOfArray = in.nextInt(); 15 | int[] array = new int[sizeOfArray]; 16 | int flag = 0; 17 | for(int j = 0; j < sizeOfArray; j++) { 18 | array[j] = in.nextInt(); 19 | } 20 | 21 | for(int k = 0; k < sizeOfArray; k++) { 22 | if(array[k] != array[sizeOfArray-k-1]) { 23 | flag = 1; 24 | break; 25 | } 26 | } 27 | 28 | System.out.println(flag == 1 ? "NOT PERFECT" : "PERFECT"); 29 | } 30 | in.close(); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/StringyString.java: -------------------------------------------------------------------------------- 1 | /** 2 | * write me a function stringy that takes a size and returns a string of alternating '1s' and '0s'. 3 | * 4 | * the string should start with a 1. 5 | * 6 | * a string with size 6 should return :'101010'. 7 | * 8 | * with size 4 should return : '1010'. 9 | * 10 | * with size 12 should return : '101010101010'. 11 | * 12 | * The size will always be positive and will only use whole numbers. 13 | * 14 | */ 15 | 16 | package codewars; 17 | 18 | public class StringyString { 19 | 20 | public static void main(String[] args) { 21 | System.out.println(stringy(12)); 22 | } 23 | 24 | public static String stringy(int size) { 25 | String number = "1"; 26 | for (int i = 1; i < size; i++) { 27 | if (i % 2 == 0) { 28 | number += "1"; 29 | } else { 30 | number += "0"; 31 | } 32 | } 33 | return number; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/SwapANumber.java: -------------------------------------------------------------------------------- 1 | package datastructures.BITManipulation; 2 | 3 | public class SwapANumber { 4 | 5 | public static void main(String[] args) { 6 | int a = 10, b = 5; 7 | System.out.println("a = " + a + ", b = " + b); 8 | swapANumberOne(a, b); 9 | swapANumberTwo(a, b); 10 | swapANumberThree(a, b); 11 | } 12 | 13 | public static void swapANumberOne(int a, int b) { 14 | a = a + b; 15 | b = a - b; 16 | a = a - b; 17 | 18 | System.out.println("a = " + a + ", b = " + b); 19 | } 20 | 21 | public static void swapANumberTwo(int a, int b) { 22 | a = a * b; 23 | b = a / b; 24 | a = a / b; 25 | 26 | System.out.println("a = " + a + ", b = " + b); 27 | } 28 | 29 | public static void swapANumberThree(int a, int b) { 30 | a = a ^ b; 31 | b = a ^ b; 32 | a = a ^ b; 33 | 34 | System.out.println("a = " + a + ", b = " + b); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /coding-problems/src/hackerearth/Factorial.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/find-factorial/ 3 | */ 4 | package hackerearth; 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.io.InputStreamReader; 9 | 10 | public class Factorial { 11 | 12 | public static void main(String[] args) throws NumberFormatException, IOException { 13 | //BufferedReader 14 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 15 | int N = Integer.parseInt(br.readLine()); // Reading input from STDIN 16 | System.out.print(factorial(N)); 17 | } 18 | 19 | public static int factorial(int N){ 20 | if(N == 0 || N == 1){ 21 | return 1; 22 | }else{ 23 | return N * factorial(N-1); 24 | } 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/ContainsDuplicate.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/articles/contains-duplicate/ 3 | */ 4 | package leetcode; 5 | 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | 9 | public class ContainsDuplicate { 10 | 11 | public static void main(String[] args) { 12 | int[] nums = new int[] { 2, 14, 18, 22, 22 }; 13 | System.out.println(containsDuplicate(nums)); 14 | } 15 | 16 | public static boolean containsDuplicate(int[] nums) { 17 | Map map = new HashMap(); 18 | for (int i = 0; i < nums.length; i++) { 19 | if (map.containsKey(nums[i])) { 20 | map.put(nums[i], map.get(nums[i]) + 1); 21 | } else { 22 | map.put(nums[i], 1); 23 | } 24 | } 25 | 26 | for(Map.Entry entry : map.entrySet()) { 27 | if(entry.getValue() > 1) { 28 | return true; 29 | } 30 | } 31 | 32 | return false; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/String/Problem6.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given two strings, check if they are rotations of each other 3 | * (rotations can be cloclwise or counter clockwise) 4 | * Example : str1 = "ABCD", str2 = "CDAB" 5 | * Output : true 6 | * 7 | * Example : str1 = "ABAA", str2 = "AAAB" 8 | * Output : true 9 | * 10 | * Example : str1 = "ABAB", str2 = "ABBA" 11 | * Output : false 12 | */ 13 | package datastructures.String; 14 | 15 | public class Problem6 { 16 | 17 | public static void main(String[] args) { 18 | String str1 = "ABCD"; 19 | String str2 = "CDAC"; 20 | System.out.println(areRotations(str1, str2)); 21 | } 22 | 23 | public static boolean areRotations(String str1, String str2) { 24 | if(str1.length() != str2.length()) { 25 | return false; 26 | } 27 | 28 | str1 = str1+str1; 29 | if(str1.indexOf(str2) > 0) { 30 | return true; 31 | } else { 32 | return false; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/MonkeyCounter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * You take your son to the forest to see the monkeys. 3 | * You know that there are a certain number there (n), 4 | * but your son is too young to just appreciate the full number, 5 | * he has to start counting them from 1. 6 | * 7 | * As a good parent, you will sit and count with him. Given the number (n), 8 | * populate an array with all numbers up to and including that number, but excluding zero. 9 | * 10 | * For example, if n = 10: 11 | * 12 | * return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 13 | * 14 | */ 15 | 16 | package codewars; 17 | 18 | public class MonkeyCounter { 19 | public static int[] monkeyCount(final int n) { 20 | int[] monkeyCountArray = new int[n]; 21 | for (int i = 0; i < n; i++) { 22 | monkeyCountArray[i] = i + 1; 23 | } 24 | return monkeyCountArray; 25 | } 26 | 27 | public static void main(String[] args) { 28 | System.out.println(monkeyCount(12)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Array/ValueEqualToIndexValue.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://practice.geeksforgeeks.org/problems/value-equal-to-index-value/0 3 | */ 4 | package datastructures.Array; 5 | 6 | import java.util.Scanner; 7 | 8 | public class ValueEqualToIndexValue { 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int noOfTests = in.nextInt(); 13 | for(int i = 0; i < noOfTests; i++) { 14 | int sizeOfArray = in.nextInt(); 15 | int[] array = new int[sizeOfArray]; 16 | int count = 0; 17 | for(int j = 0; j < sizeOfArray; j++) { 18 | array[j] = in.nextInt(); 19 | } 20 | 21 | for(int k = 0; k < sizeOfArray; k++) { 22 | if(array[k] == k+1) { 23 | System.out.print(k+1 + " "); 24 | } else { 25 | count++; 26 | } 27 | } 28 | if(count == sizeOfArray) { 29 | System.out.print("Not Found"); 30 | } 31 | System.out.println(); 32 | } 33 | in.close(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Hashing/IntersectionArray.java: -------------------------------------------------------------------------------- 1 | package datastructures.Hashing; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class IntersectionArray { 7 | 8 | public static void main(String[] args) { 9 | int[] arr1 = new int[] {10, 15, 20, 15, 30, 30, 5}; 10 | int[] arr2 = new int[] {30, 5, 30, 80}; 11 | System.out.println(optimizedSoln(arr1, arr2)); 12 | 13 | } 14 | 15 | /** 16 | * Time Complexity : O(N) 17 | * Space Complexity : O(N) 18 | * 19 | * @param arr1 20 | * @param arr2 21 | * @return 22 | */ 23 | private static int optimizedSoln(int[] arr1, int[] arr2) { 24 | Set set = new HashSet(); 25 | for(int i = 0; i < arr1.length; i++) { 26 | set.add(arr1[i]); 27 | } 28 | 29 | int count = 0; 30 | for(int j = 0; j < arr2.length; j++) { 31 | if(set.contains(arr2[j])) { 32 | count++; 33 | set.remove(arr2[j]); 34 | } 35 | } 36 | return count; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /coding-problems/src/hackerearth/TrickWithTheCards.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://www.hackerearth.com/problem/algorithm/trick-with-the-cards/ 3 | */ 4 | package hackerearth; 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.io.InputStreamReader; 9 | 10 | public class TrickWithTheCards { 11 | 12 | public static void main(String[] args) throws NumberFormatException, IOException { 13 | //BufferedReader 14 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 15 | int tc = Integer.parseInt(br.readLine()); 16 | while(tc-->0){ 17 | long N = Long.parseLong(br.readLine()); 18 | if(N <= 0L){ 19 | System.out.println(0); 20 | }else if(N <= 2L){ 21 | System.out.println(1); 22 | }else if(N%3L == 0){ 23 | System.out.println(N/3L); 24 | }else{ 25 | System.out.println(N); 26 | } 27 | } 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/MergeSortedArray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/merge-sorted-array/ 3 | */ 4 | package leetcode; 5 | 6 | public class MergeSortedArray { 7 | 8 | public static void main(String[] args) { 9 | merge(new int[] {1,2,3,0,0,0}, 3, new int[] {2,5,6}, 3); 10 | } 11 | 12 | /** 13 | * Algorithm : 3 Pointers Approach (Start from the end) 14 | * Time Complexity : O(m+n) 15 | * Space Complexity : O(1) 16 | * @param nums1 17 | * @param m 18 | * @param nums2 19 | * @param n 20 | */ 21 | public static void merge(int[] nums1, int m, int[] nums2, int n) { 22 | int p1 = m-1; 23 | int p2 = n-1; 24 | 25 | for(int p = m + n - 1; p >= 0; p--) { 26 | if(p2 < 0) { 27 | break; 28 | } 29 | 30 | if(p1 >= 0 && nums1[p1] > nums2[p2]) { 31 | nums1[p] = nums1[p1]; 32 | p1--; 33 | } else { 34 | nums1[p] = nums2[p2]; 35 | p2--; 36 | } 37 | } 38 | 39 | for(Integer i : nums1) { 40 | System.out.println(i); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Array/NumberOfNumbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://practice.geeksforgeeks.org/problems/find-number-of-numbers/1 3 | */ 4 | package datastructures.Array; 5 | 6 | import java.util.Scanner; 7 | 8 | public class NumberOfNumbers { 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int noOfTests = in.nextInt(); 13 | while (noOfTests --> 0) { 14 | int arraySize = in.nextInt(); 15 | int[] array = new int[arraySize]; 16 | for(int i = 0; i < arraySize; i++) { 17 | array[i] = in.nextInt(); 18 | } 19 | int k = in.nextInt(); 20 | System.out.println(num(array, arraySize, k)); 21 | } 22 | in.close(); 23 | } 24 | 25 | public static int num (int[] array, int arraySize, int k) { 26 | int count = 0; 27 | for(int i = 0; i < arraySize; i++) { 28 | while(array[i] != 0) { 29 | int rem = array[i]%10; 30 | array[i] = array[i]/10; 31 | if(rem == k) { 32 | count++; 33 | } 34 | } 35 | } 36 | return count; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/EqualSumAndXOR.java: -------------------------------------------------------------------------------- 1 | package datastructures.BITManipulation; 2 | 3 | public class EqualSumAndXOR { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(findCount(7)); 7 | System.out.println(findCountEfficient(7)); 8 | 9 | } 10 | 11 | /** 12 | * Naive Approach, Time Complexity : O(N) 13 | * 14 | * @param num 15 | * @return 16 | */ 17 | public static int findCount(int num) { 18 | int count = 0; 19 | for(int i = 0; i <= num; i++) { 20 | if((num + i) == (num ^ i)) { 21 | count++; 22 | } 23 | } 24 | 25 | return count; 26 | } 27 | 28 | /** 29 | * Efficient Approach, Time Complexity : O(log N) 30 | * 31 | * @param num 32 | * @return 33 | */ 34 | public static int findCountEfficient(int num) { 35 | int countUnsetBits = 0; 36 | while (num > 0) { 37 | if((num & 1) == 0) { 38 | countUnsetBits++; 39 | } 40 | num >>= 1; 41 | } 42 | // Return 2 ^ countUnsetBits 43 | return 1 << countUnsetBits; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /coding-problems/src/company/HSBC/HelpJohn.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://www.hackerearth.com/challenges/hiring/HSBC-java-developer-hiring/algorithm/not-decided-1ca0c947/ 3 | */ 4 | package company.HSBC; 5 | 6 | import java.io.IOException; 7 | import java.util.Scanner; 8 | import java.util.TreeSet; 9 | 10 | public class HelpJohn { 11 | 12 | static TreeSet ts = new TreeSet(); 13 | public static void main(String[] args) throws IOException { 14 | 15 | Scanner sc = new Scanner(System.in); 16 | int N = sc.nextInt(); 17 | for(int i_arr=0; i_arr 0) { 23 | count += num & 1; 24 | num >>= 1; 25 | } 26 | 27 | return count; 28 | } 29 | 30 | /** 31 | * Time Complexity : O(log N) 32 | * Space Complexity : O(1) 33 | * 34 | * @param num 35 | * @return 36 | */ 37 | public static int countSetBitsBrianKernighanAlgo(int num) { 38 | int count = 0; 39 | while (num > 0) { 40 | num &= (num - 1); 41 | count++; 42 | } 43 | 44 | return count; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Math/QuadraticEquationRoots.java: -------------------------------------------------------------------------------- 1 | package datastructures.Math; 2 | 3 | import java.util.Scanner; 4 | 5 | public class QuadraticEquationRoots { 6 | 7 | public static void main(String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | int testCases = sc.nextInt(); 10 | while(testCases--> 0) { 11 | int a, b, c; 12 | a = sc.nextInt(); 13 | b = sc.nextInt(); 14 | c = sc.nextInt(); 15 | quadraticRoots(a, b, c); 16 | System.out.println(); 17 | } 18 | } 19 | 20 | public static void quadraticRoots(int a, int b, int c) { 21 | int root1 = 0, root2 = 0; 22 | int temp = (int)(Math.pow(b, 2) - 4*a*c); //value of b^2-4ac 23 | 24 | if(temp < 0)//if b^2-4ac is less then zero then roots are imaginary 25 | System.out.print("Imaginary"); 26 | else 27 | { 28 | root1 = (int)Math.floor((-1*b + Math.sqrt(temp))/(2 *a)); //root1 29 | root2 = (int)Math.floor((-1*b - Math.sqrt(temp))/(2 *a));//root2 30 | System.out.print(root1+" "+root2);//print the answer 31 | } 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Hashing/MyHash.java: -------------------------------------------------------------------------------- 1 | package datastructures.Hashing; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | 6 | public class MyHash { 7 | static int BUCKET; 8 | static ArrayList> table; 9 | 10 | private static void initialize(int b) { 11 | BUCKET = b; 12 | table = new ArrayList>(); 13 | for(int i = 0; i < b; i++) { 14 | table.add(new LinkedList()); 15 | } 16 | } 17 | 18 | private static void insert(int key) { 19 | int i = key % BUCKET; 20 | table.get(i).add(key); 21 | } 22 | 23 | private static void delete(int key) { 24 | int i = key % BUCKET; 25 | table.get(i).remove((Integer) key); 26 | } 27 | 28 | private static boolean search(int key) { 29 | int i = key % BUCKET; 30 | return table.get(i).contains(key); 31 | } 32 | 33 | public static void main(String[] args) { 34 | initialize(7); 35 | insert(70); 36 | insert(71); 37 | insert(56); 38 | insert(9); 39 | insert(72); 40 | 41 | System.out.println(table); 42 | 43 | System.out.println(search(57)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /coding-problems/src/hackerearth/IntelligentGirl.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://www.hackerearth.com/practice/algorithms/dynamic-programming/introduction-to-dynamic-programming-1/practice-problems/algorithm/intelligent-girl-1/ 3 | */ 4 | package hackerearth; 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.io.InputStreamReader; 9 | 10 | public class IntelligentGirl { 11 | 12 | public static void main(String[] args) throws IOException { 13 | //BufferedReader 14 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 15 | String numberString = br.readLine(); 16 | int lenStr = numberString.length(); 17 | int[] outArr = new int[lenStr+1]; 18 | for(int i = lenStr - 1, j = lenStr; i >= 0 && j > 0; i--, j--){ 19 | if(numberString.charAt(i) % 2 == 0){ 20 | outArr[i] = outArr[j] + 1; 21 | }else{ 22 | outArr[i] = outArr[j]; 23 | } 24 | } 25 | for(int i = 0; i < lenStr; i++){ 26 | System.out.print(outArr[i] + " "); 27 | } 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/NumberFun.java: -------------------------------------------------------------------------------- 1 | /** 2 | * You might know some pretty large perfect squares. But what about the NEXT one? 3 | * 4 | * Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer. 5 | * 6 | * If the parameter is itself not a perfect square, than -1 should be returned. You may assume the parameter is positive. 7 | * 8 | * Examples: 9 | * 10 | * findNextSquare(121) --> returns 144 11 | * findNextSquare(625) --> returns 676 12 | * findNextSquare(114) --> returns -1 since 114 is not a perfect 13 | * 14 | */ 15 | 16 | package codewars; 17 | 18 | public class NumberFun { 19 | 20 | public static void main(String[] args) { 21 | System.out.println(findNextSquare(144)); 22 | } 23 | 24 | public static long findNextSquare(long sq) { 25 | int num; 26 | if (Math.round(Math.sqrt(sq)) == Math.sqrt(sq)) { 27 | num = (int) Math.sqrt(sq); 28 | num += 1; 29 | return (long) Math.pow(num, 2); 30 | } else 31 | return -1; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /coding-problems/src/hackerearth/PalindromicString.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/palindrome-check-2/ 3 | */ 4 | package hackerearth; 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.io.InputStreamReader; 9 | 10 | public class PalindromicString { 11 | 12 | public static void main(String[] args) throws IOException { 13 | //BufferedReader 14 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 15 | String name = br.readLine(); // Reading input from STDIN 16 | char[] nameToCharArray = name.toCharArray(); 17 | char[] resultantArray = new char[name.length()]; 18 | int j = 0; 19 | for(int i = nameToCharArray.length-1; i >= 0; i--){ 20 | resultantArray[j] = nameToCharArray[i]; 21 | j++; 22 | } 23 | if(name.equals(new String(resultantArray))){ 24 | System.out.println("YES"); 25 | }else{ 26 | System.out.println("NO"); 27 | } 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /coding-problems/src/hackerearth/PrimeNumber.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/prime-number-8/ 3 | */ 4 | package hackerearth; 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.io.InputStreamReader; 9 | 10 | public class PrimeNumber { 11 | 12 | public static void main(String[] args) throws NumberFormatException, IOException { 13 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 14 | int N = Integer.parseInt(br.readLine()); 15 | 16 | boolean prime[] = new boolean[N+1]; 17 | for(int i=0;i0){ 14 | int N = sc.nextInt(); 15 | int S = sc.nextInt(); 16 | int arr[] = new int[N]; 17 | for(int i=0;i 20-40 13 | * age = 5 => 4-5 14 | * age = 17 => 15-20 15 | * 16 | */ 17 | package codewars; 18 | 19 | public class AgeRangeCompatibilityEquation { 20 | public static String datingRange(int age) { 21 | long min = 0; 22 | long max = 0; 23 | if (age <= 14) { 24 | min = Math.round(Math.floor(age - 0.10 * age)); 25 | max = Math.round(Math.floor(age + 0.10 * age)); 26 | } else { 27 | min = Math.round(Math.floor(age / 2 + 7)); 28 | max = Math.round(Math.floor((age - 7) * 2)); 29 | } 30 | return min + "-" + max; 31 | } 32 | 33 | public static void main(String[] args) { 34 | System.out.println(datingRange(13)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /coding-problems/src/hackerrank/ReverseArray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://www.hackerrank.com/challenges/arrays-ds/problem 3 | */ 4 | package hackerrank; 5 | 6 | import java.io.IOException; 7 | import java.util.Scanner; 8 | 9 | public class ReverseArray { 10 | 11 | static int[] reverseArray(int[] a) { 12 | int[] reversedArray = new int[a.length]; 13 | for (int i = 0; i < a.length; i++) { 14 | reversedArray[i] = a[a.length - i - 1]; 15 | } 16 | return reversedArray; 17 | 18 | } 19 | 20 | private static final Scanner scanner = new Scanner(System.in); 21 | 22 | public static void main(String[] args) throws IOException { 23 | 24 | int arrCount = scanner.nextInt(); 25 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 26 | 27 | int[] arr = new int[arrCount]; 28 | 29 | String[] arrItems = scanner.nextLine().split(" "); 30 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 31 | 32 | for (int i = 0; i < arrCount; i++) { 33 | int arrItem = Integer.parseInt(arrItems[i]); 34 | arr[i] = arrItem; 35 | } 36 | 37 | int[] res = reverseArray(arr); 38 | 39 | for (int i = 0; i < res.length; i++) { 40 | System.out.print(res[i]+" "); 41 | } 42 | scanner.close(); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/Scramblies.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false. 3 | * 4 | * Notes: 5 | * 6 | * Only lower case letters will be used (a-z). No punctuation or digits will be included. 7 | * Performance needs to be considered 8 | * Examples 9 | * scramble('rkqodlw', 'world') ==> True 10 | * scramble('cedewaraaossoqqyt', 'codewars') ==> True 11 | * scramble('katas', 'steak') ==> False 12 | * 13 | */ 14 | 15 | package codewars; 16 | 17 | public class Scramblies { 18 | 19 | public static void main(String[] args) { 20 | System.out.println(scramble("katas", "steak")); 21 | } 22 | 23 | public static boolean scramble(String str1, String str2) { 24 | 25 | String s3 = ""; 26 | StringBuilder s = new StringBuilder(str1); 27 | StringBuilder s1 = new StringBuilder(str2); 28 | for (int i = 0; i < s1.length(); i++) { 29 | for (int j = 0; j < s.length(); j++) { 30 | if (s1.charAt(i) == s.charAt(j)) { 31 | s3 += s.charAt(j); 32 | s.deleteCharAt(j); 33 | break; 34 | } 35 | } 36 | } 37 | if (s3.equals(str2)) 38 | return true; 39 | return false; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/SpinWords.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a function that takes in a string of one or more words, 3 | * and returns the same string, but with all five or more letter words reversed 4 | * (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. 5 | * Spaces will be included only when more than one word is present. 6 | * 7 | * Examples: 8 | * 9 | * spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" 10 | * spinWords( "This is a test") => returns "This is a test" 11 | * spinWords( "This is another test" )=> returns "This is rehtona test" 12 | * 13 | */ 14 | 15 | package codewars; 16 | 17 | public class SpinWords { 18 | 19 | public static void main(String[] args) { 20 | System.out.println(spinWords("This is another test")); 21 | } 22 | 23 | public static String spinWords(String sentence) { 24 | String[] array = sentence.split(" "); 25 | for (int i = 0; i < array.length; i++) { 26 | if (array[i].length() >= 5) { 27 | StringBuffer sb = new StringBuffer(); 28 | sb.append(array[i]); 29 | sb.reverse(); 30 | array[i] = sb.toString(); 31 | } 32 | } 33 | sentence = String.join(" ", array); 34 | return sentence; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /coding-problems/src/algorithms/ReversalAlgorithm.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://www.youtube.com/watch?v=QOpU9-l5T7Y 3 | */ 4 | package algorithms; 5 | 6 | public class ReversalAlgorithm { 7 | 8 | public static void main(String[] args) { 9 | int[] array = new int[] {5, 8, 10, 12, 15, 11}; 10 | // rotate an array by 2 counter clockwise (anticlockwise) 11 | int rotateAnArrayBy = 2; 12 | 13 | leftRotate(array, array.length, rotateAnArrayBy); 14 | 15 | for(int i = 0; i < array.length; i++) { 16 | System.out.print(array[i]+" "); 17 | } 18 | } 19 | 20 | public static void leftRotate(int[] array, int arrayLength, int rotateAnArrayBy) { 21 | reverseAnArray(array, 0, rotateAnArrayBy-1); 22 | reverseAnArray(array, rotateAnArrayBy, arrayLength-1); 23 | reverseAnArray(array, 0, arrayLength-1); 24 | } 25 | 26 | public static void reverseAnArray(int[] array, int forwardPtr, int backwardPtr) { 27 | while(forwardPtr < backwardPtr) { 28 | swap(array, forwardPtr, backwardPtr); 29 | forwardPtr++; 30 | backwardPtr--; 31 | } 32 | } 33 | 34 | public static void swap(int[] array, int forwardPtr, int backwardPtr) { 35 | int temp = array[forwardPtr]; 36 | array[forwardPtr] = array[backwardPtr]; 37 | array[backwardPtr] = temp; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/DigitalRoot.java: -------------------------------------------------------------------------------- 1 | /** 2 | * A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers. 3 | * 4 | * Here's how it works (Ruby example given): 5 | * 6 | * digital_root(16) 7 | * => 1 + 6 8 | * => 7 9 | * 10 | * digital_root(942) 11 | * => 9 + 4 + 2 12 | * => 15 ... 13 | * => 1 + 5 14 | * => 6 15 | * 16 | * digital_root(132189) 17 | * => 1 + 3 + 2 + 1 + 8 + 9 18 | * => 24 ... 19 | * => 2 + 4 20 | * => 6 21 | * 22 | * digital_root(493193) 23 | * => 4 + 9 + 3 + 1 + 9 + 3 24 | * => 29 ... 25 | * => 2 + 9 26 | * => 11 ... 27 | * => 1 + 1 28 | * => 2 29 | * 30 | */ 31 | 32 | package codewars; 33 | 34 | public class DigitalRoot { 35 | 36 | public static void main(String[] args) { 37 | System.out.println(digitalRoot(12)); 38 | } 39 | 40 | public static int digitalRoot(int n) { 41 | int remainder = 0; 42 | int sum = 0; 43 | while (n > 0) { 44 | remainder = n % 10; 45 | n = n / 10; 46 | sum += remainder; 47 | } 48 | if (sum > 9) 49 | return digitalRoot(sum); 50 | else 51 | return sum; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/BuyAndSellStock.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ 4 | */ 5 | package leetcode; 6 | 7 | public class BuyAndSellStock { 8 | 9 | public static void main(String[] args) { 10 | System.out.println(maxProfit(new int[] {7,1,5,3,6,4})); 11 | } 12 | 13 | /** 14 | * Algorithm : One Pass Approach 15 | * The points of interest are the peaks and valleys in the given graph. 16 | * We need to find the largest price following each valley, which difference could be the max profit. 17 | * We can maintain two variables - minprice and maxprofit corresponding to the smallest valley and maximum profit 18 | * (maximum difference between selling price and minprice) obtained so far respectively. 19 | * @param prices 20 | * @return 21 | */ 22 | public static int maxProfit(int[] prices) { 23 | int min = Integer.MAX_VALUE; 24 | int maximumProfit = 0; 25 | for(int i = 0; i < prices.length; i++) { 26 | if(prices[i] < min) { 27 | min = prices[i]; 28 | } 29 | if(prices[i] - min > maximumProfit) { 30 | maximumProfit = prices[i] - min; 31 | } 32 | } 33 | return maximumProfit; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/ReversePolishNotationCalc.java: -------------------------------------------------------------------------------- 1 | package codewars; 2 | 3 | import java.util.Stack; 4 | 5 | public class ReversePolishNotationCalc 6 | { 7 | public static void main(String[] args) 8 | { 9 | // TODO Auto-generated method stub 10 | ReversePolishNotationCalc c=new ReversePolishNotationCalc(); 11 | System.out.println(c.evaluate("1 3 -")); 12 | } 13 | public double evaluate(String expr) 14 | { 15 | if(expr.isEmpty()) 16 | return 0.0; 17 | Stack digits= new Stack(); 18 | String[] list=expr.split(" "); 19 | for(int i=0;i=0; i--) { 28 | if(maxFromRight < array[i]) { 29 | maxFromRight = array[i]; 30 | System.out.print(maxFromRight + " "); 31 | } 32 | } 33 | } 34 | 35 | /** 36 | * time taken is O(n*n) 37 | * @param array 38 | */ 39 | private static void simplestApproach(int[] array) { 40 | for(int i = 0; i < array.length; i++) { 41 | int j; 42 | for(j = i+1; j < array.length; j++) { 43 | if(array[i] <= array[j]) { 44 | break; 45 | } 46 | } 47 | if(j == array.length) { 48 | System.out.print(array[i] + " "); 49 | } 50 | } 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/String/Problem4.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Lexicographic rank of given String 3 | * Example : STRING 4 | * Output : 598 5 | * 6 | * Given a string, find its rank among all its permutations sorted lexicographically. 7 | * For example, rank of "abc" is 1, rank of "acb" is 2, and rank of "cba" is 6 8 | * 9 | */ 10 | package datastructures.String; 11 | 12 | public class Problem4 { 13 | 14 | public static void main(String[] args) { 15 | String str = "string"; 16 | System.out.println(lexicographicRank(str)); 17 | } 18 | 19 | public static int lexicographicRank(String str) { 20 | int rank = 1; 21 | int strLength = str.length(); 22 | int mul = factorial(strLength); 23 | int count[] = new int[256]; 24 | for(int i = 0; i < strLength; i++) { 25 | count[str.charAt(i)]++; 26 | } 27 | 28 | for(int i = 1; i < 256; i++) { 29 | count[i] += count[i-1]; 30 | } 31 | 32 | for(int i = 0; i < strLength; i++) { 33 | mul /= (strLength-i); 34 | rank += count[str.charAt(i) - 1] * mul; 35 | for(int j = str.charAt(i); j < 256; j++) { 36 | count[j]--; 37 | } 38 | } 39 | 40 | return rank; 41 | } 42 | 43 | public static int factorial(int number) { 44 | return number <= 1 ? 1 : number * factorial(number - 1); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/String/Problem5.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a text and pattern String, find if permutation of the String exist 3 | * in the text 4 | * 5 | * Example : 6 | * text : geeksforgeeks 7 | * pattern : ekeg 8 | * Output : true 9 | * Example : 10 | * text : geeksforgeeks 11 | * pattern : gks 12 | * Output : false 13 | */ 14 | package datastructures.String; 15 | 16 | import java.util.Arrays; 17 | 18 | public class Problem5 { 19 | 20 | public static void main(String[] args) { 21 | String text = "geeksforgeeks"; 22 | String pattern = "eekg"; 23 | System.out.println(isPatternOrAnagramPatternFoundInText(text, pattern)); 24 | } 25 | 26 | public static boolean isPatternOrAnagramPatternFoundInText(String text, String pattren) { 27 | int countTxtW[] = new int[256]; 28 | int countPat[] = new int[256]; 29 | 30 | for(int i = 0; i < pattren.length(); i++) { 31 | countTxtW[text.charAt(i)]++; 32 | countPat[pattren.charAt(i)]++; 33 | } 34 | 35 | for(int i = pattren.length(); i < text.length(); i++) { 36 | if(Arrays.equals(countTxtW, countPat)) { 37 | return true; 38 | } 39 | countTxtW[text.charAt(i)]++; 40 | countTxtW[text.charAt(i - pattren.length())]--; 41 | } 42 | return false; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Hashing/CountDistinctElements.java: -------------------------------------------------------------------------------- 1 | package datastructures.Hashing; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | public class CountDistinctElements { 8 | 9 | public static void main(String[] args) { 10 | System.out.println(naiveSoln(new int[] {10, 20, 10, 30})); 11 | Integer[] arr = Arrays.stream(new int[] {10, 20, 10, 30}).boxed().toArray(Integer[] :: new); 12 | System.out.println(optimizedSoln(arr)); 13 | } 14 | 15 | /** 16 | * Time Complexity : O(N*N) 17 | * Space Complexity : O(1) 18 | * 19 | * @param arr 20 | * @return 21 | */ 22 | private static int naiveSoln(int[] arr) { 23 | int count = 0; 24 | for(int i = 0; i < arr.length; i++) { 25 | boolean flag = false; 26 | for(int j = 0; j < i; j++) { 27 | if(arr[i] == arr[j]) { 28 | flag = true; 29 | break; 30 | } 31 | } 32 | 33 | if(flag == false) { 34 | count++; 35 | } 36 | } 37 | 38 | return count; 39 | } 40 | 41 | /** 42 | * Time Complexity : O(N) 43 | * Space Complexity : O(N) 44 | * 45 | * @param arr 46 | * @return 47 | */ 48 | private static int optimizedSoln(Integer[] arr) { 49 | Set s = new HashSet(Arrays.asList(arr)); 50 | return s.size(); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Array/FascinatingNumber.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://practice.geeksforgeeks.org/problems/fascinating-number/0 3 | */ 4 | package datastructures.Array; 5 | 6 | import java.util.Scanner; 7 | 8 | public class FascinatingNumber { 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int noOfTests = in.nextInt(); 13 | int[] numbers = new int[noOfTests]; 14 | for(int i = 0; i < numbers.length; i++) { 15 | numbers[i] = in.nextInt(); 16 | if(numbers[i] < 100) { 17 | System.out.println("Number should be atleast three digits"); 18 | continue; 19 | } 20 | isNumberAFaccinatingNumber(numbers[i]); 21 | } 22 | in.close(); 23 | } 24 | 25 | static void isNumberAFaccinatingNumber(int number) { 26 | int numberMultiply2 = number*2; 27 | int numberMultiply3 = number*3; 28 | String concNumber = number+""+numberMultiply2+""+numberMultiply3; 29 | int number0 = Integer.parseInt(String.valueOf(concNumber.charAt(0))); 30 | for(int i = 1; i < concNumber.length(); i++) { 31 | number0 = number0*Integer.parseInt(String.valueOf(concNumber.charAt(i))); 32 | } 33 | 34 | if(number0 == 362880) { 35 | System.out.println("Fascinating"); 36 | } else { 37 | System.out.println("Not Fascinating"); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Array/GetPairsCount.java: -------------------------------------------------------------------------------- 1 | package datastructures.Array; 2 | 3 | import java.util.HashMap; 4 | 5 | public class GetPairsCount { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(getCount(new int[] {1, 5, 7, -1, 5}, 6)); 9 | } 10 | 11 | /** 12 | * Time Complexity : O(N) 13 | * 14 | * @param arr 15 | * @param sum 16 | * @return 17 | */ 18 | public static int getCount(int[] arr, int sum) { 19 | HashMap hm = new HashMap(); 20 | for(int i = 0; i < arr.length; i++) { 21 | if(!hm.containsKey(arr[i])) { 22 | hm.put(arr[i], 0); 23 | } 24 | hm.put(arr[i], hm.get(arr[i]) + 1); 25 | } 26 | 27 | int count = 0; 28 | 29 | // Iterate through each element and increment the 30 | // count (Important to see, that every pair will be countet twice) 31 | for(int i = 0; i < arr.length; i++) { 32 | if(hm.get(sum - arr[i]) != null) { 33 | count += hm.get(sum - arr[i]); 34 | } 35 | 36 | // If (arr[i], arr[i]) pair satisfies the condition, then 37 | // we need to ensure that the count is decreased by one 38 | // such that the pair (arr[i], arr[i]) will not considered 39 | if((sum - arr[i]) == arr[i]) { 40 | count--; 41 | } 42 | } 43 | 44 | return count/2; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /coding-problems/PendingSols/GyanMatrix/SubsetMaximization.txt: -------------------------------------------------------------------------------- 1 | Subset Maximization 2 | 3 | You are given an array A of length N. You need to find the maximum length of the subset of given array such 4 | that the frequency all the elements present in the subset are equal. 5 | 6 | Input Format 7 | 8 | The first line of input contains an integer, denoting the value of N. 9 | The second line of input contains N space-separated integers, denoting the elements of array A. 10 | Output Format 11 | 12 | Print the maximum length of the subset of the array A in which frequency of all the elements present in that subset is equal. 13 | 14 | Constraints 15 | 1 <= N <= 10^5 16 | 1 <= A[i] <= 10^5 17 | 18 | Sample Input 19 | 5 20 | 1 2 2 3 3 21 | Sample Output 22 | 4 23 | Explanation 24 | {2 ,2 ,3 ,3} is the required subset with maximum length of 4. 25 | 26 | Note: Your code should be able to convert the sample input into the sample output. However, this is not enough 27 | to pass the challenge, because the code will be run on multiple test cases. Therefore, your code must solve this problem statement. 28 | Time Limit: 1.0 sec(s) for each input file 29 | Memory Limit: 256 MB 30 | Source Limit: 1024 KB 31 | Marking Scheme: Marks are awarded if any testcase passes 32 | Allowed Languages: JavaScript(Rhino), JavaScript(Node.js), Python, Python 3, Java, Java 8 -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/Program10.java: -------------------------------------------------------------------------------- 1 | /** 2 | * ADOBE, INTEL, MICROSOFT, SAMSUNG, ORACLE 3 | * 4 | * Given a positive integer N. The task is to check if N is a power of 2. That is N is 2x for some x. 5 | * 6 | * Input: 7 | * The first line contains T denoting the number of test cases. Each test case contains a single positive integer N. 8 | * 9 | * Output: 10 | * Print "YES" if it is a power of 2 else "NO" (Without the double quotes). 11 | * 12 | * Constraints: 13 | * 1 <= T <= 100 14 | * 0 <= N <= 1018 15 | * 16 | * Example: 17 | * Input : 18 | * 2 19 | * 1 20 | * 98 21 | * 22 | * Output : 23 | * YES 24 | * NO 25 | * 26 | * Explanation: 27 | * Testcase 1: 1 is equal to 2 raised to 0 (20 == 1). 28 | * 29 | */ 30 | package datastructures.BITManipulation; 31 | 32 | import java.util.Scanner; 33 | 34 | public class Program10 { 35 | public static void main(String[] args) { 36 | Scanner in = new Scanner(System.in); 37 | try { 38 | long T = in.nextLong(); 39 | while(T --> 0) { 40 | long N = in.nextLong(); 41 | if(N > 1 && ((long)(N & (N-1)) == 0)) { 42 | System.out.println("YES"); 43 | } else { 44 | System.out.println("NO"); 45 | } 46 | } 47 | } finally { 48 | if(in != null) { 49 | in.close(); 50 | } 51 | } 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Array/GreaterOnRightSide.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://practice.geeksforgeeks.org/problems/greater-on-right-side/0 3 | */ 4 | package datastructures.Array; 5 | 6 | import java.util.Scanner; 7 | 8 | public class GreaterOnRightSide { 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int noOfTests = in.nextInt(); 13 | while(noOfTests --> 0) { 14 | int arraySize = in.nextInt(); 15 | int[] array = new int[arraySize]; 16 | for(int i = 0; i < arraySize; i++) { 17 | array[i] = in.nextInt(); 18 | } 19 | greaterOnRightSide(array, arraySize); 20 | printArray(array, arraySize); 21 | } 22 | in.close(); 23 | } 24 | 25 | public static void printArray(int[] array, int arraySize) { 26 | for(int i = 0; i < arraySize; i++) { 27 | System.out.print(array[i] + " "); 28 | } 29 | System.out.println(); 30 | } 31 | 32 | public static int[] greaterOnRightSide(int[] array, int arraySize) { 33 | int max = 0; 34 | for(int j = 0;j < arraySize-1; j++){ 35 | max = array[j+1]; 36 | for(int k = j+1; k < arraySize-1; k++){ 37 | if(array[k+1] > max){ 38 | max = array[k+1]; 39 | } 40 | } 41 | array[j] = max; 42 | } 43 | array[arraySize-1] = -1; 44 | return array; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/Program9.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given N in Gray code equivalent. Find its binary equivalent. 3 | * 4 | * Input: 5 | * The first line contains an integer T, number of test cases. For each test cases, 6 | * there is an integer N denoting the number in gray equivalent. 7 | * 8 | * Output: 9 | * For each test case, in a new line, the output is the decimal equivalent number N of binary form. 10 | * 11 | * Constraints: 12 | * 1 <= T <= 100 13 | * 0 <= n <= 108 14 | * 15 | * Example: 16 | * Input 17 | * 2 18 | * 4 19 | * 15 20 | * Output 21 | * 7 22 | * 10 23 | * 24 | * Explanation: 25 | * Testcase1. 4 is represented as 100 and its binary equivalent is 111 whose decimal equivalent is 7. 26 | * Testcase2. 15 is represented as 1111 and its binary equivalent is 1010 i.e. 10 in decimal. 27 | * 28 | */ 29 | package datastructures.BITManipulation; 30 | 31 | import java.util.Scanner; 32 | 33 | public class Program9 { 34 | public static void main(String[] args) { 35 | Scanner in = new Scanner(System.in); 36 | try { 37 | int T = in.nextInt(); 38 | while(T --> 0) { 39 | int N = in.nextInt(); 40 | int output = 0; 41 | for (; N != 0; N = N >> 1) 42 | output ^= N; 43 | System.out.println(output); 44 | } 45 | } finally { 46 | if(in != null) { 47 | in.close(); 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/DeodorantEvaporator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * This program tests the life of an evaporator containing a gas. 3 | * 4 | * We know the content of the evaporator (content in ml), the percentage of foam or gas lost every day (evap_per_day) 5 | * and the threshold (threshold) in percentage beyond which the evaporator is no longer useful. 6 | * All numbers are strictly positive. 7 | * 8 | * The program reports the nth day (as an integer) on which the evaporator will be out of use. 9 | * 10 | * Note : Content is in fact not necessary in the body of the function "evaporator", 11 | * you can use it or not use it, as you wish. 12 | * Some people might prefer to reason with content, some other with percentages only. 13 | * It's up to you but you must keep it as a parameter because the tests have it as an argument. 14 | * 15 | */ 16 | 17 | package codewars; 18 | 19 | public class DeodorantEvaporator { 20 | 21 | public static void main(String[] args) { 22 | System.out.println(evaporator(8.0, 4, 2.3)); 23 | } 24 | 25 | public static int evaporator(double content, double evap_per_day, double threshold) { 26 | double accurateContent = content; 27 | int counter = 0; 28 | 29 | while (accurateContent > (threshold / 100) * content) { 30 | accurateContent *= (1 - evap_per_day / 100); 31 | counter++; 32 | } 33 | 34 | return counter; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /coding-problems/PendingSols/VivitriCapital/Partial Digit Subsequence.txt: -------------------------------------------------------------------------------- 1 | Partial Digit Sequence 2 | You are given an array A of length N. The partial digit subsequence of an array A is a subsequence of integers in which each consecutive integers have at least 1 digit in common. You are required to find the length of longest partial digit subsequence from the given array. 3 | 4 | Input : 5 | 6 | The first line of input contains N, length of array A. 7 | The second line of input contains N space-separated integers representing elements of A. 8 | Output : 9 | 10 | Print an integer representing the maximum length of the longest partial digit subsequence of the given array A. 11 | Constraints : 12 | 1 <= N <= 10^5 13 | 1 <= A[i] <= 10^18 14 | 15 | 16 | Sample Input 17 | 2 18 | 12 23 19 | Sample Output 20 | 2 21 | Explanation 22 | The longest partial digit subsequence of the given array is [12, 23]. as 12 and 23 contain 2 as the common digit. 23 | 24 | Note: Your code should be able to convert the sample input into the sample output. However, this is not enough to pass the challenge, because the code will be run on multiple test cases. Therefore, your code must solve this problem statement. 25 | Time Limit: 1.0 sec(s) for each input file 26 | Memory Limit: 256 MB 27 | Source Limit: 1024 KB 28 | Marking Scheme: Marks are awarded if any testcase passes 29 | Allowed Languages: C++, C++14, C#, Go, Java, Java 8, Ruby -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Array/PlayWithAnArray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://practice.geeksforgeeks.org/problems/play-with-an-array/1 3 | */ 4 | package datastructures.Array; 5 | 6 | import java.util.Arrays; 7 | import java.util.Scanner; 8 | 9 | public class PlayWithAnArray { 10 | 11 | public static void main(String[] args) { 12 | Scanner sc = new Scanner(System.in); 13 | int t = sc.nextInt(); 14 | while (t-- > 0) { 15 | int n = sc.nextInt(); 16 | int[] a = new int[n]; 17 | for (int i = 0; i < n; i++) 18 | a[i] = sc.nextInt(); 19 | int[] b = formatArray(a, n); 20 | int flag = 1; 21 | if (b.length == a.length) { 22 | for (int i = 1; i < n; i += 2) 23 | if (b[i] < b[i - 1]) 24 | flag = 0; 25 | if (flag == 0) 26 | System.out.println("0"); 27 | else { 28 | Arrays.sort(a); 29 | Arrays.sort(b); 30 | for (int i = 0; i < n; i++) { 31 | if (a[i] != b[i]) 32 | flag = 0; 33 | } 34 | System.out.println(flag); 35 | } 36 | } else 37 | System.out.println("0"); 38 | } 39 | sc.close(); 40 | } 41 | 42 | public static int[] formatArray(int[] a, int n) { 43 | for (int i = 0; i < n; i++) { 44 | for (int j = 0; j < n - i - 1; j++) { 45 | if (a[j] > a[j + 1]) { 46 | int temp = a[j]; 47 | a[j] = a[j + 1]; 48 | a[j + 1] = temp; 49 | 50 | } 51 | } 52 | } 53 | return a; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/Program8.java: -------------------------------------------------------------------------------- 1 | /** 2 | * You are given a decimal number n. You need to find the gray code of the number n and conver it into decimal. 3 | * To see how it's done, refer here. 4 | * 5 | * Input: 6 | * The first line contains an integer T, the number of test cases. For each test case, there is an integer n denoting the number 7 | * 8 | * Output: 9 | * For each test case, the output is gray code equivalent of n. 10 | * 11 | * Constraints: 12 | * 1 <= T <= 100 13 | * 0 <= n <= 108 14 | * 15 | * Example: 16 | * Input 17 | * 2 18 | * 7 19 | * 10 20 | * Output 21 | * 4 22 | * 15 23 | * 24 | * Explanation: 25 | * Testcase1: 7 is represented as 111 in binary form. The gray code of 111 is 100, in the binary form whose decimal equivalent is 4. 26 | * 27 | * Testcase2: 10 is represented as 1010 in binary form. The gray code of 1010 is 1111, in the binary form whose decimal equivalent 28 | * is 15. 29 | * 30 | * 31 | */ 32 | package datastructures.BITManipulation; 33 | 34 | import java.util.Scanner; 35 | 36 | public class Program8 { 37 | public static void main(String[] args) { 38 | Scanner in = new Scanner(System.in); 39 | try { 40 | int T = in.nextInt(); 41 | while(T --> 0) { 42 | int N = in.nextInt(); 43 | System.out.println(N ^ (N >> 1)); 44 | } 45 | } finally { 46 | if(in != null) { 47 | in.close(); 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /coding-problems/src/namasteDSA/EvenOrOdd.java: -------------------------------------------------------------------------------- 1 | package namasteDSA; 2 | 3 | public class EvenOrOdd { 4 | 5 | public static void main(String[] args) { 6 | checkEvenOrOddA(12); 7 | } 8 | 9 | /** 10 | * Approach 1 : Using Modulo Operator 11 | * 12 | **/ 13 | public static void checkEvenOrOddA(int number) { 14 | if(number % 2 == 0) { 15 | System.out.println("Even Number"); 16 | } else { 17 | System.out.println("Odd Number"); 18 | } 19 | } 20 | 21 | 22 | /** 23 | * Approach 2 : A number is even or odd can be determined by examining it's LSB (least significant bit) 24 | * 25 | * Understanding the LSB: In binary representation, all even numbers have their LSB (the rightmost bit) as 0, 26 | * while all odd numbers have their LSB as 1. 27 | * 28 | * Bitwise AND with 1: Perform a bitwise AND operation between the number and 1. 29 | * If the number is even, its LSB is 0. Performing number & 1 will result in 0 & 1, which is 0. 30 | * If the number is odd, its LSB is 1. Performing number & 1 will result in 1 & 1, which is 1. 31 | * 32 | * Checking the result: 33 | * If the result of number & 1 is 0, the number is even. 34 | * If the result of number & 1 is 1, the number is odd. 35 | * @param number 36 | */ 37 | public static void checkEvenOrOddB (int number) { 38 | if((number & 1) == 0) { 39 | System.out.println("Even Number"); 40 | } else { 41 | System.out.println("Odd Number"); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Stack/CustomStackInArray.java: -------------------------------------------------------------------------------- 1 | package datastructures.Stack; 2 | 3 | public class CustomStackInArray { 4 | 5 | public static void main(String[] args) throws Exception { 6 | MyStack myStack = new MyStack(4); 7 | myStack.push(5); 8 | myStack.push(10); 9 | myStack.push(15); 10 | System.out.println(myStack.peek()); 11 | System.out.println(myStack.pop()); 12 | System.out.println(myStack.peek()); 13 | myStack.push(20); 14 | System.out.println(myStack.size()); 15 | } 16 | } 17 | 18 | class MyStack { 19 | int capacity; 20 | int top; 21 | int[] arr; 22 | 23 | public MyStack(int capacity) { 24 | this.capacity = capacity; 25 | this.top = -1; 26 | this.arr = new int[capacity]; 27 | } 28 | 29 | public void push(int element) throws Exception { 30 | if(capacity == (top + 1)) { 31 | throw new Exception("Stack Overflow"); 32 | } 33 | 34 | top += 1; 35 | arr[top] = element; 36 | } 37 | 38 | public int pop() throws Exception { 39 | if(top == -1) { 40 | throw new Exception("Stack Underflow"); 41 | } 42 | 43 | int result = arr[top]; 44 | top -= 1; 45 | return result; 46 | } 47 | 48 | public int peek() throws Exception { 49 | if(top == -1) { 50 | throw new Exception("Stack Underflow"); 51 | } 52 | 53 | return arr[top]; 54 | } 55 | 56 | public int size() { 57 | return top + 1; 58 | } 59 | 60 | public boolean isEmpty() { 61 | return (top == -1); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/AckermannFunction.java: -------------------------------------------------------------------------------- 1 | /** 2 | * The Ackermann function is a famous function that played a big role in computability theory 3 | * as the first exemple of a total computable function that is not primitive recursive. 4 | * 5 | * Since then the function has been a bit simplified but is still of good use. 6 | * Due to its definition in terms of extremely deep recursion it can be used as a benchmark of a 7 | * compiler's ability to optimize recursion. 8 | * 9 | * The goal of this kata is to code a function wich will be given two input, m and n, 10 | * and will return the Ackermann number A(m,n) defined by: 11 | * 12 | * A(m,n) = n+1 if m=0 13 | * A(m,n) = A(m-1,1) if m>0 , n=0 14 | * A(m,n) = A(m-1,A(m,n-1)) if m,n > 0 15 | * 16 | * m,n should be non-negative integers, the function should return null (Javascript), 17 | * None (Python), or nil (Ruby) for other type, non-integer and negative numbers. 18 | * 19 | */ 20 | 21 | package codewars; 22 | 23 | public class AckermannFunction { 24 | 25 | public static void main(String[] args) { 26 | System.out.println(ackermann(2, 5)); 27 | } 28 | 29 | public static int ackermann(int m, int n) { 30 | if (m < 0 || n < 0) return -1; 31 | if (m == 0) return n + 1; 32 | 33 | if (n == 0) return ackermann(m-1, 1); 34 | 35 | return ackermann(m-1, ackermann(m, n-1)); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/JadenCase.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Jaden Smith, the son of Will Smith, is the star of films such as The Karate Kid 3 | * (2010) and After Earth (2013). Jaden is also known for some of his philosophy that 4 | * he delivers via Twitter. When writing on Twitter, he is known for almost always 5 | * capitalizing every word. 6 | * 7 | * Your task is to convert strings to how they would be written by Jaden Smith. 8 | * The strings are actual quotes from Jaden Smith, but they are not capitalized 9 | * in the same way he originally typed them. 10 | * 11 | * Example: 12 | * 13 | * Not Jaden-Cased: "How can mirrors be real if our eyes aren't real" 14 | * Jaden-Cased: "How Can Mirrors Be Real If Our Eyes Aren't Real" 15 | * Note that the Java version expects a return value of null for an empty string or null. 16 | * 17 | */ 18 | 19 | package codewars; 20 | 21 | public class JadenCase { 22 | 23 | public static void main(String[] args) { 24 | System.out.println(toJadenCase("")); 25 | } 26 | 27 | public static String toJadenCase(String phrase) { 28 | try { 29 | String[] arr; 30 | if (phrase == null | phrase.isEmpty()) { 31 | return null; 32 | } else { 33 | arr = phrase.split(" "); 34 | for (int i = 0; i < arr.length; i++) 35 | arr[i] = arr[i].substring(0, 1).toUpperCase() + arr[i].substring(1); 36 | } 37 | return String.join(" ", arr); 38 | } catch (Exception e) { 39 | return null; 40 | } 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/PersistentBugger.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit. 3 | * 4 | * For example: 5 | * 6 | * persistence(39) == 3 // because 3*9 = 27, 2*7 = 14, 1*4=4 7 | * // and 4 has only one digit 8 | * 9 | * persistence(999) == 4 // because 9*9*9 = 729, 7*2*9 = 126, 10 | * // 1*2*6 = 12, and finally 1*2 = 2 11 | * 12 | * persistence(4) == 0 // because 4 is already a one-digit number 13 | * 14 | */ 15 | 16 | package codewars; 17 | 18 | public class PersistentBugger { 19 | 20 | public static void main(String[] args) { 21 | System.out.println(persistence(1234)); 22 | } 23 | 24 | public static int persistence(long n) { 25 | Long nextNumberToCheck = n; 26 | int counter = 0; 27 | 28 | while (nextNumberToCheck.toString().length() != 1) { 29 | nextNumberToCheck = multiplyDigitsFromLong(nextNumberToCheck); 30 | counter++; 31 | } 32 | 33 | return counter; 34 | } 35 | 36 | public static long multiplyDigitsFromLong(long number) { 37 | Long numberObject = number; 38 | long multiplication = 1; 39 | 40 | for (char characterDigit : numberObject.toString().toCharArray()) { 41 | multiplication *= Long.parseLong(String.valueOf(characterDigit)); 42 | } 43 | 44 | return multiplication; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/QuickCals.java: -------------------------------------------------------------------------------- 1 | /** 2 | * You may be familiar with the concept of combinations: for example, 3 | * if you take 5 cards from a 52 cards deck as you would playing poker, 4 | * you can have a certain number (2,598,960, would you say?) of different combinations. 5 | * 6 | * In mathematics the number of k combinations you can have taking from a set of n elements 7 | * is called the binomial coefficient of n and k, more popularly called n choose k. 8 | * 9 | * The formula to compute it is relatively simple: n choose k==n!/(k!*(n-k)!), 10 | * where ! of course denotes the factorial operator. 11 | * 12 | * You are now to create a choose function that computes the binomial coefficient, like this: 13 | * 14 | * choose(1,1)==1 15 | * choose(5,4)==5 16 | * choose(10,5)==252 17 | * choose(10,20)==0 18 | * choose(52,5)==2598960 19 | * 20 | * Be warned: a certain degree of optimization is expected, both to deal with larger numbers precision (and their rounding errors in languages like JS) and computing time. 21 | * 22 | */ 23 | package codewars; 24 | 25 | import java.math.BigInteger; 26 | public class QuickCals { 27 | 28 | public static void main(String[] args) { 29 | System.out.println(choose(100, 34)); 30 | } 31 | 32 | public static BigInteger choose(int n, int p) { 33 | if (p == 0) { 34 | return BigInteger.ONE; 35 | } 36 | return choose(n, p - 1).multiply(BigInteger.valueOf(n - p + 1)).divide(BigInteger.valueOf(p)); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/Program7.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a number N. The task is to find the length of the longest consecutive 1s in its binary representation. 3 | * 4 | * Input: 5 | * The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. 6 | * Each test case contains an integer N. 7 | * 8 | * Output: 9 | * For each test case, in a new line, print the length of the longest consecutive 1's in N's binary representation. 10 | * 11 | * Constraints: 12 | * 1 <= T < 100 13 | * 1 <= N <= 103 14 | * 15 | * Example: 16 | * Input: 17 | * 2 18 | * 14 19 | * 222 20 | * 21 | * Output: 22 | * 3 23 | * 4 24 | * 25 | * Explanation: 26 | * Testcase 1: Binary representation of 14 is 1110, in which 111 is the longest consecutive set bits and length is 3. 27 | * 28 | */ 29 | package datastructures.BITManipulation; 30 | 31 | import java.util.Scanner; 32 | 33 | public class Program7 { 34 | public static void main(String[] args) { 35 | Scanner in = new Scanner(System.in); 36 | try { 37 | int T = in.nextInt(); 38 | while(T --> 0) { 39 | int N = in.nextInt(); 40 | System.out.println(maxConsecutiveOnes(N)); 41 | } 42 | } finally { 43 | if(in != null) { 44 | in.close(); 45 | } 46 | } 47 | } 48 | 49 | public static int maxConsecutiveOnes(int num) { 50 | int count = 0; 51 | while(num != 0) { 52 | num = (num & (num << 1)); 53 | count++; 54 | } 55 | return count; 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /coding-problems/src/hackerearth/RoyAndProfilePicture.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/roy-and-profile-picture/description/ 3 | */ 4 | package hackerearth; 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.io.InputStreamReader; 9 | 10 | public class RoyAndProfilePicture { 11 | 12 | public static void main(String[] args) throws NumberFormatException, IOException { 13 | //BufferedReader 14 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 15 | int lengthOfSideOfSquare = Integer.parseInt(br.readLine()); 16 | int noOfPhotos = Integer.parseInt(br.readLine()); 17 | for(int i = 0; i < noOfPhotos; i++){ 18 | String[] dimensionOfPhotos = br.readLine().split(" "); 19 | messageToUser(dimensionOfPhotos, lengthOfSideOfSquare); 20 | } 21 | } 22 | 23 | public static void messageToUser(String[] dimensionOfPhotos, int lengthOfSideOfSquare){ 24 | int W = Integer.parseInt(dimensionOfPhotos[0]); 25 | int H = Integer.parseInt(dimensionOfPhotos[1]); 26 | if(W < lengthOfSideOfSquare || H < lengthOfSideOfSquare){ 27 | System.out.println("UPLOAD ANOTHER"); 28 | }else{ 29 | if(W==H){ 30 | System.out.println("ACCEPTED"); 31 | }else{ 32 | System.out.println("CROP IT"); 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/BeforeAfterPrimes.java: -------------------------------------------------------------------------------- 1 | /** 2 | * We need a function prime_bef_aft() that gives the largest prime below a certain given value n, 3 | * 4 | * befPrime or bef_prime (depending on the language), 5 | * 6 | * and the smallest prime larger than this value, 7 | * 8 | * aftPrime/aft_prime (depending on the language). 9 | * 10 | * The result should be output in a list like the following: 11 | * 12 | * primeBefAft == {befPrime, aftPrime} 13 | * If n is a prime number it will give two primes, n will not be included in the result. 14 | * 15 | * Let's see some cases: 16 | * 17 | * primeBefAft(100) --> {97, 101} 18 | * 19 | * primeBefAft(97) --> {89, 101} 20 | * 21 | * primeBefAft(101) --> {97, 103} 22 | * 23 | */ 24 | 25 | 26 | package codewars; 27 | 28 | public class BeforeAfterPrimes { 29 | 30 | public static long[] primeBefAft(long num) { 31 | long[] outputArray = new long[2]; 32 | 33 | for (long i = num - 1; i > 1; i--) { 34 | if (isPrime(i)) { 35 | outputArray[0] = i; 36 | break; 37 | } 38 | } 39 | for (long i = num + 1;; i++) { 40 | if (isPrime(i)) { 41 | outputArray[1] = i; 42 | break; 43 | } 44 | } 45 | 46 | return outputArray; 47 | } 48 | 49 | public static boolean isPrime(long num) { 50 | for (long i = 2; i < num; i++) { 51 | if (num % i == 0) 52 | return false; 53 | } 54 | return num != 1; 55 | } 56 | 57 | public static void main(String[] args) { 58 | for (int i = 0; i < primeBefAft(100).length; i++) { 59 | System.out.println(primeBefAft(100)[i]); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/Program11.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an unsigned integer N. The task is to swap all odd bits with even bits. For example, 3 | * if the given number is 23 (00010111), it should be converted to 43(00101011). Here, 4 | * every even position bit is swapped with adjacent bit on right side(even position bits are highlighted in binary 5 | * representation of 23), and every odd position bit is swapped with adjacent on left side. 6 | * 7 | * Input: 8 | * The first line of input contains T, denoting the number of testcases. Each testcase contains single line. 9 | * 10 | * Output: 11 | * For each testcase in new line, print the converted number. 12 | * 13 | * Constraints: 14 | * 1 ≤ T ≤ 100 15 | * 1 ≤ N ≤ 100 16 | * 17 | * Example: 18 | * Input: 19 | * 2 20 | * 23 21 | * 2 22 | * 23 | * Output: 24 | * 43 25 | * 1 26 | * 27 | * Explanation: 28 | * Testcase 1: BInary representation of the given number; 00010111 after swapping 00101011 29 | * 30 | */ 31 | package datastructures.BITManipulation; 32 | 33 | import java.util.Scanner; 34 | 35 | public class Program11 { 36 | 37 | public static void main(String[] args) { 38 | Scanner in = new Scanner(System.in); 39 | try { 40 | int T = in.nextInt(); 41 | while(T --> 0) { 42 | int N = in.nextInt(); 43 | int evenBits = N & 0xAAAA; 44 | int oddBits = N & 0x5555; 45 | evenBits >>= 1; 46 | oddBits <<= 1; 47 | System.out.println(evenBits | oddBits); 48 | } 49 | } finally { 50 | if(in != null) { 51 | in.close(); 52 | } 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/PowerOfTwo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/power-of-two/description/ 3 | */ 4 | package leetcode; 5 | 6 | public class PowerOfTwo { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(isPowerOfTwoA(1)); 10 | System.out.println(isPowerOfTwoA(16)); 11 | System.out.println(isPowerOfTwoA(3)); 12 | 13 | System.out.println(isPowerOfTwoB(1)); 14 | System.out.println(isPowerOfTwoB(16)); 15 | System.out.println(isPowerOfTwoB(3)); 16 | 17 | System.out.println(isPowerOfTwoC(1)); 18 | System.out.println(isPowerOfTwoC(16)); 19 | System.out.println(isPowerOfTwoC(3)); 20 | 21 | } 22 | 23 | /** 24 | * Approach : Recursion 25 | * Time Complexity : O(log n) 26 | * @param n 27 | * @return 28 | */ 29 | public static boolean isPowerOfTwoA(int n) { 30 | if(n == 1) { 31 | return true; 32 | } else if ((n % 2 != 0) || n < 1) { 33 | return false; 34 | } 35 | return isPowerOfTwoA(n/2); 36 | 37 | } 38 | 39 | /** 40 | * Approach : Bit Manipulation 41 | * Time Complexity : O(1) 42 | * Space Complexity : O(1) 43 | * @param n 44 | * @return 45 | */ 46 | public static boolean isPowerOfTwoB(int n) { 47 | if(n <= 0) { 48 | return false; 49 | } 50 | return (n & (-n)) == n; 51 | } 52 | 53 | /** 54 | * Approach : Bit Manipulation 55 | * Time Complexity : O(1) 56 | * Space Complexity : O(1) 57 | * @param n 58 | * @return 59 | */ 60 | public static boolean isPowerOfTwoC(int n) { 61 | if(n <= 0) { 62 | return false; 63 | } 64 | return (n & (n-1)) == 0; 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/ReverseString.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Leetcode - https://leetcode.com/problems/reverse-string/description 5 | * @author prash 6 | * 7 | */ 8 | public class ReverseString { 9 | 10 | public static void main(String[] args) { 11 | System.out.println(reverseStringA(new char[] {'h','e','l','l','o'})); 12 | System.out.println(reverseStringB(new char[] {'h','e','l','l','o'})); 13 | } 14 | 15 | /** 16 | * Two Pointer Approach 17 | * Time Complexity - O(N) 18 | * Space Complexity - O(1) 19 | * @param s 20 | * @return 21 | */ 22 | public static char[] reverseStringA(char[] s) { 23 | int charArrayLength = s.length; 24 | int j = charArrayLength - 1; 25 | for(int i = 0; i < charArrayLength; i++) { 26 | if (i >= j) { 27 | break; 28 | } else { 29 | char temp = s[i]; 30 | s[i] = s[j]; 31 | s[j] = temp; 32 | } 33 | j = j-1; 34 | } 35 | 36 | return s; 37 | } 38 | 39 | public static void helper(char[] s, int left, int right) { 40 | if (left >= right) { 41 | return; 42 | } 43 | char tmp = s[left]; 44 | s[left++] = s[right]; 45 | s[right--] = tmp; 46 | helper(s, left, right); 47 | } 48 | 49 | /** 50 | * Recursive Approach 51 | * Time Complexity - O(N) 52 | * Space Complexity - O(N) -> Auxiliary Space to tackle Recusrion stack calls 53 | * @param s 54 | * @return 55 | */ 56 | public static char[] reverseStringB(char[] s) { 57 | helper(s, 0, s.length-1); 58 | return s; 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/topIntQuests/SubarraySumK.java: -------------------------------------------------------------------------------- 1 | package leetcode.topIntQuests; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class SubarraySumK { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(naiveSoln(new int[] {3, 4, 7, 2, -3, 1, 4, 2}, 7)); 10 | System.out.println(optimizedSoln(new int[] {3, 4, 7, 2, -3, 1, 4, 2}, 7)); 11 | } 12 | 13 | /** 14 | * Time complexity : O(n*n) We need to consider every subarray possible. 15 | * Space complexity : O(1). Constant space is used. 16 | * 17 | * @param nums 18 | * @param k 19 | * @return 20 | */ 21 | public static int naiveSoln(int[] nums, int k) { 22 | int count = 0; 23 | for(int i = 0; i < nums.length; i++) { 24 | int sum = 0; 25 | for(int j = i; j < nums.length; j++) { 26 | sum += nums[j]; 27 | if(sum == k) { 28 | count++; 29 | } 30 | } 31 | } 32 | 33 | return count; 34 | } 35 | 36 | /** 37 | * Time complexity : O(n). The entire nums array is traversed only once. 38 | * 39 | * Space complexity : O(n). Hashmap map can contain upto n distinct entries in the worst case. 40 | * 41 | * @param nums 42 | * @param k 43 | * @return 44 | */ 45 | public static int optimizedSoln(int[] nums, int k) { 46 | Map map = new HashMap(); 47 | map.put(0, 1); 48 | int count = 0, sum = 0; 49 | for(int i = 0; i < nums.length; i++) { 50 | sum += nums[i]; 51 | if(map.containsKey(sum - k)) { 52 | count += map.get(sum - k); 53 | } 54 | map.put(sum, map.getOrDefault(sum, 0) + 1); 55 | } 56 | return count; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/AlternateSquareSum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a method alternate_sq_sum() (JS: alternateSqSum ) that takes an array of integers as input and finds the sum of squares of the elements at even positions (i.e., 2nd, 4th, etc.) plus the sum of the rest of the elements at odd position. 3 | * 4 | * NOTE: 5 | * The values at even position need to be squared. For a language with zero-based indices, this will occur at oddly-indexed locations. For instance, in Python, the values at indices 1, 3, 5, etc. should be squared because these are the second, fourth, and sixth positions in the list. 6 | * 7 | * For Example: 8 | * alternateSqSum(new int[] {11, 12, 13, 14, 15}) // should return 379 9 | * Explanation: 10 | * Elements at indices 0, 2, 4 are 11, 13, 15 and they are at odd positions as 11 is at position #1, 13 is at position #3 and 15 at #5. 11 | * 12 | * Elements at indices 1, 3 are 12 and 14 and they are at even position. So we need to add 11, 13, 15 as they are and square of 12 and 14 13 | * 14 | * --> 11 + 13 + 15 + 12^2 + 14^2 15 | * = 11 + 13 + 15 + 144 + 196 16 | * = 379 17 | * 18 | * For empty arrays, result should be 0 (zero) 19 | * 20 | */ 21 | 22 | package codewars; 23 | 24 | public class AlternateSquareSum { 25 | 26 | public static void main(String[] args) { 27 | System.out.println(alternateSqSum(new int[] {11, 12, 13, 14, 15})); 28 | } 29 | 30 | public static int alternateSqSum(int[] arr) { 31 | int sum = 0; 32 | for (int i = 0; i < arr.length; i++) { 33 | if (i % 2 != 0) 34 | sum = sum + arr[i] * arr[i]; 35 | else 36 | sum += arr[i]; 37 | } 38 | return sum; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/PlusOne.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a non-empty array of digits representing a non-negative integer, plus one to the integer. 3 | * 4 | * The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. 5 | * 6 | * You may assume the integer does not contain any leading zero, except the number 0 itself. 7 | * 8 | * Example 1: 9 | * 10 | * Input: [1,2,3] 11 | * Output: [1,2,4] 12 | * Explanation: The array represents the integer 123. 13 | * Example 2: 14 | * 15 | * Input: [4,3,2,1] 16 | * Output: [4,3,2,2] 17 | * Explanation: The array represents the integer 4321. 18 | * 19 | */ 20 | package leetcode; 21 | 22 | public class PlusOne { 23 | 24 | public static void main(String[] args) { 25 | int[] nums = new int[] {1, 2, 9}; 26 | int[] digits = plusOne(nums); 27 | for(int i = 0; i < digits.length; i++) { 28 | System.out.print(digits[i] + " "); 29 | } 30 | } 31 | public static int[] plusOne(int[] digits) { 32 | if(digits==null||digits.length==0) 33 | return new int[0]; 34 | 35 | int carry = 1; 36 | for(int i=digits.length-1; i>=0; i--){ 37 | int sum = digits[i]+carry; 38 | if(sum>=10){ 39 | carry=1; 40 | }else{ 41 | carry=0; 42 | } 43 | digits[i]=sum%10; 44 | } 45 | 46 | if(carry==1){ 47 | int[] result = new int[digits.length+1]; 48 | System.arraycopy(digits, 0, result, 1, digits.length); 49 | result[0]=1; 50 | return result; 51 | }else{ 52 | return digits; 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/CircularlySortedArray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a method, isCircleSorted(int[] A) (Java, JavaScript), or Array#circularly_sorted? (Ruby) that determines if A is circularly sorted. An Array is circularly sorted if the elements are sorted in ascending order, but displaced, or rotated, by any number of steps. 3 | * 4 | * For Example: 5 | * 6 | * // True: 7 | * isCircleSorted([2,3,4,5,0,1]); 8 | * isCircleSorted([4,5,6,9,1]); 9 | * isCircleSorted([10,11,6,7,9]); 10 | * isCircleSorted([1,2,3,4,5]); 11 | * isCircleSorted([5,7,43,987,-9,0]); 12 | * 13 | * 14 | * // False: 15 | * isCircleSorted([4,1,2,5]); 16 | * isCircleSorted([8,7,6,5,4,3]); 17 | * isCircleSorted([6,7,4,8]); 18 | * isCircleSorted([7,6,5,4,3,2,1]); 19 | * 20 | */ 21 | 22 | package codewars; 23 | 24 | import java.util.Collections; 25 | import java.util.Comparator; 26 | import java.util.LinkedList; 27 | 28 | public class CircularlySortedArray { 29 | 30 | public static void main(String[] args) { 31 | System.out.println(isCircleSorted(new int[] {1, 2, 3, 4, 5})); 32 | } 33 | 34 | public static boolean isCircleSorted(int[] a) { 35 | LinkedList input = new LinkedList<>(); 36 | for (Integer a1 : a) { 37 | input.add(a1); 38 | } 39 | 40 | LinkedList stamp = new LinkedList<>(input); // for comparison 41 | stamp.sort(Comparator.naturalOrder()); 42 | 43 | for (int i = 0; i < a.length; i++) { 44 | if (input.equals(stamp)) return true; 45 | Collections.rotate(input, 1); 46 | } 47 | 48 | return false; 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /coding-problems/PendingSols/SamsungR_D/BobAndBeautyOfTheArray.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Bob and Beauty of the Array 3 | * Bob is having a array A of N elements . Bob wants to determine the beauty of the array and 4 | * the beauty of the array is defned as :- 5 | * 6 | * Determine Bitwise OR of maximum and minimum elements of every subset of size greater 7 | * than or equal to 2 and add them. 8 | * 9 | * As the answer can be quite large , you have to report it by taking modulo with 1000000007 . 10 | * 11 | * Input 12 | * 13 | * First line of the input will contain N , denoting the number of elements of the array. 14 | * 15 | * Second line will contain N spaced integers denoting elements of the array . 16 | * 17 | * 18 | * Constraints 19 | * 1 <= N <= 200000 20 | * 1 <= A[i] <= 1000 21 | * 22 | * 23 | * Output: 24 | * 25 | * For each query you have to output single integer denoting beauty of the array . 26 | * 27 | * Hint: 28 | * 29 | * Hashing 30 | * 31 | * Sample Input 32 | * 3 33 | * 2 5 5 34 | * Sample Output 35 | * 26 36 | * Explanation 37 | * Array contains 3 integers . Thus all subsets having size >= 2 are :- 38 | * 39 | * { { 2, 5 } , { 2 , 5} , {5 , 5} , {2 , 5 , 5 } } , thus bitwise OR of the maximum and minimum elements of those subsets are 40 | * 41 | * { 7 , 7 , 5 , 7 } respectively , thus summation of all is 7 + 7 + 5 + 7 = 26%1000000007 = 26 . 42 | * 43 | * Note: Your code should be able to convert the sample input into the sample output. 44 | * However, this is not enough to pass the challenge, because the code will be run on multiple 45 | * test cases. Therefore, your code must solve this problem statement. 46 | * 47 | */ -------------------------------------------------------------------------------- /coding-problems/src/codewars/CalculateStringRotation.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second. 3 | * 4 | * For instance, take the strings "fatigue" and "tiguefa". In this case, the first string has been rotated 5 characters forward to produce the second string, so 5 would be returned. 5 | * 6 | * If the second string isn't a valid rotation of the first string, the method returns -1. 7 | * Examples: 8 | * 9 | * "coffee", "eecoff" => 2 10 | * "eecoff", "coffee" => 4 11 | * "moose", "Moose" => -1 12 | * "isn't", "'tisn" => 2 13 | * "Esham", "Esham" => 0 14 | * "dog", "god" => -1 15 | * 16 | * For Swift, your function should return an Int?. So rather than returning -1 when the second string isn't a valid rotation of the first, return nil. 17 | * 18 | * shiftedDiff("coffee", "eecoff") => 2 19 | * shiftedDiff("eecoff", "coffee") => 4 20 | * shiftedDiff("moose", "Moose") => nil 21 | * shiftedDiff("isn't", "'tisn") => 2 22 | * shiftedDiff("Esham", "Esham") => 0 23 | * shiftedDiff("dog", "god") => nil 24 | * 25 | */ 26 | 27 | package codewars; 28 | 29 | public class CalculateStringRotation { 30 | 31 | public static void main(String[] args) { 32 | System.out.println(shiftedDiff("dog", "god")); 33 | } 34 | 35 | static int shiftedDiff(String first, String second) { 36 | String testString = second + second; 37 | 38 | if (!isValid(testString, first, second)) 39 | return -1; 40 | return testString.indexOf(first); 41 | } 42 | 43 | static boolean isValid(String testString, String first, String second) { 44 | return testString.contains(first) && first.length() == second.length(); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/Program5.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * AMAZON, SAMSUNG 4 | * 5 | * You are given two numbers A and B. Write a program to count number of bits 6 | * needed to be flipped to convert A to B. 7 | * 8 | * Input: 9 | * The first line of input contains an integer T denoting the number of 10 | * test cases. T testcases follow. The first line of each test case is A 11 | * and B separated by a space. 12 | * 13 | * Output: 14 | * For each testcase, in a new line, print the number of bits needed to be flipped. 15 | * 16 | * Constraints: 17 | * 1 ≤ T ≤ 100 18 | * 1 ≤ A, B ≤ 103 19 | * 20 | * Example: 21 | * Input: 22 | * 1 23 | * 10 20 24 | * Output: 25 | * 4 26 | * 27 | * Explanation: 28 | * Testcase1: 29 | * A = 01010 30 | * B = 10100 31 | * Number of bits need to flipped = set bit count in A XOR B value i.e. 4 32 | * 33 | * 34 | */ 35 | package datastructures.BITManipulation; 36 | 37 | import java.util.Scanner; 38 | 39 | public class Program5 { 40 | public static void main(String[] args) { 41 | Scanner in = new Scanner(System.in); 42 | try { 43 | int noOfTests = in.nextInt(); 44 | int[] outputArr = new int[noOfTests]; 45 | for(int i = 0; i < noOfTests; i++) { 46 | int A = in.nextInt(); 47 | int B = in.nextInt(); 48 | outputArr[i] = countSetBitsOfN(A ^ B); 49 | } 50 | 51 | for(int i = 0; i < noOfTests; i++) { 52 | System.out.println(outputArr[i]); 53 | } 54 | } finally { 55 | if(in != null) { 56 | in.close(); 57 | } 58 | } 59 | } 60 | 61 | public static int countSetBitsOfN(int number) { 62 | int count = 0; 63 | while (number > 0) { 64 | number = number & (number - 1); 65 | count++; 66 | } 67 | return count; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/Program6.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a number N, check whether it is sparse or not. A number is said to be a sparse number 3 | * if in the binary representation of the number no two or more consecutive bits are set. 4 | * 5 | * Input: 6 | * The first line of input contains an integer T denoting the number of test cases. The first line of each test case is number 'N'. 7 | * 8 | * Output: 9 | * Print '1' if the number is sparse and '0' if the number is not sparse. 10 | * 11 | * Constraints: 12 | * 1 <= T <= 100 13 | * 1 <= N <= 103 14 | * 15 | * Example: 16 | * Input: 17 | * 2 18 | * 2 19 | * 3 20 | * 21 | * Output: 22 | * 1 23 | * 0 24 | * 25 | * Explanation: 26 | * Testcase 1: Binary Representation of 2 is 10, which is not having consecutive set bits. So, it is sparse number. 27 | * Testcase 2: Binary Representation of 3 is 11, which is having consecutive set bits in it. So, it is not a sparse number. 28 | * 29 | */ 30 | package datastructures.BITManipulation; 31 | 32 | import java.util.Scanner; 33 | 34 | public class Program6 { 35 | public static void main(String[] args) { 36 | Scanner in = new Scanner(System.in); 37 | try { 38 | int noOfTests = in.nextInt(); 39 | int[] outputArr = new int[noOfTests]; 40 | for(int i = 0; i < noOfTests; i++) { 41 | int N = in.nextInt(); 42 | outputArr[i] = checkSparse(N); 43 | } 44 | 45 | for(int i = 0; i < noOfTests; i++) { 46 | System.out.println(outputArr[i]); 47 | } 48 | } finally { 49 | if(in != null) { 50 | in.close(); 51 | } 52 | } 53 | } 54 | 55 | public static int checkSparse(int num) { 56 | if((num & (num >> 1)) >= 1) { 57 | return 0; 58 | } else { 59 | return 1; 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/SumSquaredDivisors.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Divisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42. These divisors squared are: 1, 4, 9, 36, 49, 196, 441, 1764. 3 | * The sum of the squared divisors is 2500 which is 50 * 50, a square! 4 | * 5 | * Given two integers m, n (1 <= m <= n) we want to find all integers between m and n whose sum of squared divisors is itself a square. 6 | * 42 is such a number. 7 | * 8 | * The result will be an array of arrays or of tuples (in C an array of Pair) or a string, each subarray having two elements, 9 | * first the number whose squared divisors is a square and then the sum of the squared divisors. 10 | * 11 | * #Examples: 12 | * 13 | * list_squared(1, 250) --> [[1, 1], [42, 2500], [246, 84100]] 14 | * list_squared(42, 250) --> [[42, 2500], [246, 84100]] 15 | * The form of the examples may change according to the language, see Example Tests: for more details. 16 | * 17 | */ 18 | 19 | package codewars; 20 | 21 | public class SumSquaredDivisors { 22 | public static String listSquared(long m, long n) { 23 | long sum = 0; 24 | String str = new String("["); 25 | for (long i = m; i <= n; i++) { 26 | sum = 0; 27 | for (long j = 2; j <= i; j++) { 28 | if (i % j == 0) { 29 | sum += j * j; 30 | } 31 | } 32 | if (Math.sqrt(sum + 1) % 1 == 0 && sum > 0) { 33 | sum = sum + 1; 34 | str += ("[" + i + ", " + sum + "], "); 35 | } else if (i == 1) { 36 | str += ("[" + i + ", " + 1 + "], "); 37 | } 38 | } 39 | if (str.length() > 1) { 40 | str = str.substring(0, str.length() - 2) + "]"; 41 | } else { 42 | str += "]"; 43 | } 44 | return str; 45 | } 46 | 47 | public static void main(String[] args) { 48 | System.out.println(listSquared(1, 250)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Array/CheckMergeArray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * In this problem, given two sorted arrays, you have to implement the 3 | * int[] mergeArrays(int[] arr1, int[] arr2) method, which returns an array 4 | * consisting of all elements of both arrays in a sorted way 5 | * 6 | */ 7 | package datastructures.Array; 8 | 9 | public class CheckMergeArray { 10 | 11 | public static void main(String[] args) { 12 | int[] arr1 = {1,12,14,17,23}; // creating a sorted array called arr1 13 | int[] arr2 = {11,19,27}; // creating a sorted array called arr2 14 | 15 | int[] resultantArray = mergeArrays(arr1, arr2); // calling mergeArrays 16 | 17 | System.out.print("Arrays after merging: "); 18 | for(int i : resultantArray) { 19 | System.out.print(i + " "); 20 | } 21 | } 22 | 23 | public static int[] mergeArrays(int[] arr1, int[] arr2) { 24 | int s1 = arr1.length; 25 | int s2 = arr2.length; 26 | int[] resultantArr = new int[s1+s2]; 27 | int i = 0, j = 0, k = 0; 28 | 29 | // Traverse both array 30 | while (i < s1 && j < s2) { 31 | // Check if current element of first 32 | // array is smaller than current element 33 | // of second array. If yes, store first 34 | // array element and increment first array 35 | // index. Otherwise do same with second array 36 | if(arr1[i] < arr2[j]) { 37 | resultantArr[k++] = arr1[i++]; 38 | } else { 39 | resultantArr[k++] = arr2[j++]; 40 | } 41 | } 42 | 43 | // Store remaining elements of first array 44 | while (i < s1) { 45 | resultantArr[k++] = arr1[i++]; 46 | } 47 | 48 | // Store remaining elements of second array 49 | while (j < s2) { 50 | resultantArr[k++] = arr2[j++]; 51 | } 52 | 53 | return resultantArr; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Array/ReverseAnArray.java: -------------------------------------------------------------------------------- 1 | package datastructures.Array; 2 | 3 | public class ReverseAnArray { 4 | 5 | public static void main(String[] args) { 6 | int[] array = new int[] {1, 3, 4, 2, 5, 0}; 7 | 8 | int[] reversedArray = simplestApproach(array); 9 | printArrayElements(reversedArray); 10 | 11 | System.out.println(); 12 | 13 | efficientApproach(array); 14 | printArrayElements(array); 15 | } 16 | 17 | /** 18 | * This method is not taking any extra space 19 | * @param array 20 | */ 21 | private static void efficientApproach(int[] array) { 22 | int forwardPtr = 0; 23 | int backwardPtr = array.length-1; 24 | 25 | while(forwardPtr < backwardPtr) { 26 | swap(array, forwardPtr, backwardPtr); 27 | forwardPtr++; 28 | backwardPtr--; 29 | } 30 | } 31 | 32 | /** 33 | * Utility method to print the array elements 34 | * @param array 35 | */ 36 | private static void printArrayElements(int[] array) { 37 | for(int i = 0; i < array.length; i++) { 38 | System.out.print(array[i]+" "); 39 | } 40 | } 41 | 42 | /** 43 | * Utility method to swap the array elements 44 | * @param array 45 | * @param forwardPtr 46 | * @param backwardPtr 47 | */ 48 | public static void swap(int[] array, int forwardPtr, int backwardPtr) { 49 | int temp = array[forwardPtr]; 50 | array[forwardPtr] = array[backwardPtr]; 51 | array[backwardPtr] = temp; 52 | } 53 | 54 | /** 55 | * Taken auxiliary space of O(n) 56 | * @param array 57 | */ 58 | private static int[] simplestApproach(int[] array) { 59 | int[] reversedArray = new int[array.length]; 60 | for(int i = 0; i < array.length; i++) { 61 | reversedArray[i] = array[array.length-i-1]; 62 | } 63 | return reversedArray; 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Array/CheckRemoveEven.java: -------------------------------------------------------------------------------- 1 | /** 2 | * In this problem, you have to implement the int [] removeEven(int[] arr) 3 | * method, which removes all the even elements from the array and 4 | * returns back updated array. 5 | * 6 | */ 7 | package datastructures.Array; 8 | 9 | import java.util.ArrayList; 10 | import java.util.Arrays; 11 | import java.util.Iterator; 12 | import java.util.List; 13 | 14 | public class CheckRemoveEven { 15 | 16 | public static void main(String[] args) { 17 | int[] arr = removeEven(new int[] {1, 2, 4, 5, 10, 6, 3}); 18 | for(Integer i : arr) { 19 | System.out.println(i); 20 | } 21 | 22 | Integer[] arrLst = new Integer[] {1, 2, 4, 5, 10, 6, 3}; 23 | removeEvenUsingJavaCollections(arrLst); 24 | } 25 | 26 | public static void removeEvenUsingJavaCollections(Integer[] arr) { 27 | List arrLst = new ArrayList(Arrays.asList(arr)); 28 | @SuppressWarnings("rawtypes") 29 | Iterator itr = arrLst.iterator(); 30 | while (itr.hasNext()) 31 | { 32 | int x = (Integer)itr.next(); 33 | if (x%2 == 0) { 34 | itr.remove(); 35 | } 36 | } 37 | 38 | for(Integer i : arrLst) { 39 | System.out.print(i + " "); 40 | } 41 | } 42 | 43 | public static int[] removeEven(int[] arr) { 44 | int oddElements = 0; 45 | for(int i = 0; i < arr.length; i++) { 46 | if(arr[i] % 2 != 0) { 47 | oddElements++; 48 | } 49 | } 50 | 51 | int[] result = new int[oddElements]; 52 | int result_index = 0; 53 | for(int i = 0; i < arr.length; i++) { 54 | if(arr[i] % 2 != 0) { 55 | result[result_index++] = arr[i]; 56 | } 57 | } 58 | return result; // change this and return the correct result array 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/RemoveElement.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array nums and a value val, remove all instances of that value 3 | * in-place and return the new length. 4 | * 5 | * Do not allocate extra space for another array, you must do this by 6 | * modifying the input array in-place with O(1) extra memory. 7 | * 8 | * The order of elements can be changed. It doesn't matter what you leave 9 | * beyond the new length. 10 | * 11 | * Example 1: 12 | * Given nums = [3,2,2,3], val = 3, 13 | * 14 | * Your function should return length = 2, with the first two elements of nums being 2. 15 | * 16 | * It doesn't matter what you leave beyond the returned length. 17 | * 18 | * Example 2: 19 | * Given nums = [0,1,2,2,3,0,4,2], val = 2, 20 | * 21 | * Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. 22 | * 23 | * Note that the order of those five elements can be arbitrary. 24 | * 25 | * It doesn't matter what values are set beyond the returned length. 26 | */ 27 | package leetcode; 28 | 29 | public class RemoveElement { 30 | 31 | public static void main(String[] args) { 32 | System.out.println(removeElement(new int[] {3, 2, 2, 3}, 3)); 33 | } 34 | 35 | /** 36 | * Time Complexity : O(N) 37 | * Space Complexity : O(1) 38 | * 39 | * ALGORITHM : Two Pointer Technique 40 | * 41 | * @param nums 42 | * @param val 43 | * @return 44 | */ 45 | public static int removeElement(int[] nums, int val) { 46 | int j = 0; 47 | for(int i = 0; i < nums.length; i++) { 48 | if(nums[i] == val) { 49 | continue; 50 | } else { 51 | nums[j++] = nums[i]; 52 | } 53 | } 54 | return j; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/Consecutives.java: -------------------------------------------------------------------------------- 1 | /** 2 | * You are given a list/array which contains only integers (positive and negative). 3 | * Your job is to sum only the numbers that are the same and consecutive. 4 | * The result should be one list. 5 | * 6 | * Extra credit if you solve it in one line. You can asume there is never an empty list/array 7 | * and there will always be an integer. 8 | * 9 | * Same meaning: 1 == 1 10 | * 11 | * 1 != -1 12 | * 13 | * #Examples: 14 | * 15 | * [1,4,4,4,0,4,3,3,1] # should return [1,12,0,4,6,1] 16 | * 17 | * """So as you can see sum of consecutives 1 is 1 18 | * sum of 3 consecutives 4 is 12 19 | * sum of 0... and sum of 2 20 | * consecutives 3 is 6 ...""" 21 | * 22 | * [1,1,7,7,3] # should return [2,14,3] 23 | * [-5,-5,7,7,12,0] # should return [-10,14,12,0] 24 | * 25 | */ 26 | 27 | package codewars; 28 | 29 | import java.util.ArrayList; 30 | import java.util.List; 31 | 32 | public class Consecutives { 33 | 34 | public static void main(String[] args) { 35 | ArrayList s = new ArrayList(); 36 | s.add(1); 37 | s.add(4); 38 | s.add(4); 39 | s.add(4); 40 | s.add(0); 41 | s.add(4); 42 | s.add(3); 43 | s.add(3); 44 | s.add(1); 45 | System.out.println(sumConsecutives(s)); 46 | } 47 | 48 | public static List sumConsecutives(List s) { 49 | // your code 50 | List newList = new ArrayList(); 51 | int count = 1, j = 1; 52 | for (int i = 0; i < s.size(); i++) { 53 | if (j == s.size()) { 54 | newList.add(s.get(i)); 55 | break; 56 | } 57 | if (s.get(i) == s.get(j)) 58 | count++; 59 | else { 60 | newList.add(s.get(i) * count); 61 | count = 1; 62 | } 63 | j++; 64 | } 65 | return newList; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/WordPattern.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a pattern and a string str, find if str follows the same pattern. 3 | * 4 | * Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. 5 | * 6 | * Examples: 7 | * pattern = "abba", str = "dog cat cat dog" should return true. 8 | * pattern = "abba", str = "dog cat cat fish" should return false. 9 | * pattern = "aaaa", str = "dog cat cat dog" should return false. 10 | * pattern = "abba", str = "dog dog dog dog" should return false. 11 | * Notes: 12 | * You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space. 13 | * 14 | */ 15 | 16 | package codewars; 17 | 18 | import java.util.HashMap; 19 | 20 | public class WordPattern { 21 | public static void main(String[] args) { 22 | System.out.print(wordPattern("abba", "dog cat cat dog")); 23 | } 24 | 25 | public static boolean wordPattern(String pattern, String str) { 26 | String[] strArr = str.split(" "); 27 | if(strArr.length != pattern.length()){ 28 | return false; 29 | } 30 | 31 | HashMap pattCharToStrMap = new HashMap(); 32 | for(int i = 0; i < pattern.length(); i++){ 33 | char c = pattern.charAt(i); 34 | if(pattCharToStrMap.containsKey(c)){ 35 | String value = pattCharToStrMap.get(c); 36 | if(!value.equals(strArr[i])){ 37 | return false; 38 | } 39 | }else if(pattCharToStrMap.containsValue(strArr[i])){ 40 | return false; 41 | } 42 | pattCharToStrMap.put(c, strArr[i]); 43 | } 44 | return true; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /coding-problems/PendingSols/GyanMatrix/Gifts.txt: -------------------------------------------------------------------------------- 1 | Gifts 2 | 3 | Alice wants to buy some gifts for Bob. The shopkeeper has N types of gifts. 4 | Each type of gift has a distinct price. But shopkeeper has only 2 gifts of each type. 5 | Alice has a budget of B units. A gift-set is a collection of gifts Alice bought. 6 | Alice wants to count the number of possible non-empty gift-sets she can buy by spending less than or equal to B. 7 | Two gift-sets are different if there is at least one gift which is present in one gift-set but not in other. 8 | For each type of gift, both the gifts are identical. 9 | 10 | 11 | Input Format 12 | 13 | The first line contains two space-separated integers, denoting N and B. 14 | Next line contains N space-separated integers, where the ith integer denotes the price of the ith type of gift. 15 | 16 | 17 | Output Format 18 | 19 | Print an integer, denoting the number of non-empty gift-sets she can buy. 20 | 21 | 22 | Constraints 23 | 1 <= N <= 14 24 | 1 <= B, P[i] <= 10^9 25 | ​​​​​​​ 26 | Sample Input 27 | 2 9 28 | 8 3 29 | Sample Output 30 | 3 31 | Explanation 32 | Possible gift-sets are: 33 | 34 | {gift of type 1} with cost equal to 8 units. 35 | 36 | {gift of type 2, gift of type 2} with cost equal to 6 units. 37 | 38 | {gift of type 2} with cost equal to 3 units. 39 | 40 | Note: Your code should be able to convert the sample input into the sample output. 41 | However, this is not enough to pass the challenge, because the code will be run on multiple test cases. 42 | Therefore, your code must solve this problem statement. 43 | 44 | Time Limit: 1.0 sec(s) for each input file 45 | Memory Limit: 256 MB 46 | Source Limit: 1024 KB 47 | Marking Scheme: Marks are awarded if any testcase passes 48 | Allowed Languages: JavaScript(Rhino), JavaScript(Node.js), Python, Python 3, Java, Java 8 -------------------------------------------------------------------------------- /coding-problems/src/leetcode/ConsecutiveCharacters.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a string s, the power of the string is the maximum length of a non-empty substring that 3 | * contains only one unique character. 4 | * 5 | * Return the power of the string. 6 | * 7 | * Example 1: 8 | * Input: s = "leetcode" 9 | * Output: 2 10 | * Explanation: The substring "ee" is of length 2 with the character 'e' only. 11 | * 12 | * Example 2: 13 | * Input: s = "abbcccddddeeeeedcba" 14 | * Output: 5 15 | * Explanation: The substring "eeeee" is of length 5 with the character 'e' only. 16 | * 17 | * Example 3: 18 | * Input: s = "triplepillooooow" 19 | * Output: 5 20 | * 21 | * Example 4: 22 | * Input: s = "hooraaaaaaaaaaay" 23 | * Output: 11 24 | * 25 | * Example 5: 26 | * Input: s = "tourist" 27 | * Output: 1 28 | * 29 | * Constraints: 30 | * 1 <= s.length <= 500 31 | * s contains only lowercase English letters 32 | * 33 | */ 34 | package leetcode; 35 | 36 | public class ConsecutiveCharacters { 37 | 38 | public static void main(String[] args) { 39 | System.out.println(maxPower("leetcode")); 40 | } 41 | 42 | /** 43 | * Time Complexity : O(N) 44 | * Space Complexity : O(1) 45 | * 46 | * @param s 47 | * @return 48 | */ 49 | private static int maxPower(String s) { 50 | int count = 0; 51 | int maxCount = 0; 52 | char previous = ' '; 53 | for (int i = 0; i < s.length(); i++) { 54 | char c = s.charAt(i); 55 | if (c == previous) { 56 | // if same as previous one, increase the count 57 | count++; 58 | } else { 59 | // else, reset the count 60 | count = 1; 61 | previous = c; 62 | } 63 | maxCount = Math.max(maxCount, count); 64 | } 65 | return maxCount; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/topIntQuests/PowerOfThree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an integer, write a function to determine if it is a power of three. 3 | */ 4 | package leetcode.topIntQuests; 5 | 6 | public class PowerOfThree { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(isPowerOfThreeA(27)); 10 | System.out.println(isPowerOfThreeB(27)); 11 | System.out.println(isPowerOfThreeC(27)); 12 | } 13 | 14 | /** 15 | * Simple Naive approach 16 | * 17 | * @param n 18 | * @return 19 | */ 20 | public static boolean isPowerOfThreeA(int n) { 21 | if(n == 1) return true; 22 | 23 | boolean result = false; 24 | while(n > 0) { 25 | int rem = n%3; 26 | if(rem == 0) { 27 | n /= 3; 28 | if(n == 1) { 29 | return true; 30 | } 31 | } else { 32 | return false; 33 | } 34 | } 35 | 36 | return result; 37 | } 38 | 39 | /** 40 | * Recursive approach 41 | * 42 | * @param n 43 | * @return 44 | */ 45 | public static boolean isPowerOfThreeB(int n) { 46 | if(n == 0) 47 | return false; 48 | 49 | if(n == 1) 50 | return true; 51 | 52 | if(n > 1) 53 | return n%3==0 && isPowerOfThreeB(n/3); 54 | else 55 | return false; 56 | } 57 | 58 | /** 59 | * Fastest Approach 60 | * 61 | * n is of type int. In Java, this means it is a 4 byte, signed integer. The 62 | * maximum value of this data type is 2147483647. System.out.println(Integer.MAX_VALUE) 63 | * 64 | * Maximum value of n, that's also a power of 3 is 1162261467 = 3^19 65 | * so, 3 is a prime number, the only divisors of 3^19 are 3^0, 3^1, ...., 3^19, so we need to 66 | * check if 3^19 is divisible by n or not 67 | * @param n 68 | * @return 69 | */ 70 | public static boolean isPowerOfThreeC(int n) { 71 | return n > 0 && 1162261467 % n == 0; 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/BitwiseHacks.java: -------------------------------------------------------------------------------- 1 | package datastructures.BITManipulation; 2 | 3 | public class BitwiseHacks { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(setBitAtNthPosition(7, 3)); 7 | System.out.println(unsetBitAtNthPosition(7, 2)); 8 | System.out.println(togglingABitAtNthPosition(7, 1)); 9 | System.out.println(checkIfABitIsSetAtNthPosition(7, 2)); 10 | System.out.println(strippingOffTheLowestSetBit(7)); 11 | System.out.println(getLowestSetBit(7)); 12 | System.out.println(clearLSBToIthBit(11, 2)); 13 | System.out.println(clearMSBToIthBit(12, 2)); 14 | System.out.println(uppercaseToLowercase('A')); 15 | System.out.println(lowercaseToUppercase('y')); 16 | } 17 | 18 | public static int setBitAtNthPosition(int num, int pos) { 19 | return num |= (1 << pos); 20 | } 21 | 22 | public static int unsetBitAtNthPosition(int num, int pos) { 23 | return num &= (~(1 << pos)); 24 | } 25 | 26 | public static int togglingABitAtNthPosition(int num, int pos) { 27 | return num ^= (1 << pos); 28 | } 29 | 30 | public static boolean checkIfABitIsSetAtNthPosition(int num, int pos) { 31 | num = num & (1 << pos); 32 | return num > 0 ? true : false; 33 | } 34 | 35 | public static int strippingOffTheLowestSetBit(int num) { 36 | return num & (num - 1); 37 | } 38 | 39 | public static int getLowestSetBit(int num) { 40 | return num & (-num); 41 | } 42 | 43 | public static int clearLSBToIthBit(int num, int pos) { 44 | return num & ~((1 << pos+1) - 1); 45 | } 46 | 47 | public static int clearMSBToIthBit(int num, int pos) { 48 | return num & ((1 << pos) - 1); 49 | } 50 | 51 | public static char uppercaseToLowercase(char ch) { 52 | return ((char) (ch | ' ')); 53 | } 54 | 55 | public static char lowercaseToUppercase(char ch) { 56 | return ((char) (ch & '_')); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Trie/TrieOperations.java: -------------------------------------------------------------------------------- 1 | package datastructures.Trie; 2 | 3 | public class TrieOperations { 4 | static class TrieNode { 5 | boolean isEnd; 6 | // Here We're considering only 26 lowercase english alphabets 7 | TrieNode[] child = new TrieNode[26]; 8 | } 9 | 10 | static TrieNode root; 11 | 12 | static boolean search(String key) { 13 | TrieNode curr = root; 14 | for(int i = 0; i < key.length(); i++) { 15 | int index = key.charAt(i) - 'a'; 16 | if(curr.child[index] == null) { 17 | return false; 18 | } 19 | curr = curr.child[index]; 20 | } 21 | return curr.isEnd; 22 | } 23 | 24 | static void insert(String key) { 25 | TrieNode curr = root; 26 | for(int i = 0; i < key.length(); i++) { 27 | int index = key.charAt(i) - 'a'; 28 | if(curr.child[index] == null) { 29 | curr.child[index] = new TrieNode(); 30 | } 31 | curr = curr.child[index]; 32 | } 33 | curr.isEnd = true; 34 | } 35 | 36 | static TrieNode delete(TrieNode root, String key, int i) { 37 | if(root == null) { 38 | return null; 39 | } 40 | 41 | if(i == key.length()) { 42 | root.isEnd = false; 43 | if(isEmpty(root)) { 44 | root = null; 45 | } 46 | return root; 47 | } 48 | 49 | int idx = key.charAt(i) - 'a'; 50 | root.child[idx] = delete(root.child[idx], key, i+1); 51 | 52 | if(isEmpty(root) && root.isEnd == false) { 53 | root = null; 54 | } 55 | return root; 56 | } 57 | 58 | static boolean isEmpty(TrieNode root) { 59 | for(int i = 0;i < 26; i++) { 60 | if(root.child[i] != null) { 61 | return false; 62 | } 63 | } 64 | return true; 65 | } 66 | 67 | public static void main(String[] args) { 68 | String key = "geek"; 69 | root = new TrieNode(); 70 | insert("geek"); 71 | insert("geeks"); 72 | System.out.println(search("geek")); 73 | delete(root, key, 0); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/Program12.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array arr[] of N positive elements. The task is to find the Maximum AND Value generated by 3 | * any pair of element from the array. 4 | * Note: AND is bitwise '&' operator. 5 | * 6 | * Input: 7 | * The first line of the input contains a single integer T, denoting the number of test cases. Then T 8 | * test cases follow. Each test-case has two lines of the input, the first line contains an integer denoting 9 | * the size of an array N and the second line of input contains N positive integers 10 | * 11 | * Output: 12 | * For each testcase, print Maximum AND Value of a pair in a separate line. 13 | * 14 | * Constraints: 15 | * 1 <=T <= 100 16 | * 1 <= N <= 100 17 | * 1 <= arr[i] <= 104 18 | * 19 | * Example: 20 | * Input: 21 | * 2 22 | * 4 23 | * 4 8 12 16 24 | * 4 25 | * 4 8 16 2 26 | * 27 | * Output: 28 | * 8 29 | * 0 30 | * 31 | * Explanation: 32 | * Testcase 1: Pair (8,12) has the Maximum AND Value i.e. 8. 33 | * Testcase 2: Maximum AND Value is 0 34 | * 35 | */ 36 | package datastructures.BITManipulation; 37 | 38 | import java.util.Scanner; 39 | 40 | public class Program12 { 41 | 42 | public static void main(String[] args) { 43 | Scanner in = new Scanner(System.in); 44 | try { 45 | int T = in.nextInt(); 46 | while(T --> 0) { 47 | int N = in.nextInt(); 48 | int[] arr = new int[N]; 49 | for(int i = 0; i < arr.length; i++) { 50 | arr[i] = in.nextInt(); 51 | } 52 | 53 | int result = 0; 54 | for(int i = 0; i < arr.length; i++) { 55 | for(int j = i + 1; j < arr.length; j++) { 56 | result = result > (arr[i] & arr[j]) ? result : (arr[i] & arr[j]); 57 | } 58 | } 59 | System.out.println(result); 60 | } 61 | } finally { 62 | if(in != null) { 63 | in.close(); 64 | } 65 | } 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /coding-problems/src/hackerearth/SeatingArrangement.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/seating-arrangement-1/ 3 | */ 4 | package hackerearth; 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.io.InputStreamReader; 9 | 10 | public class SeatingArrangement { 11 | 12 | public static void main(String[] args) throws NumberFormatException, IOException { 13 | //BufferedReader 14 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 15 | int T = Integer.parseInt(br.readLine()); 16 | for(int i = 0; i < T; i++){ 17 | seatingArrangement(Integer.parseInt(br.readLine())); 18 | } 19 | } 20 | public static void seatingArrangement(int N){ 21 | int remainder = 0; 22 | remainder = N%12; 23 | switch(remainder){ 24 | case 0: 25 | System.out.println(""+(N-11)+" WS"); 26 | break; 27 | 28 | case 1: 29 | System.out.println(""+(N+11)+" WS"); 30 | break; 31 | 32 | case 2: 33 | System.out.println(""+(N+9)+" MS"); 34 | break; 35 | 36 | case 3: 37 | System.out.println(""+(N+7)+" AS"); 38 | break; 39 | 40 | case 4: 41 | System.out.println(""+(N+5)+" AS"); 42 | break; 43 | 44 | case 5: 45 | System.out.println(""+(N+3)+" MS"); 46 | break; 47 | 48 | case 6: 49 | System.out.println(""+(N+1)+" WS"); 50 | break; 51 | 52 | case 7: 53 | System.out.println(""+(N-1)+" WS"); 54 | break; 55 | 56 | case 8: 57 | System.out.println(""+(N-3)+" MS"); 58 | break; 59 | 60 | case 9: 61 | System.out.println(""+(N-5)+" AS"); 62 | break; 63 | 64 | case 10: 65 | System.out.println(""+(N-7)+" AS"); 66 | break; 67 | 68 | case 11: 69 | System.out.println(""+(N-9)+" MS"); 70 | break; 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/Program4.java: -------------------------------------------------------------------------------- 1 | /** 2 | * AMAZON 3 | * 4 | * You are given a number N. Find the total count of set bits for all numbers from 1 5 | * to N(both inclusive). 6 | * 7 | * Input: 8 | * The first line of input contains an integer T denoting the number of test cases. 9 | * T testcases follow. The first line of each test case is N. 10 | * 11 | * Output: 12 | * For each testcase, in a new line, print the total count of all bits. 13 | * 14 | * Constraints: 15 | * 1 ≤ T ≤ 100 16 | * 1 ≤ N ≤ 103 17 | * 18 | * Example: 19 | * Input: 20 | * 2 21 | * 4 22 | * 17 23 | * Output: 24 | * 5 25 | * 35 26 | * 27 | * Explanation: 28 | * Testcase1: 29 | * An easy way to look at it is to consider the number, n = 4: 30 | * 0 0 0 = 0 31 | * 0 0 1 = 1 32 | * 0 1 0 = 1 33 | * 0 1 1 = 2 34 | * 1 0 0 = 1 35 | * Therefore , the total number of bits is 5. 36 | * 37 | */ 38 | package datastructures.BITManipulation; 39 | 40 | import java.util.Scanner; 41 | 42 | public class Program4 { 43 | public static void main(String[] args) { 44 | Scanner in = new Scanner(System.in); 45 | try { 46 | int noOfTests = in.nextInt(); 47 | int[] outputArr = new int[noOfTests]; 48 | for(int i = 0; i < noOfTests; i++) { 49 | int N = in.nextInt(); 50 | outputArr[i] = countSetBitsForOneToN(N); 51 | } 52 | 53 | for(int i = 0; i < noOfTests; i++) { 54 | System.out.println(outputArr[i]); 55 | } 56 | } finally { 57 | if(in != null) { 58 | in.close(); 59 | } 60 | } 61 | } 62 | 63 | public static int countSetBitsForOneToN(int N) { 64 | int sum = 0; 65 | for(int i = 1; i <= N; i++) { 66 | sum += countSetBitsOfN(i); 67 | } 68 | return sum; 69 | } 70 | 71 | public static int countSetBitsOfN(int number) { 72 | int count = 0; 73 | while (number > 0) { 74 | number = number & (number - 1); 75 | count++; 76 | } 77 | return count; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/JosephusSurvivor.java: -------------------------------------------------------------------------------- 1 | /** 2 | * In this kata you have to correctly return who is the "survivor", ie: the last element of a Josephus permutation. 3 | * 4 | * Basically you have to assume that n people are put into a circle and that they are eliminated in steps of k elements, like this: 5 | * 6 | * josephus_survivor(7,3) => means 7 people in a circle; 7 | * one every 3 is eliminated until one remains 8 | * [1,2,3,4,5,6,7] - initial sequence 9 | * [1,2,4,5,6,7] => 3 is counted out 10 | * [1,2,4,5,7] => 6 is counted out 11 | * [1,4,5,7] => 2 is counted out 12 | * [1,4,5] => 7 is counted out 13 | * [1,4] => 5 is counted out 14 | * [4] => 1 counted out, 4 is the last element - the survivor! 15 | * The above link about the "base" kata description will give you a more thorough insight about the origin of this kind of permutation, but basically that's all that there is to know to solve this kata. 16 | * 17 | * Notes and tips: using the solution to the other kata to check your function may be helpful, but as much larger numbers will be used, using an array/list to compute the number of the survivor may be too slow; you may assume that both n and k will always be >=1. 18 | * 19 | */ 20 | 21 | package codewars; 22 | 23 | import java.util.ArrayList; 24 | 25 | public class JosephusSurvivor { 26 | 27 | public static int josephusSurvivor(final int n, final int k) { 28 | ArrayList arrayN = new ArrayList<>(); 29 | // filling list 30 | for (int i = 1; i <= n; i++) { 31 | arrayN.add(i); 32 | } 33 | // elimintation 34 | int lastIndex = 0; 35 | for (int i = 0; i < n - 1; i++) { 36 | int indexToEliminate = ((lastIndex - 1) + k) % arrayN.size(); 37 | lastIndex = indexToEliminate; 38 | arrayN.remove(indexToEliminate); 39 | } 40 | return arrayN.get(0).intValue(); 41 | } 42 | 43 | public static void main(String[] args) { 44 | System.out.println(josephusSurvivor(7, 4)); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/Program3.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a number N and a bit number K, check if Kth bit of N is set or not. 3 | * A bit is called set if it is 1. Position of set bit '1' should be indexed 4 | * starting with 0 from LSB side in binary representation of the number. 5 | * Consider N = 4(100): 0th bit = 0, 1st bit = 0, 2nd bit = 1. 6 | * 7 | * Input: 8 | * The first line of input contains an integer T denoting the number of test cases. 9 | * Then T test cases follow. Each test case consists of two lines. 10 | * The first line of each test case contain an integer N. 11 | * The second line of each test case contains an integer K. 12 | * 13 | * Output: 14 | * Corresponding to each test case, print "Yes" (without quotes) 15 | * if Kth bit is set else print "No" (without quotes) in a new line. 16 | * 17 | * Constraints: 18 | * 1 ≤ T ≤ 200 19 | * 1 ≤ N ≤ 109 20 | * 0 ≤ K ≤ floor(log2(N) + 1) 21 | * 22 | * Example: 23 | * Input: 24 | * 3 25 | * 4 26 | * 0 27 | * 4 28 | * 2 29 | * 500 30 | * 3 31 | * 32 | * Output: 33 | * No 34 | * Yes 35 | * No 36 | * 37 | * Explanation: 38 | * Binary representation of 4 is 100, in which 0th bit from LSB is not set. So, answer is No. 39 | * 40 | */ 41 | package datastructures.BITManipulation; 42 | 43 | import java.util.Scanner; 44 | 45 | public class Program3 { 46 | public static void main(String[] args) { 47 | Scanner in = new Scanner(System.in); 48 | try { 49 | int noOfTests = in.nextInt(); 50 | String[] outputArr = new String[noOfTests]; 51 | for(int i = 0; i < noOfTests; i++) { 52 | int N = in.nextInt(); 53 | int K = in.nextInt(); 54 | if((N & (1 << K)) > 0) { 55 | outputArr[i] = "Yes"; 56 | } else { 57 | outputArr[i] = "No"; 58 | } 59 | } 60 | for(int i = 0; i < noOfTests; i++) { 61 | System.out.println(outputArr[i]); 62 | } 63 | } finally { 64 | if(in != null) { 65 | in.close(); 66 | } 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/DominantIndex.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Largest Number At Least Twice of Others 3 | * 4 | * In a given integer array nums, there is always exactly one largest element. 5 | * 6 | * Find whether the largest element in the array is at least twice as much as every other number in the array. 7 | * 8 | * If it is, return the index of the largest element, otherwise return -1. 9 | * 10 | * Example 1: 11 | * 12 | * Input: nums = [3, 6, 1, 0] 13 | * Output: 1 14 | * Explanation: 6 is the largest integer, and for every other number in the array x, 15 | * 6 is more than twice as big as x. The index of value 6 is 1, so we return 1. 16 | * 17 | * 18 | * Example 2: 19 | * 20 | * Input: nums = [1, 2, 3, 4] 21 | * Output: -1 22 | * Explanation: 4 isn't at least as big as twice the value of 3, so we return -1. 23 | * 24 | * 25 | * Note: 26 | * 27 | * nums will have a length in the range [1, 50]. 28 | * Every nums[i] will be an integer in the range [0, 99]. 29 | * 30 | */ 31 | 32 | package leetcode; 33 | 34 | public class DominantIndex { 35 | 36 | public static void main(String[] args) { 37 | int[] nums = new int[] {3, 6, 1, 0}; 38 | System.out.println(dominantIndex(nums)); 39 | } 40 | 41 | /** 42 | * Time complexity : O(N) 43 | * @param nums 44 | * @return 45 | */ 46 | public static int dominantIndex(int[] nums) { 47 | int dominantIndex = 0; 48 | int largestElement = nums[0]; 49 | for(int i = 1; i < nums.length; i++) { 50 | if(nums[i] > largestElement) { 51 | largestElement = nums[i]; 52 | dominantIndex = i; 53 | } 54 | } 55 | for(int i = 0; i < nums.length; i++) { 56 | if(i == dominantIndex) { 57 | continue; 58 | } else { 59 | if(2*nums[i] > largestElement) { 60 | return -1; 61 | } 62 | } 63 | } 64 | return dominantIndex; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /coding-problems/PendingSols/PayPal/Bob and Forest.txt: -------------------------------------------------------------------------------- 1 | Bob and Forest 2 | You are given a 2D character array denoting forest of length N and breadth M . In the matrix, '.' denotes barren land and ' * ' denotes tree. 3 | You are given Q questions. In each question, you are given integer K and you have to determine the number of unique squares of side less than or equal to K which contain only trees. 4 | 5 | Input 6 | 7 | First line : N and M (N denoting number of rows and M denoting number of columns). 8 | 9 | Each of the next N lines contains string of M length containing '.' and '*' . 10 | 11 | Next line consists of an integer Q, denoting number of questions. 12 | 13 | Each of the next Q lines contains a single integer K. 14 | 15 | Input Constraints 16 | 1 <= N, M <= 1000 17 | 1 <= Q <= 10^5 18 | 0 <= K <= 10^3 19 | 20 | 21 | 22 | Output 23 | 24 | For each question, print the number of unique squares of side less than or equal to K which contain only trees. 25 | Answer for each question should come in a new line. 26 | 27 | Sample Input 28 | 4 4 29 | *..* 30 | .*** 31 | **** 32 | .*** 33 | 3 34 | 1 35 | 2 36 | 3 37 | Sample Output 38 | 12 39 | 16 40 | 17 41 | Explanation 42 | In the given sample , as we can see :- 43 | 44 | Squares of side 1 containing only trees :- 12. 45 | Squares of side 2 containing only trees :- 4. 46 | Squares of side 2 containing only trees :- 1. 47 | 48 | Thus answer for query 1 is 12. 49 | Answer for query 2 i.e squares of side less than or equal to 2 are 12+4 = 16. 50 | Answer for query 3 i.e squares of side less than or equal to 3 are 12+4+1=17. 51 | 52 | Note: Your code should be able to convert the sample input into the sample output. However, this is not enough to pass the challenge, because the code will be run on multiple test cases. Therefore, your code must solve this problem statement. 53 | Time Limit: 1.0 sec(s) for each input file 54 | Memory Limit: 256 MB 55 | Source Limit: 1024 KB 56 | Marking Scheme: Marks are awarded if any testcase passes 57 | Allowed Languages: Java, Java 8 -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/Program1.java: -------------------------------------------------------------------------------- 1 | /** 2 | * AMAZON 3 | * 4 | * Given an integer an N. The task is to print the position of first set bit found 5 | * from right side in the binary representation of the number. 6 | * 7 | * Input: 8 | * The first line of the input contains an integer T, denoting the number of test cases. 9 | * Then T test cases follow. The only line of the each test case contains an integer N. 10 | * 11 | * Output: 12 | * For each test case print in a single line an integer denoting the position of the 13 | * first set bit found form right side of the binary representation of the number. 14 | * If there is no set bit print "0". 15 | * 16 | * Constraints: 17 | * 1 <= T <= 200 18 | * 0 <= N <= 106 19 | * 20 | * Example: 21 | * Input: 22 | * 2 23 | * 18 24 | * 12 25 | * 26 | * Output: 27 | * 2 28 | * 3 29 | * 30 | * Explanation: 31 | * Binary representation of the 18 is 010010, the first set bit from the right 32 | * side is at position 2. 33 | */ 34 | package datastructures.BITManipulation; 35 | 36 | import java.util.*; 37 | 38 | class Program1 { 39 | public static int INT_SIZE = 32; 40 | public static void main (String[] args) { 41 | Scanner in = new Scanner(System.in); 42 | try { 43 | int noOfTests = in.nextInt(); 44 | int[] values = new int[noOfTests]; 45 | for(int i = 0; i < values.length; i++) { 46 | values[i] = in.nextInt(); 47 | } 48 | for(int i = 0; i < values.length; i++) { 49 | System.out.println(getFirstSetBit(values[i])); 50 | } 51 | } finally { 52 | if(in != null) { 53 | in.close(); 54 | } 55 | } 56 | } 57 | 58 | public static int getFirstSetBit(int value){ 59 | if(value == 0) { 60 | return 0; 61 | } else { 62 | int pos = 1; 63 | for(int i = 0; i < INT_SIZE; i++) { 64 | if((value & (1 << i)) == 0) { 65 | pos++; 66 | } else { 67 | break; 68 | } 69 | } 70 | return pos; 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/TitleToNumber.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a column title as appear in an Excel sheet, return its corresponding column number. 3 | * 4 | * For example: 5 | * 6 | * A -> 1 7 | * B -> 2 8 | * C -> 3 9 | * ... 10 | * Z -> 26 11 | * AA -> 27 12 | * AB -> 28 13 | * ... 14 | * Example 1: 15 | * 16 | * Input: "A" 17 | * Output: 1 18 | * Example 2: 19 | * 20 | * Input: "AB" 21 | * Output: 28 22 | * Example 3: 23 | * 24 | * Input: "ZY" 25 | * Output: 701 26 | * 27 | * 28 | * Constraints: 29 | * 30 | * 1 <= s.length <= 7 31 | * s consists only of uppercase English letters. 32 | * s is between "A" and "FXSHRXW" 33 | * 34 | */ 35 | package leetcode; 36 | 37 | import java.util.HashMap; 38 | import java.util.Map; 39 | 40 | public class TitleToNumber { 41 | 42 | public static void main(String[] args) { 43 | System.out.println(titleToNumberL2R("FXSHRXW")); 44 | System.out.println(titleToNumberR2L("FXSHRXW")); 45 | } 46 | 47 | /** 48 | * Time complexity : O(N) where N is the number of characters in the input string 49 | * Space Complexity : O(1) 50 | * @param s 51 | * @return 52 | */ 53 | public static int titleToNumberR2L(String s) { 54 | int result = 0; 55 | Map alphabetMap = new HashMap(); 56 | for(int i = 0; i < 26; i++) { 57 | int c = i + 65; 58 | alphabetMap.put((char) c, i + 1); 59 | } 60 | 61 | int n = s.length(); 62 | for(int i = 0; i < n; i++) { 63 | char currentChar = s.charAt(n - i - 1); 64 | result += (alphabetMap.get(currentChar) * Math.pow(26, i)); 65 | } 66 | 67 | return result; 68 | } 69 | 70 | /** 71 | * Time complexity : O(N) where N is the number of characters in the input string 72 | * Space Complexity : O(1) 73 | * @param s 74 | * @return 75 | */ 76 | public static int titleToNumberL2R(String s) { 77 | int result = 0; 78 | int n = s.length(); 79 | for(int i = 0; i < n; i++) { 80 | result *= 26; 81 | result += (s.charAt(i) - 'A' + 1); 82 | } 83 | 84 | return result; 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /coding-problems/src/company/fidelityInternational/DistBetTwoPoints.java: -------------------------------------------------------------------------------- 1 | /** 2 | * In this challenge you will be working with points in two or three dimensional space. The classes 3 | * and methods you implement will store values for coordinates as well as calculate distance between 4 | * points. The 2D and 3D distances between two points are calculated using the following formulae: 5 | * 6 | * 2D distance = SquareRoot((x2-x1)^2 + (y2-y1)^2) 7 | * 3D distance = SquareRoot((x2-x1)^2 + (y2-y1)^2 + (z2-z1)^2) 8 | * 9 | */ 10 | 11 | package company.fidelityInternational; 12 | 13 | import java.util.Scanner; 14 | 15 | class Point2D { 16 | int x, y; 17 | 18 | public Point2D(int x, int y) { 19 | this.x = x; 20 | this.y = y; 21 | } 22 | 23 | public double dist2D(Point2D p) { 24 | double distance = Math.sqrt(Math.pow((p.x - x), 2) + Math.pow((p.y - y), 2)); 25 | return distance; 26 | } 27 | 28 | public void printDistance(double d) { 29 | System.out.println("2D distance = " + (int) Math.ceil(d)); 30 | } 31 | } 32 | 33 | class Point3D extends Point2D{ 34 | int z; 35 | 36 | public Point3D(int x, int y, int z) { 37 | super(x, y); 38 | this.z = z; 39 | } 40 | 41 | public double dist3D(Point3D p) { 42 | double distance = Math.sqrt(Math.pow((p.x - x), 2) + Math.pow((p.y - y), 2) + Math.pow((p.z - z), 2)); 43 | return distance; 44 | } 45 | 46 | public void printDistance(double d) { 47 | System.out.println("3D distance = " + (int) Math.ceil(d)); 48 | } 49 | } 50 | 51 | public class DistBetTwoPoints { 52 | 53 | public static void main(String[] args) { 54 | Scanner in = new Scanner(System.in); 55 | int x1 = in.nextInt(); 56 | int y1 = in.nextInt(); 57 | int z1 = in.nextInt(); 58 | int x2 = in.nextInt(); 59 | int y2 = in.nextInt(); 60 | int z2 = in.nextInt(); 61 | in.close(); 62 | 63 | Point3D p1 = new Point3D(x1, y1, z1); 64 | Point3D p2 = new Point3D(x2, y2, z2); 65 | double d2 = p1.dist2D(p2); 66 | double d3 = p1.dist3D(p2); 67 | 68 | Point2D p = new Point2D(0, 0); 69 | p.printDistance(d2); 70 | p = p1; 71 | p.printDistance(d3); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/BITManipulation/Program2.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given two numbers M and N. The task is to find the position of rightmost 3 | * different bit in binary representation of numbers. 4 | * 5 | * Input: 6 | * The input line contains T, denoting the number of testcases. 7 | * Each testcase follows. First line of each testcase contains two space 8 | * separated integers M and N. 9 | * 10 | * Output: 11 | * For each testcase in new line, print the position of rightmost 12 | * different bit in binary representation of numbers. If both M and N 13 | * are same then print -1 in this case. 14 | * 15 | * Constraints: 16 | * 1 <= T <= 100 17 | * 1 <= M <= 103 18 | * 1 <= N <= 103 19 | * 20 | * Example: 21 | * Input: 22 | * 2 23 | * 11 9 24 | * 52 4 25 | * 26 | * Output: 27 | * 2 28 | * 5 29 | * 30 | * Explanation: 31 | * Binary representaion of the given numbers are: 1011 and 1001, 32 | * 2nd bit from right is different. 33 | * 34 | */ 35 | package datastructures.BITManipulation; 36 | 37 | import java.util.Scanner; 38 | 39 | public class Program2 { 40 | public static int INT_SIZE = 32; 41 | public static void main (String[] args) { 42 | Scanner in = new Scanner(System.in); 43 | try { 44 | int noOfTests = in.nextInt(); 45 | int M = 0; 46 | int N = 0; 47 | int[] outputValues = new int[noOfTests]; 48 | for(int i = 0; i < noOfTests; i++) { 49 | M = in.nextInt(); 50 | N = in.nextInt(); 51 | outputValues[i] = getFirstSetBit(M ^ N); 52 | } 53 | for(int i = 0; i < outputValues.length; i++) { 54 | System.out.println(outputValues[i]); 55 | } 56 | } finally { 57 | if(in != null) { 58 | in.close(); 59 | } 60 | } 61 | } 62 | 63 | public static int getFirstSetBit(int value){ 64 | if(value == 0) { 65 | return 0; 66 | } else { 67 | int pos = 1; 68 | for(int i = 0; i < INT_SIZE; i++) { 69 | if((value & (1 << i)) == 0) { 70 | pos++; 71 | } else { 72 | break; 73 | } 74 | } 75 | return pos; 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /coding-problems/PendingSols/PayPal/Even Length Palindromic Number.txt: -------------------------------------------------------------------------------- 1 | Even Length Palindromic Number 2 | You have to design a new model which maps an even length palindromic number to some digit between 0 to 9. 3 | The number is mapped to a digit x on the basis of following criteria: 4 | 1. x should appear maximum number of times in the palindromic number, that is, among all digits in the number, x should appear maximum number of times. 5 | 2. If more than one digit appears maximum number of times, x should be the smallest digit among them. 6 | 7 | Given an integer N, you have to find the digit x for the Nth even length palindromic number. 8 | 9 | Note- First 9 even length palindromic numbers are: 10 | 11 | 11, 22, 33, 44, 55, 66, 77, 88, 99 12 | 13 | Input : 14 | 15 | First line contains T, number of test cases. 16 | 17 | Each of the next T lines contains an integer N. 18 | 19 | Output: 20 | 21 | For each test case, print the digit to which the Nth even length palindromic number is mapped. 22 | Answer for each test case should come in a new line. 23 | 24 | Constraints: 25 | 1 <= T <= 10^5 26 | 1 <= N <= 10^18 27 | 28 | 29 | 30 | 31 | Sample Input 32 | 3 33 | 1 34 | 2 35 | 10 36 | Sample Output 37 | 1 38 | 2 39 | 0 40 | 41 | Explanation 42 | For case 1: 43 | 44 | 1st even length palidromic number is 11 , so answer is 1 as 1 appears most number of times in the number. 45 | 46 | For case 2: 47 | 48 | 2nd even length palidromic number is 22 , so answer is 2 as 2 appears most number of times in the number. 49 | 50 | For case 3: 51 | 52 | 10th even length palindromic number is 1001, here both 0 and 1 appears same number of times but 0<1 so answer is 0. 53 | 54 | Note: Your code should be able to convert the sample input into the sample output. However, this is not enough to pass the challenge, because the code will be run on multiple test cases. Therefore, your code must solve this problem statement. 55 | Time Limit: 1.0 sec(s) for each input file 56 | Memory Limit: 256 MB 57 | Source Limit: 1024 KB 58 | Marking Scheme: Marks are awarded if any testcase passes 59 | Allowed Languages: Java, Java 8 -------------------------------------------------------------------------------- /coding-problems/src/leetcode/HIndexPartOne.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of citations (each citation is a non-negative integer) 3 | * of a researcher, write a function to compute the researcher's h-index. 4 | * 5 | * According to the definition of h-index on Wikipedia: "A scientist has 6 | * index h if h of his/her N papers have at least h citations each, 7 | * and the other N − h papers have no more than h citations each." 8 | * 9 | * Example: 10 | * 11 | * Input: citations = [3,0,6,1,5] 12 | * Output: 3 13 | * Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had 14 | * received 3, 0, 6, 1, 5 citations respectively. 15 | * Since the researcher has 3 papers with at least 3 citations each and the remaining 16 | * two with no more than 3 citations each, her h-index is 3. 17 | * Note: If there are several possible values for h, the maximum one is taken as the h-index. 18 | * 19 | * 20 | */ 21 | package leetcode; 22 | 23 | import java.util.Arrays; 24 | 25 | public class HIndexPartOne { 26 | 27 | public static void main(String[] args) { 28 | System.out.println(hIndexApproachOne(new int[] {3, 0, 6, 1, 5})); 29 | System.out.println(hIndexApproachTwo(new int[] {3, 0, 6, 1, 5})); 30 | } 31 | 32 | /** 33 | * Time Complexity : O(NlogN) 34 | * Space Complexity : O(1) 35 | * 36 | * @param citArr 37 | * @return 38 | */ 39 | public static int hIndexApproachOne(int[] citArr) { 40 | Arrays.sort(citArr); 41 | int i = 0; 42 | while (i < citArr.length && citArr[citArr.length - 1 - i] > i) { 43 | i++; 44 | } 45 | return i; 46 | } 47 | 48 | /** 49 | * Time Complexity : O(N) 50 | * Space Complexity : O(N) 51 | * 52 | * @param citArr 53 | * @return 54 | */ 55 | public static int hIndexApproachTwo(int[] citArr) { 56 | int n = citArr.length; 57 | int[] papersCount = new int[n+1]; 58 | for(int i : citArr) { 59 | papersCount[Math.min(n, i)]++; 60 | } 61 | int k = n; 62 | for(int s = papersCount[n]; k > s; s+= papersCount[k]) { 63 | k--; 64 | } 65 | return k; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/TwoSum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of integers, return indices of the two numbers such that they add up to a specific target. 3 | * 4 | * You may assume that each input would have exactly one solution, and you may not use the same element twice. 5 | * 6 | * Example: 7 | * 8 | * Given nums = [2, 7, 11, 15], target = 9, 9 | * 10 | * Because nums[0] + nums[1] = 2 + 7 = 9, 11 | * return [0, 1]. 12 | * 13 | */ 14 | package leetcode; 15 | 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | 19 | public class TwoSum { 20 | 21 | public static void main(String[] args) { 22 | int[] nums = new int[] {4, 6, 3, 8}; 23 | int target = 13; 24 | int[] outputArray = onePassHashTableApproach(nums, target); 25 | for(int i = 0; i < 2; i++) { 26 | System.out.print(outputArray[i] + " "); 27 | } 28 | } 29 | 30 | /** 31 | * Time Complexity : O(N^2) 32 | * Space Complexity : O(1) 33 | * 34 | * @param nums 35 | * @param target 36 | * @return 37 | */ 38 | public static int[] bruteForceApproach(int[] nums, int target) { 39 | int arrLength = nums.length; 40 | int[] returnArray = new int[2]; 41 | for(int i = 0; i < arrLength; i++) { 42 | int diff = target - nums[i]; 43 | for(int j = i+1; j < arrLength; j++) { 44 | if(nums[j] == diff) { 45 | returnArray[0] = i; 46 | returnArray[1] = j; 47 | break; 48 | } 49 | } 50 | } 51 | return returnArray; 52 | } 53 | 54 | /** 55 | * Time Complexity : O(N) 56 | * Space Complexity : O(N) 57 | * 58 | * @param nums 59 | * @param target 60 | * @return 61 | */ 62 | public static int[] onePassHashTableApproach(int[] nums, int target) { 63 | Map map = new HashMap(); 64 | for (int i = 0; i < nums.length; i++) { 65 | int complement = target - nums[i]; 66 | if (map.containsKey(complement)) { 67 | return new int[] { map.get(complement), i }; 68 | } 69 | map.put(nums[i], i); 70 | } 71 | return new int[2]; 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /coding-problems/PendingSols/PayPal/Maximize the Value.txt: -------------------------------------------------------------------------------- 1 | Minimize the value 2 | You are given a binary tree rooted at 1. Initially, all the nodes of the tree have some initial values Vi. Wave operation is to be applied on the tree. 3 | 4 | After applying the wave operation, 5 | Value of each node in the tree = Sum of all initial values of nodes in its subtree. 6 | 7 | You are required to add 1 more node with value X to the tree such that: 8 | 1. The tree remains binary after adding the node to the tree. 9 | 2. After applying the wave operation to this tree (the tree after adding node with value X), the sum of tree is minimum. 10 | 11 | Sum of tree = sum of values of all nodes in the tree. 12 | 13 | Print the minimum sum of the tree. 14 | 15 | Input : 16 | 17 | First line of input contains 2 integers N and X , number of nodes in the tree and value of new node to add respectively. 18 | Second line contains N space separated integers denoting value of each node. 19 | Each of the following N - 1 lines contains 2 integers u and v , representing edge between node u and node v. 20 | Output : 21 | 22 | Print the minimum sum possible after adding node with value X and applying wave operation such that tree remains binary tree. 23 | Constraints : 24 | 1 <= N <= 10^5 25 | 1 = 0) 11 | X := X + S[0,pos] // append substring of string S from index 0 to pos (both including) into X 12 | else 13 | X := X + S[pos,len-1] // append substring of string S from index pos to len-1 (both including) into X 14 | You have to answer Q tasks. For each task, you are given an integer K and you have to print the Kth vowel in the string X. If the Kth vowel doesn't exist print -1. 15 | 16 | Note: The vowels are a, e, i, o, and u. 17 | 18 | Input Format: 19 | 20 | The first line contains a string S. 21 | 22 | The second line contains an integer N. 23 | 24 | The third line contains N space-separated integers, denoting the element of the array val. 25 | 26 | The fourth line contains an integer Q, denoting the number of tasks. 27 | 28 | The fifth line contains Q space-separated integers, denoting the tasks. 29 | 30 | Output Format: 31 | 32 | Print the answer for each of the Q tasks in a newline. 33 | 34 | Constraints: 35 | 1 <= |S|, N, Q <= 10^5 36 | 0 <= |val[i]| <= |S|-1 37 | 1 <= K <= 10^10 38 | 39 | 40 | 41 | All the characters of string S are lowercase characters only. 42 | 43 | Sample Input 44 | aeiou 45 | 3 46 | -3 -2 1 47 | 5 48 | 1 3 5 7 10 49 | Sample Output 50 | o 51 | i 52 | u 53 | e 54 | -1 55 | Explanation 56 | The String Obtained X="ouiouae" 57 | 58 | 59 | 60 | Note: Your code should be able to convert the sample input into the sample output. However, this is not enough to pass the challenge, because the code will be run on multiple test cases. Therefore, your code must solve this problem statement. 61 | Time Limit: 1.0 sec(s) for each input file 62 | Memory Limit: 256 MB 63 | Source Limit: 1024 KB 64 | Marking Scheme: Marks are awarded if any testcase passes 65 | Allowed Languages: C++, C++14, C#, Go, Java, Java 8, Ruby -------------------------------------------------------------------------------- /coding-problems/src/algorithms/ZAlgorithm.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Z Algorithm for Pattern Matching 3 | * 4 | * Time complexity = O(N+M) where N -> length of input where pattern to be matched 5 | * M -> length of pattern 6 | * Space complexity = O(N+M) 7 | * 8 | * Z Array : 9 | * For a string str[0..n-1], Z array is of same length as string. 10 | * An element Z[i] of Z array stores length of the longest substring 11 | * starting from str[i] which is also a prefix of str[0..n-1]. 12 | * The first entry of Z array is meaning less as complete string is always prefix of itself. 13 | * 14 | * http://www.geeksforgeeks.org/z-algorithm-linear-time-pattern-searching-algorithm/ 15 | * http://www.utdallas.edu/~besp/demo/John2010/z-algorithm.htm 16 | * https://www.youtube.com/watch?v=CpZh4eF8QBw - Thank you Tushar for the wonderful explanation 17 | * 18 | */ 19 | 20 | package algorithms; 21 | 22 | public class ZAlgorithm { 23 | public static void main(String[] args) { 24 | String input = "abaaa"; 25 | int[] zArr = calculateZArray(input.toCharArray()); 26 | int sum = input.length(); 27 | for(int i = 0; i < zArr.length; i++) { 28 | sum += zArr[i]; 29 | } 30 | System.out.println(sum); 31 | } 32 | 33 | public static int[] calculateZArray(char[] input) { 34 | int[] zArr = new int[input.length]; 35 | int left = 0; 36 | int right = 0; 37 | for(int k = 1; k < input.length; k++) { 38 | if(k > right) { 39 | left = right = k; 40 | right = repeatableCode(input, zArr, left, right, k); 41 | }else { 42 | // We're operating inside zArr box 43 | int k1 = k - left; 44 | // if value doesn't stretches till right bound then just copy it. Just to reduce comparisons 45 | if(zArr[k1] < right - k + 1) { 46 | zArr[k] = zArr[k1]; 47 | }else { // otherwise try to see of there are more matches 48 | left = k; 49 | right = repeatableCode(input, zArr, left, right, k); 50 | } 51 | } 52 | } 53 | return zArr; 54 | } 55 | 56 | private static int repeatableCode(char[] input, int[] zArr, int left, int right, int k) { 57 | while(right < input.length && input[right] == input[right - left]) { 58 | right++; 59 | } 60 | zArr[k] = right - left; 61 | right--; 62 | return right; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /coding-problems/src/algorithms/RabinKarpAlgorithm.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Time complexity in worst case O(n^2)(depends on hash function) 3 | * Space complexity O(1) 4 | * 5 | * References 6 | * https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm 7 | * 8 | * https://www.youtube.com/watch?v=H4VrKHVG5qI&t=15s 9 | * 10 | */ 11 | package algorithms; 12 | 13 | public class RabinKarpAlgorithm { 14 | 15 | private static int prime = 101; 16 | 17 | public static int patternSearch(String text, String pattern) { 18 | char[] textArr = text.toCharArray(); 19 | char[] patternArr = pattern.toCharArray(); 20 | int patternLength = patternArr.length; 21 | int textLength = textArr.length; 22 | 23 | long patternHash = createHash(patternArr, patternLength); 24 | long textHash = createHash(textArr, patternLength); 25 | 26 | for(int i = 1; i <= (textLength - patternLength + 1); i++) { 27 | if(patternHash == textHash && checkEqual(textArr, i - 1, i + patternLength - 2, patternArr, 0, patternLength - 1)) { 28 | return i - 1; 29 | } 30 | if(i < textLength - patternLength + 1) { 31 | textHash = recalculateHash(textArr, i - 1, i + patternLength - 1, textHash, patternLength); 32 | } 33 | } 34 | return -1; 35 | } 36 | 37 | private static long recalculateHash(char[] str, int oldIndex, int newIndex, long oldHash, int patternLength) { 38 | long newHash = oldHash - str[oldIndex]; 39 | newHash = newHash/prime; 40 | newHash += str[newIndex]*Math.pow(prime, patternLength - 1); 41 | return newHash; 42 | } 43 | 44 | private static long createHash(char[] str, int end) { 45 | long hash = 0; 46 | for(int i = 0; i < end; i++) { 47 | hash += str[i]*Math.pow(prime, i); 48 | } 49 | return hash; 50 | } 51 | 52 | private static boolean checkEqual(char[] str1, int start1, int end1, char[] str2, int start2, int end2) { 53 | if(end1 - start1 != end2 - start2) { 54 | return false; 55 | } 56 | while (start1 <= end1 && start2 <= end2) { 57 | if(str1[start1] != str2[start2]) { 58 | return false; 59 | } 60 | start1++; 61 | start2++; 62 | } 63 | return true; 64 | } 65 | 66 | public static void main(String[] args) { 67 | System.out.println(patternSearch("TusharRoy", "sharRoy")); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /coding-problems/src/datastructures/Hashing/LinearProbingHashing.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Basic implementation of Linear Probing 3 | * -1 represents empty slot in array 4 | * -2 represents deleted slot in array 5 | * 6 | * If -1 and -2 considered as a keys in an array, then we need to create a dummy node to reference this in the 7 | * array, in case of deletion. Each time we have to check for 'Deleted' we have to check for this deleted node 8 | * 9 | */ 10 | package datastructures.Hashing; 11 | 12 | import java.util.Arrays; 13 | 14 | public class LinearProbingHashing { 15 | static int capacity; 16 | static int[] arr; 17 | static int size; 18 | public static void main(String[] args) { 19 | initialize(7); 20 | insert(49); 21 | insert(50); 22 | insert(63); 23 | insert(64); 24 | insert(68); 25 | insert(69); 26 | 27 | Arrays.stream(arr).forEach(e-> System.out.print(e + " ")); 28 | System.out.println(); 29 | System.out.println(search(65)); 30 | 31 | System.out.println(delete(69)); 32 | 33 | Arrays.stream(arr).forEach(e-> System.out.print(e + " ")); 34 | } 35 | 36 | private static void initialize(int c) { 37 | capacity = c; 38 | size = 0; 39 | arr = new int[capacity]; 40 | Arrays.fill(arr, -1); 41 | } 42 | 43 | private static int hashFunc(int key) { 44 | return key % capacity; 45 | } 46 | 47 | private static boolean search(int key) { 48 | int h = hashFunc(key); 49 | int i = h; 50 | while (arr[i] != -1) { 51 | if(arr[i] == key) { 52 | return true; 53 | } 54 | i = (i+1) % capacity; 55 | if(i == h) { 56 | return false; 57 | } 58 | } 59 | return false; 60 | } 61 | 62 | private static boolean insert(int key) { 63 | if(size == capacity) { 64 | return false; 65 | } 66 | 67 | int i = hashFunc(key); 68 | while(arr[i] != -1 && arr[i] != -2 && arr[i] != key) { 69 | i = (i+1) % capacity; 70 | } 71 | 72 | if(arr[i] == key) { 73 | return false; 74 | } else { 75 | arr[i] = key; 76 | size++; 77 | return true; 78 | } 79 | } 80 | 81 | private static boolean delete(int key) { 82 | int h = hashFunc(key); 83 | int i = h; 84 | while (arr[i] != -1) { 85 | if(arr[i] == key) { 86 | arr[i] = -2; 87 | return true; 88 | } 89 | 90 | i = (i+1) % capacity; 91 | if(i == h) { 92 | return false; 93 | } 94 | } 95 | return false; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/RevRot.java: -------------------------------------------------------------------------------- 1 | /** 2 | * The input is a string str of digits. Cut the string into chunks (a chunk here is a substring of the initial string) of size sz (ignore the last chunk if its size is less than sz). 3 | * 4 | * If a chunk represents an integer such as the sum of the cubes of its digits is divisible by 2, reverse that chunk; otherwise rotate it to the left by one position. Put together these modified chunks and return the result as a string. 5 | * 6 | * If 7 | * 8 | * sz is <= 0 or if str is empty return "" 9 | * sz is greater (>) than the length of str it is impossible to take a chunk of size sz hence return "". 10 | * 11 | * Examples: 12 | * 13 | * revrot("123456987654", 6) --> "234561876549" 14 | * revrot("123456987653", 6) --> "234561356789" 15 | * revrot("66443875", 4) --> "44668753" 16 | * revrot("66443875", 8) --> "64438756" 17 | * revrot("664438769", 8) --> "67834466" 18 | * revrot("123456779", 8) --> "23456771" 19 | * revrot("", 8) --> "" 20 | * revrot("123456779", 0) --> "" 21 | * revrot("563000655734469485", 4) --> "0365065073456944" 22 | * 23 | */ 24 | 25 | package codewars; 26 | 27 | import java.util.*; 28 | 29 | public class RevRot { 30 | 31 | public static void main(String[] args) { 32 | System.out.println(revRot("", 8)); 33 | } 34 | 35 | public static String revRot(String strng, int sz) { 36 | 37 | // your code 38 | if (sz <= 0 || strng.isEmpty() || sz > strng.length()) { 39 | return ""; 40 | } else { 41 | int index = 0; 42 | int sum = 0; 43 | ArrayList list = new ArrayList(); 44 | String result = new String(); 45 | while (index < strng.length()) { 46 | if (index + sz <= strng.length()) 47 | list.add(strng.substring(index, index + sz)); 48 | index = index + sz; 49 | } 50 | 51 | for (int i = 0; i < list.size(); i++) { 52 | sum = 0; 53 | for (int j = 0; j < sz; j++) { 54 | 55 | int digit = (int) list.get(i).charAt(j); 56 | sum += digit * digit * digit; 57 | } 58 | if (sum % 2 == 0) { 59 | StringBuilder str = new StringBuilder(list.get(i)); 60 | str = str.reverse(); 61 | result += str.toString(); 62 | } else { 63 | 64 | String str = list.get(i).toString(); 65 | str = str.substring(1, sz) + str.charAt(0); 66 | result += str; 67 | } 68 | } 69 | return result; 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/DivisibleInts.java: -------------------------------------------------------------------------------- 1 | /** 2 | * You are given an integer N. Your job is to figure out how many substrings inside of N divide evenly with N. 3 | * 4 | * Confused? I'll break it down for you. 5 | * 6 | * Let's say that you are given the integer '877692'. 7 | * 8 | * 8 does not evenly divide with 877692. 877692/8 = 109711 with 4 remainder. 9 | * 10 | * 7 does not evenly divide with 877692. 877692/7 = 125384 with 4 remainder. 11 | * 12 | * 7 does not evenly divide with 877692. 877692/7 = 125384 with 4 remainder. 13 | * 14 | * 6 evenly divides with 877692. 877692/6 = 146282 with 0 remainder. 15 | * 16 | * 9 does not evenly divide with 877692. 877692/9 = 97521 with 3 remainder. 17 | * 18 | * 2 evenly divides with 877692. 877692/2 = 438846 with 0 remainder. 19 | * We aren't going to stop there though. We need to check ALL of the substrings inside of 877692. 20 | * 21 | * 87 does not evenly divide with 877692. 877692/87 = 10088 with 36 remainder. 22 | * 23 | * 77 does not evenly divide with 877692. 877692/77 = 11398 with 46 remainder. 24 | * 25 | * 76 does not evenly divide with 877692. 877692/76 = 11548 with 44 remainder. 26 | * 27 | * 69 does not evenly divide with 877692. 877692/69 = 12720 with 12 remainder. 28 | * 29 | * 30 | * etc. 31 | * #Rules: 32 | * -If an integer is 0, then it does NOT divide evenly into anything. 33 | * -Even though N can divide evenly with itself, we do not count it towards the end number. For Example: 34 | * 35 | * N = 23, the answer will be 0. 36 | * -If there are multiple instances of a number, they all get counted. For example: 37 | * 38 | * N = 11, the answer will be 2 39 | * #Input: A non negative integer. 40 | * 41 | * #Output: The number of times you found an integer that was evenly divisible with N. 42 | * 43 | */ 44 | 45 | package codewars; 46 | 47 | public class DivisibleInts { 48 | 49 | public static void main(String[] args) { 50 | System.out.println(getCount(12)); 51 | } 52 | 53 | public static int getCount(int n) { 54 | int counter = 0; 55 | String number = n + ""; 56 | for (int i = 0; i < number.length(); i++) { 57 | for (int j = i; j < number.length(); j++) { 58 | String num = number.substring(i, j + 1); 59 | if (Integer.parseInt(num) > 0 && (n % (Integer.parseInt(num)) == 0)) { 60 | counter++; 61 | } 62 | } 63 | } 64 | return counter - 1; 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/PivotIndex.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Given an array of integers nums, write a method that returns the "pivot" index of this array. 5 | * 6 | * We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index. 7 | * 8 | * If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index. 9 | * 10 | * Example 1: 11 | * 12 | * Input: 13 | * nums = [1, 7, 3, 6, 5, 6] 14 | * Output: 3 15 | * Explanation: 16 | * The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3. 17 | * Also, 3 is the first index where this occurs. 18 | * 19 | * 20 | * Example 2: 21 | * 22 | * Input: 23 | * nums = [1, 2, 3] 24 | * Output: -1 25 | * Explanation: 26 | * There is no index that satisfies the conditions in the problem statement. 27 | * 28 | * 29 | * Note: 30 | * 31 | * The length of nums will be in the range [0, 10000]. 32 | * Each element nums[i] will be an integer in the range [-1000, 1000]. 33 | * 34 | * @author Prashant 35 | * 36 | */ 37 | public class PivotIndex { 38 | 39 | public static void main(String[] args) { 40 | int[] nums = new int[] { 1, 2, 3 }; 41 | System.out.println(pivotIndex(nums)); 42 | System.out.println(efficientSolution(nums)); 43 | } 44 | 45 | public static int pivotIndex(int[] nums) { 46 | int pivotIndex = -1; 47 | for (int i = 0; i < nums.length; i++) { 48 | int sumL = 0; 49 | int sumR = 0; 50 | for (int j = 0; j <= i - 1; j++) { 51 | sumL += nums[j]; 52 | } 53 | for (int k = i + 1; k < nums.length; k++) { 54 | sumR += nums[k]; 55 | } 56 | 57 | if (sumL == sumR) { 58 | pivotIndex = i; 59 | break; 60 | } 61 | } 62 | return pivotIndex; 63 | } 64 | 65 | /** 66 | * O(N) time and O(1) space 67 | * @param nums 68 | * @return 69 | */ 70 | public static int efficientSolution(int[] nums) { 71 | int sum = 0; 72 | int sumL = 0; 73 | for(int i = 0; i < nums.length; i++) { 74 | sum += nums[i]; 75 | } 76 | 77 | for(int i = 0; i < nums.length; i++) { 78 | sum -= nums[i]; // getting right sum for index 'i' 79 | 80 | if(sumL == sum) { 81 | return i; 82 | } 83 | 84 | sumL += nums[i]; 85 | } 86 | return -1; 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /coding-problems/src/company/fidelityInternational/AnimalInheritance.java: -------------------------------------------------------------------------------- 1 | /** 2 | * In this challenge, you will be asked to build on an abstract class and initialize an instance 3 | * of each class with a variable. The program will then test your implementation by retrieving the 4 | * data you stored. 5 | * 6 | * Complete the code in the editor below to implement the following: 7 | * 1. Three classes named Dog, Cow, and Duck that inherit from the Animal class. 8 | * 2. No argument constructors for each class that initialize the instance variables 9 | * inherited from the superclass. 10 | * 3. Each class must implement the getGreeting() method: 11 | * a. For a Dog object, this must return the String ruff 12 | * b. For a Cow object, this must return the String moo 13 | * c. For a Duck object, this must return the String quack. 14 | */ 15 | 16 | package company.fidelityInternational; 17 | 18 | abstract class Animal { 19 | protected boolean isMammal; 20 | protected boolean isCarnivorous; 21 | 22 | public Animal(boolean isMammal, boolean isCarnivorous) { 23 | this.isMammal = isMammal; 24 | this.isCarnivorous = isCarnivorous; 25 | } 26 | 27 | public boolean getIsMammal() { 28 | return this.isMammal; 29 | } 30 | 31 | public boolean getIsCarnivorous() { 32 | return this.isCarnivorous; 33 | } 34 | 35 | abstract public String getGreeting(); 36 | 37 | public void printAnimal(String name) { 38 | System.out.println("A " + name + " says '" + this.getGreeting() + "', is " + (this.getIsCarnivorous() ? "" : "not ") 39 | + "carnivorous, and is " + (this.getIsMammal() ? "" : "not ") + "a mammal."); 40 | } 41 | } 42 | 43 | class Dog extends Animal{ 44 | public Dog() { 45 | super(true, true); 46 | } 47 | 48 | public String getGreeting() { 49 | return "ruff"; 50 | } 51 | } 52 | 53 | class Cow extends Animal{ 54 | public Cow() { 55 | super(true, false); 56 | } 57 | 58 | public String getGreeting() { 59 | return "moo"; 60 | } 61 | } 62 | 63 | class Duck extends Animal{ 64 | public Duck() { 65 | super(false, false); 66 | } 67 | 68 | public String getGreeting() { 69 | return "quack"; 70 | } 71 | } 72 | 73 | public class AnimalInheritance{ 74 | public static void main(String[] args) { 75 | Animal dog = new Dog(); 76 | dog.printAnimal("dog"); 77 | 78 | Animal cow = new Cow(); 79 | cow.printAnimal("cow"); 80 | 81 | Animal duck = new Duck(); 82 | duck.printAnimal("duck"); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/EqualSidesOfAnArray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1. 3 | * 4 | * For example: 5 | * 6 | * Let's say you are given the array {1,2,3,4,3,2,1}: 7 | * Your function will return the index 3, because at the 3rd position of the array, the sum of left side of the index ({1,2,3}) and the sum of the right side of the index ({3,2,1}) both equal 6. 8 | * 9 | * Let's look at another one. 10 | * You are given the array {1,100,50,-51,1,1}: 11 | * Your function will return the index 1, because at the 1st position of the array, the sum of left side of the index ({1}) and the sum of the right side of the index ({50,-51,1,1}) both equal 1. 12 | * 13 | * Last one: 14 | * You are given the array {20,10,-80,10,10,15,35} 15 | * At index 0 the left side is {} 16 | * The right side is {10,-80,10,10,15,35} 17 | * They both are equal to 0 when added. (Empty arrays are equal to 0 in this problem) 18 | * Index 0 is the place where the left side and right side are equal. 19 | * 20 | * Note: Please remember that in most programming/scripting languages the index of an array starts at 0. 21 | * 22 | * Input: 23 | * An integer array of length 0 < arr < 1000. The numbers in the array can be any integer positive or negative. 24 | * 25 | * Output: 26 | * The lowest index N where the side to the left of N is equal to the side to the right of N. If you do not find an index that fits these rules, then you will return -1. 27 | * 28 | * Note: 29 | * If you are given an array with multiple answers, return the lowest correct index. 30 | * An empty array should be treated like a 0 in this problem. 31 | * 32 | */ 33 | 34 | package codewars; 35 | 36 | public class EqualSidesOfAnArray { 37 | 38 | public static void main(String[] args) { 39 | System.out.println(findEvenIndex(new int[] {1, 2, 3, 4, 5, 6})); 40 | } 41 | 42 | public static int findEvenIndex(int[] arr) { 43 | // your code 44 | int sum1 = 0, sum2 = 0, index = 0; 45 | for (int i = 1; i < arr.length - 1; i++) { 46 | for (int j = 0; j < i; j++) 47 | sum1 += arr[j]; 48 | for (int k = i + 1; k < arr.length; k++) 49 | sum2 += arr[k]; 50 | if (sum1 == sum2) { 51 | index = i; 52 | break; 53 | } else 54 | index = -1; 55 | sum1 = sum2 = 0; 56 | } 57 | return index; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/EANValidator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * A lot of goods have an International Article Number (formerly known as "European Article Number") abbreviated "EAN". 3 | * EAN is a 13-digits barcode consisting of 12-digits data followed by a single-digit checksum (EAN-8 is not considered in this kata). 4 | * 5 | * The single-digit checksum is calculated as followed (based upon the 12-digit data): 6 | * 7 | * The digit at the first, third, fifth, etc. position (i.e. at the odd position) has to be multiplied with "1". 8 | * The digit at the second, fourth, sixth, etc. position (i.e. at the even position) has to be multiplied with "3". 9 | * Sum these results. 10 | * 11 | * If this sum is dividable by 10, the checksum is 0. Otherwise the checksum has the following formula: 12 | * 13 | * checksum = 10 - (sum mod 10) 14 | * 15 | * For example, calculate the checksum for "400330101839" (= 12-digits data): 16 | * 17 | * 4·1 + 0·3 + 0·1 + 3·3 + 3·1 + 0·3 + 1·1 + 0·3 + 1·1 + 8·3 + 3·1 + 9·3 18 | * = 4 + 0 + 0 + 9 + 3 + 0 + 1 + 0 + 1 + 24 + 3 + 27 19 | * = 72 20 | * 10 - (72 mod 10) = 8 ⇒ Checksum: 8 21 | * 22 | * Thus, the EAN-Code is 4003301018398 (= 12-digits data followed by single-digit checksum). 23 | * 24 | * Your Task 25 | * Validate a given EAN-Code. Return true if the given EAN-Code is valid, otherwise false. 26 | * 27 | * Assumption 28 | * You can assume the given code is syntactically valid, i.e. it only consists of numbers and it exactly has a length of 13 characters. 29 | * 30 | * Examples 31 | * EANValidator.validate("4003301018398") // True 32 | * EANValidator.validate("4003301018392") // False 33 | * 34 | */ 35 | 36 | package codewars; 37 | 38 | public class EANValidator { 39 | 40 | public static void main(String[] args) { 41 | System.out.println(validate("4003301018398")); 42 | } 43 | 44 | public static boolean validate(final String eanCode) { 45 | 46 | int[] values = new int[12]; 47 | 48 | for (int i = 0; i < 12; i++) { 49 | 50 | if ((i % 2) == 0) { 51 | values[i] = Character.getNumericValue(eanCode.charAt(i)); 52 | continue; 53 | } 54 | 55 | else 56 | values[i] = ((Character.getNumericValue(eanCode.charAt(i))) * 3); 57 | } 58 | 59 | int sum = 0; 60 | for (int s : values) 61 | sum += s; 62 | 63 | int checkSum; 64 | if ((sum % 10) != 0) 65 | checkSum = (10 - (sum % 10)); 66 | else 67 | checkSum = 0; 68 | 69 | int givenCheckSum = Character.getNumericValue(eanCode.charAt(12)); 70 | return givenCheckSum == checkSum; 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /coding-problems/src/company/thoughtWorks/TrickWithTheCards.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Mr. X is performing a trick with the cards. He has N cards, lets name them 1.....N, on a round table. 3 | * So card 1 is in between 2nd card and Nth card. Initially all cards are upside down. 4 | * His trick involves making all cards face up. 5 | * 6 | * His trick is whenever he taps on a card, it flips (if card was originally upside down, after 7 | * flipping its faces up, and vice-versa), but he is no ordinary magician, he makes the two 8 | * adjacent cards (if any) also to flip with the single tap. Formally, if he taps ith card, 9 | * then i-1, i, i+1 cards are flipped. (Note that if he taps Nth card, then he flips (N-1)th, 10 | * Nth and 1st card.) 11 | * 12 | * Our magician needs a helper, to assist him in his magic tricks. He is looking for 13 | * someone who can predict minimum number of taps needed to turn all the cards facing up. 14 | * 15 | * Input : 16 | * First line of input contains T, the number of test cases. Then T lines follows, 17 | * each line contains N, the number of cards for that particular case. 18 | * 19 | * Output : 20 | * Print the output for each case in a single line. 21 | * 22 | * Constraints : 23 | * 1 <= T <= 10^5 24 | * 0 <= N <= 10^15 25 | * 26 | * SAMPLE INPUT 27 | * 2 28 | * 2 29 | * 3 30 | * 31 | * SAMPLE OUTPUT 32 | * 1 33 | * 1 34 | * Time Limit: 1.0 sec(s) for each input file. 35 | * Memory Limit: 256 MB 36 | * Source Limit: 1024 KB 37 | * Marking Scheme: Marks are awarded if any testcase passes. 38 | * Allowed Languages: C, C++, C++14, Clojure, C#, D, Erlang, F#, Go, Groovy, Haskell, Java, 39 | * Java 8, JavaScript(Rhino), JavaScript(Node.js), Julia, Kotlin, Lisp, Lisp (SBCL), Lua, 40 | * Objective-C, OCaml, Octave, Pascal, Perl, PHP, Python, Python 3, R(RScript), Racket, Ruby, 41 | * Rust, Scala, Swift, Swift-4.1, Visual Basic 42 | * 43 | */ 44 | 45 | package company.thoughtWorks; 46 | 47 | import java.io.BufferedReader; 48 | import java.io.InputStreamReader; 49 | 50 | public class TrickWithTheCards { 51 | public static void main(String args[]) throws Exception { 52 | // BufferedReader 53 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 54 | int tc = Integer.parseInt(br.readLine()); 55 | while (tc-- > 0) { 56 | long N = Long.parseLong(br.readLine()); 57 | if (N <= 0L) { 58 | System.out.println(0); 59 | } else if (N <= 2L) { 60 | System.out.println(1); 61 | } else if (N % 3L == 0) { 62 | System.out.println(N / 3L); 63 | } else { 64 | System.out.println(N); 65 | } 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /coding-problems/src/codewars/TwoStrings.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given two strings of equal length, you have to tell whether they both strings are identical. 3 | * 4 | * Two strings S1 and S2 are said to be identical, if any of the permutation of string S1 is equal to the string S2. See Sample explanation for more details. 5 | * 6 | * Input : 7 | * 8 | * First line, contains an intger 'T' denoting no. of test cases. 9 | * Each test consists of a single line, containing two space separated strings S1 and S2 of equal length. 10 | * Output: 11 | * 12 | * For each test case, if any of the permutation of string S1 is equal to the string S2 print YES else print NO. 13 | * Constraints: 14 | * 15 | * 1<= T <=100 16 | * 1<= |S1| = |S2| <= 10^5 17 | * String is made up of lower case letters only. 18 | * Note : Use Hashing Concept Only . Try to do it in O(string length) . 19 | * 20 | * SAMPLE INPUT 21 | * 3 22 | * sumit mitsu 23 | * ambuj jumba 24 | * abhi hibb 25 | * 26 | * SAMPLE OUTPUT 27 | * YES 28 | * YES 29 | * NO 30 | * 31 | * Explanation 32 | * For first test case, 33 | * 34 | * mitsu can be rearranged to form sumit . 35 | * 36 | * For second test case, 37 | * 38 | * jumba can be rearranged to form ambuj . 39 | * 40 | * For third test case, 41 | * 42 | * hibb can not be arranged to form abhi. 43 | * 44 | * Time Limit: 1.0 sec(s) for each input file. 45 | * Memory Limit: 256 MB 46 | * Source Limit: 1024 KB 47 | * Marking Scheme: Marks are awarded when all the testcases pass. 48 | * Allowed Languages: C, C++, C++14, Clojure, C#, D, Erlang, F#, Go, Groovy, Haskell, Java, Java 8, JavaScript(Rhino), JavaScript(Node.js), Julia, Kotlin, Lisp, Lisp (SBCL), Lua, Objective-C, OCaml, Octave, Pascal, Perl, PHP, Python, Python 3, R(RScript), Racket, Ruby, Rust, Scala, Swift, Visual Basic 49 | * 50 | */ 51 | package codewars; 52 | 53 | import java.io.BufferedReader; 54 | import java.io.InputStreamReader; 55 | 56 | import java.util.*; 57 | public class TwoStrings { 58 | public static void main(String args[] ) throws Exception { 59 | 60 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 61 | int T = Integer.parseInt(br.readLine()); 62 | for(int i = 0; i < T; i++){ 63 | String[] arrayOfS1S2 = br.readLine().split(" "); 64 | char[] S1 = arrayOfS1S2[0].toCharArray(); 65 | char[] S2 = arrayOfS1S2[1].toCharArray(); 66 | Arrays.sort(S1); 67 | Arrays.sort(S2); 68 | if(Arrays.equals(S1, S2)){ 69 | System.out.println("YES"); 70 | }else { 71 | System.out.println("NO"); 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /coding-problems/src/hackerearth/TwoStrings.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given two strings of equal length, you have to tell whether they both strings are identical. 3 | * 4 | * Two strings S1 and S2 are said to be identical, if any of the permutation of string S1 is equal to the string S2. See Sample explanation for more details. 5 | * 6 | * Input : 7 | * 8 | * First line, contains an intger 'T' denoting no. of test cases. 9 | * Each test consists of a single line, containing two space separated strings S1 and S2 of equal length. 10 | * Output: 11 | * 12 | * For each test case, if any of the permutation of string S1 is equal to the string S2 print YES else print NO. 13 | * Constraints: 14 | * 15 | * 1<= T <=100 16 | * 1<= |S1| = |S2| <= 10^5 17 | * String is made up of lower case letters only. 18 | * Note : Use Hashing Concept Only . Try to do it in O(string length) . 19 | * 20 | * SAMPLE INPUT 21 | * 3 22 | * sumit mitsu 23 | * ambuj jumba 24 | * abhi hibb 25 | * 26 | * SAMPLE OUTPUT 27 | * YES 28 | * YES 29 | * NO 30 | * 31 | * Explanation 32 | * For first test case, 33 | * 34 | * mitsu can be rearranged to form sumit . 35 | * 36 | * For second test case, 37 | * 38 | * jumba can be rearranged to form ambuj . 39 | * 40 | * For third test case, 41 | * 42 | * hibb can not be arranged to form abhi. 43 | * 44 | * Time Limit: 1.0 sec(s) for each input file. 45 | * Memory Limit: 256 MB 46 | * Source Limit: 1024 KB 47 | * Marking Scheme: Marks are awarded when all the testcases pass. 48 | * Allowed Languages: C, C++, C++14, Clojure, C#, D, Erlang, F#, Go, Groovy, Haskell, Java, Java 8, JavaScript(Rhino), JavaScript(Node.js), Julia, Kotlin, Lisp, Lisp (SBCL), Lua, Objective-C, OCaml, Octave, Pascal, Perl, PHP, Python, Python 3, R(RScript), Racket, Ruby, Rust, Scala, Swift, Visual Basic 49 | * 50 | */ 51 | package hackerearth; 52 | 53 | import java.io.BufferedReader; 54 | import java.io.InputStreamReader; 55 | 56 | import java.util.*; 57 | public class TwoStrings { 58 | public static void main(String args[] ) throws Exception { 59 | 60 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 61 | int T = Integer.parseInt(br.readLine()); 62 | for(int i = 0; i < T; i++){ 63 | String[] arrayOfS1S2 = br.readLine().split(" "); 64 | char[] S1 = arrayOfS1S2[0].toCharArray(); 65 | char[] S2 = arrayOfS1S2[1].toCharArray(); 66 | Arrays.sort(S1); 67 | Arrays.sort(S2); 68 | if(Arrays.equals(S1, S2)){ 69 | System.out.println("YES"); 70 | }else { 71 | System.out.println("NO"); 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /coding-problems/src/hackerearth/PlayWIthNumbersSimple.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Using Simple Approach 3 | * 4 | * You are given an array of n numbers and q queries. For each query you have to print the floor of the expected value(mean) of the subarray from L to R. 5 | * 6 | * 7 | * First line contains two integers N and Q denoting number of array elements and number of queries. 8 | * 9 | * Next line contains N space seperated integers denoting array elements. 10 | * 11 | * Next Q lines contain two integers L and R(indices of the array). 12 | * 13 | * 14 | * print a single integer denoting the answer. 15 | * 16 | * : 17 | * 18 | * 1<= N ,Q,L,R <= 10^6 19 | * 20 | * 1<= Array elements <= 10^9 21 | * 22 | * NOTE 23 | * 24 | * Use Fast I/O 25 | * 26 | * Problem setter : Sheldon Tauro 27 | * 28 | * SAMPLE INPUT 29 | * 5 3 30 | * 1 2 3 4 5 31 | * 1 3 32 | * 2 4 33 | * 2 5 34 | * 35 | * SAMPLE OUTPUT 36 | * 2 37 | * 3 38 | * 3 39 | * Time Limit: 1.5 sec(s) for each input file. 40 | * Memory Limit: 256 MB 41 | * Source Limit: 1024 KB 42 | * Marking Scheme: Marks are awarded when all the testcases pass. 43 | * Allowed Languages: C, C++, C++14, Clojure, C#, D, Erlang, F#, Go, Groovy, 44 | * Haskell, Java, Java 8, JavaScript(Rhino), JavaScript(Node.js), Julia, Kotlin, 45 | * Lisp, Lisp (SBCL), Lua, Objective-C, OCaml, Octave, Pascal, Perl, PHP, Python, 46 | * Python 3, R(RScript), Racket, Ruby, Rust, Scala, Swift, Swift-4.1, Visual Basic 47 | * 48 | */ 49 | package hackerearth; 50 | 51 | import java.io.BufferedReader; 52 | import java.io.InputStreamReader; 53 | 54 | public class PlayWIthNumbersSimple { 55 | public static void main(String[] args) throws Exception { 56 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 57 | final String[] NQ = br.readLine().split(" "); 58 | final int[] A = new int[Integer.parseInt(NQ[0])]; 59 | String[] arrayInput = br.readLine().split(" "); 60 | long sum[] = new long[Integer.parseInt(NQ[0])]; 61 | long sums = 0; 62 | for (int i = 0; i < Integer.parseInt(NQ[0]); i++) { 63 | A[i] = Integer.parseInt(arrayInput[i]); 64 | sums = sums + A[i]; 65 | sum[i] = sums; 66 | } 67 | 68 | StringBuilder op = new StringBuilder(); 69 | 70 | for (int i = 0; i < Integer.parseInt(NQ[1]); i++) { 71 | final String[] query = br.readLine().split(" "); 72 | int start = Integer.parseInt(query[0]) - 1; 73 | int end = Integer.parseInt(query[1]) - 1; 74 | 75 | long sum0 = sum[end] - sum[start] + A[start]; 76 | 77 | long mean = sum0 / (end - start + 1); 78 | op.append(mean).append("\n"); 79 | } 80 | System.out.println(op.toString()); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /coding-problems/src/company/thoughtWorks/IntelligentGirl.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Soumika has a string S and its starting index is 1. The string S consists of characters from . 3 | * As she is very intelligent, she wants to test his brother Vinay Tendulkar. 4 | * She asked her brother Vinay Tendulkar to count the number of even numbered characters 5 | * ( i.e ) for every index i . For an index i, the result should be calculated from i to the 6 | * end of the string. As Vinay doesn't know about programming, he wants you to help him find 7 | * the solution. 8 | * 9 | * Input: 10 | * First line contains a string S. 11 | * 12 | * Output: 13 | * Print |S| space-separated integers,the result of every index. 14 | * 15 | * Constraints: 16 | * 1 ≤ |S| ≤ 4 17 | * 18 | * SAMPLE INPUT 19 | * 574674546476 20 | * 21 | * SAMPLE OUTPUT 22 | * 7 7 7 6 5 5 4 4 3 2 1 1 23 | * Explanation 24 | * Given string S is . 25 | * for index 1 26 | * Number of even numbers from 5 to end of the string is 7 so the result of index 1 is 7. 27 | * for index 2 28 | * Number of even numbers from 7 to end of the string is 7 so the result of index 2 is 7. 29 | * for index 3 30 | * Number of even numbers from 4 to end of the string is 7 so the result of index 3 is 7. 31 | * for index 3 32 | * Number of even numbers from 6 to end of the string is 6 so the result of index 4 is 6..... 33 | * 34 | * Time Limit: 1.0 sec(s) for each input file. 35 | * Memory Limit: 256 MB 36 | * Source Limit: 1024 KB 37 | * Marking Scheme: Marks are awarded if any testcase passes. 38 | * Allowed Languages: C, C++, C++14, Clojure, C#, D, Erlang, F#, Go, Groovy, Haskell, Java, 39 | * Java 8, JavaScript(Rhino), JavaScript(Node.js), Julia, Kotlin, Lisp, Lisp (SBCL), Lua, 40 | * Objective-C, OCaml, Octave, Pascal, Perl, PHP, Python, Python 3, R(RScript), Racket, Ruby, 41 | * Rust, Scala, Swift, Swift-4.1, Visual Basic 42 | * 43 | */ 44 | 45 | package company.thoughtWorks; 46 | 47 | import java.io.BufferedReader; 48 | import java.io.InputStreamReader; 49 | 50 | public class IntelligentGirl { 51 | 52 | public static void main(String args[]) throws Exception { 53 | // BufferedReader 54 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 55 | String numberString = br.readLine(); 56 | int lenStr = numberString.length(); 57 | int[] outArr = new int[lenStr + 1]; 58 | for (int i = lenStr - 1, j = lenStr; i >= 0 && j > 0; i--, j--) { 59 | if (numberString.charAt(i) % 2 == 0) { 60 | outArr[i] = outArr[j] + 1; 61 | } else { 62 | outArr[i] = outArr[j]; 63 | } 64 | } 65 | for (int i = 0; i < lenStr; i++) { 66 | System.out.print(outArr[i] + " "); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /coding-problems/src/leetcode/topIntQuests/DailyTemperatures.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a list of daily temperatures T, return a list such that, for each day in the input, tells you 3 | * how many days you would have to wait until a warmer temperature. If there is no future day for which 4 | * this is possible, put 0 instead. 5 | * 6 | * For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], 7 | * your output should be [1, 1, 4, 2, 1, 1, 0, 0]. 8 | * 9 | * Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer 10 | * in the range [30, 100] 11 | * 12 | */ 13 | package leetcode.topIntQuests; 14 | 15 | import java.util.Arrays; 16 | import java.util.Stack; 17 | 18 | public class DailyTemperatures { 19 | 20 | public static void main(String[] args) { 21 | int[] T = new int[] {73, 74, 75, 71, 69, 72, 76, 73}; 22 | int[] ans = naiveSoln(T); 23 | 24 | Arrays.stream(ans).forEach(e-> System.out.print(e + " ")); 25 | 26 | ans = optimizedSoln(T); 27 | 28 | System.out.println(); 29 | Arrays.stream(ans).forEach(e-> System.out.print(e + " ")); 30 | } 31 | 32 | /** 33 | * Brute Force approach 34 | * Time Complexity : O(N*N), where N is the size of T array 35 | * Space Complexity : O(W), where W is the number of allowed values in T[i] 36 | * 37 | * @param T 38 | * @return 39 | */ 40 | @SuppressWarnings("unused") 41 | public static int[] naiveSoln(int[] T) { 42 | int arrLength = T.length; 43 | int count; 44 | int[] result = new int[T.length]; 45 | outer : for(int i = 0; i < arrLength; i++) { 46 | count = 0; 47 | inner : for(int j = i+1; j < arrLength; j++) { 48 | if(T[j] > T[i]) { 49 | count++; 50 | result[i] = count; 51 | break inner; 52 | } else { 53 | count++; 54 | } 55 | } 56 | } 57 | 58 | return result; 59 | } 60 | 61 | /** 62 | * This solution is based on the concept of Stack (Next Greater Element) 63 | * Time Complexity : O(N) 64 | * Space Complexity : O(W), where W is the number of allowed values in T[i] 65 | * 66 | * @return 67 | */ 68 | public static int[] optimizedSoln(int[] T) { 69 | int[] ans = new int[T.length]; 70 | Stack stack = new Stack(); 71 | for (int i = T.length - 1; i >= 0; --i) { 72 | while (!stack.isEmpty() && T[i] >= T[stack.peek()]) stack.pop(); 73 | ans[i] = stack.isEmpty() ? 0 : stack.peek() - i; 74 | stack.push(i); 75 | } 76 | return ans; 77 | } 78 | } 79 | --------------------------------------------------------------------------------