├── .github └── FUNDING.yml ├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src └── main └── java └── com ├── ctci ├── arraysandstrings │ ├── CheckPermutation.java │ ├── IsUnique.java │ ├── OneAway.java │ ├── PalindromePermutation.java │ ├── RotateMatrix.java │ ├── StringCompression.java │ ├── StringRotation.java │ ├── URLify.java │ └── ZeroMatrix.java ├── bitmanipulation │ ├── BinaryToString.java │ ├── Conversion.java │ ├── Debugger.java │ ├── DrawLine.java │ ├── FlipBitToWin.java │ ├── Insertion.java │ ├── NextNumber.java │ └── PairwiseSwap.java ├── linkedlists │ ├── DeleteMiddleNode.java │ ├── Intersection.java │ ├── KthToLastElement.java │ ├── LoopDetection.java │ ├── Node.java │ ├── Palindrome.java │ ├── Partition.java │ ├── RemoveDuplicates.java │ └── SumLists.java ├── recursionanddp │ └── FibonacciNumber.java ├── stacksandqueues │ ├── QueueViaStacks.java │ ├── SortStack.java │ ├── StackMin.java │ └── StackOfPlates.java └── treesandgraphs │ ├── BuildOrder.java │ ├── CheckBalanced.java │ ├── CheckSubtree.java │ ├── FirstCommonAncestor.java │ ├── FirstCommonAncestorWithParentAccess.java │ ├── GraphNode.java │ ├── ListOfDepths.java │ ├── MinimalTree.java │ ├── RouteBetweenNodes.java │ ├── Successor.java │ ├── TreeNode.java │ └── ValidateBST.java ├── hackerrank ├── algorithms │ ├── arraysandsorting │ │ ├── InsertionSort1.java │ │ ├── InsertionSort2.java │ │ ├── IntroTutorial.java │ │ ├── LoopInvariant.java │ │ ├── QuickSort1.java │ │ ├── QuickSort2.java │ │ └── RunningTime.java │ ├── implementation │ │ ├── CavityMap.java │ │ ├── ExtraLongFactorials.java │ │ ├── GridSearch.java │ │ └── TheTimeInWords.java │ ├── recursion │ │ └── RecursiveDigitSum.java │ ├── strings │ │ ├── AlternatingCharacters.java │ │ ├── MakingAnagrams.java │ │ ├── PalindromeIndex.java │ │ ├── Pangram.java │ │ └── TwoStrings.java │ └── warmup │ │ ├── FlippingBits.java │ │ ├── LonelyInteger.java │ │ ├── LoveLetterMystery.java │ │ ├── MaximizingXor.java │ │ └── UtopianTree.java ├── bitmanipulation │ ├── CounterGame.java │ ├── Solution.java │ └── TwosCompliment.java ├── contests │ └── SwappingInAnArray.java ├── interviewpreparation │ ├── arrays │ │ ├── DS2DArrayProblem.java │ │ └── NewYearChaos.java │ ├── greedyalgorithmns │ │ ├── LuckBalance.java │ │ └── MinimumAbsoluteDifference.java │ └── warmup │ │ ├── JumpingClouds.java │ │ └── RepeatedString.java ├── java │ ├── advanced │ │ └── JavaVisitorPattern.java │ ├── bignumber │ │ └── BigDecimal.java │ └── oops │ │ └── JavaInheritance.java ├── projecteuler │ └── MultiplesOf3and5.java └── tutorials │ └── ctci │ ├── QueuesWithTwoStacks.java │ └── RansomNote.java ├── leetcode ├── arrays │ ├── BuySellStocks.java │ ├── BuySellStocksII.java │ ├── CanPlaceFlowers.java │ ├── FindTheCelebrity.java │ ├── InsertInterval.java │ ├── MajorityElement.java │ ├── MergeIntervals.java │ ├── MergeSortedArray.java │ ├── NumberOfIslands.java │ ├── PascalsTriangle.java │ ├── RemoveDuplicates.java │ ├── RotateArray.java │ ├── ShortestWordDistance.java │ ├── ShortestWordDistanceIII.java │ ├── SparseMatrixMultiplication.java │ ├── ValidTriangleNumber.java │ └── binarysearch │ │ ├── PowXN.java │ │ ├── SearchInsertPosition.java │ │ ├── SmallestLetterGreaterThanTarget.java │ │ └── SqrtX.java ├── design │ ├── AllOne.java │ ├── DesignHitCounter.java │ ├── InsertDeleteGetRandom.java │ ├── LFUCache.java │ └── LRUCache.java ├── dynamicprogramming │ ├── MaximumProductSubArray.java │ ├── MaximumSubArray.java │ ├── PaintHouse.java │ └── PaintHouseII.java ├── graphs │ ├── GraphValidTree.java │ ├── WordLadder.java │ └── WordLadderII.java ├── hashtables │ ├── ContainsDuplicates.java │ ├── IsomorphicStrings.java │ ├── MyHashMap.java │ ├── MyHashSet.java │ ├── RepeatedDnaSequence.java │ ├── ShortestWordDistanceII.java │ ├── TwoSumIII.java │ └── slidingwindow │ │ ├── LongestSubstringWithKDistinctCharacters.java │ │ ├── LongestSubstringWithoutRepeatingCharacters.java │ │ └── MinimumWindowSubstring.java ├── heaps │ ├── KthLargestElementInArray.java │ └── TopKFrequentElements.java ├── linkedlists │ ├── AddOneToNumberInList.java │ ├── LinkedListCycleII.java │ └── Node.java ├── math │ ├── BestMeetingPoint.java │ ├── ExcelSheetColumnNumber.java │ └── ReverseInteger.java ├── recursion │ ├── FlattenNestListIterator.java │ ├── NestedInteger.java │ ├── NestedListWeightSum.java │ └── NestedListWeightSumII.java ├── stacks │ ├── ExclusiveTimeOfFunctions.java │ └── ReversePolishNotation.java ├── strings │ ├── AnagramsInString.java │ ├── CountAndSay.java │ ├── LongestCommonPrefix.java │ ├── RansomNote.java │ ├── ReverseStringII.java │ ├── ReverseVowels.java │ ├── StrStr.java │ ├── StringCompression.java │ ├── UniqueCharacterInString.java │ └── ValidPalindrome.java ├── trees │ ├── BinaryTreeUpsideDown.java │ ├── BinaryTreeZigZagLevelOrderTraversal.java │ ├── ClosestBinarySearchTreeValue.java │ ├── ClosestBinarySearchTreeValueII.java │ ├── LeavesOfBinaryTree.java │ ├── SecondMinNodeInBinaryTree.java │ ├── SerializeDeserializeBinaryTree.java │ ├── SymmetricTree.java │ └── TreeNode.java └── trie │ └── LongestWord.java └── rampatra ├── Main.java ├── arrays ├── ArrangeNosToFormBiggestNo.java ├── BooleanMatrix.java ├── CelebrityProblem.java ├── ConsecutiveElements.java ├── CountDivisors.java ├── CountSmallerElementsOnRHS.java ├── DistinctPairs.java ├── DuplicatesInArray.java ├── DuplicatesInArrayWithinKDistance.java ├── EqualProbabilityRandomNoGenerator.java ├── EquilibriumIndex.java ├── FixedPoint.java ├── FlattenArray.java ├── IntersectionAndUnionOf2SortedArrays.java ├── InversionsInArray.java ├── KLargestElements.java ├── KthLargestElement.java ├── LargestProductContiguousSubArray.java ├── LargestSumContiguousSubArray.java ├── LeadersInArray.java ├── LongestBitonicSubArray.java ├── LongestConsecutiveSubsequence.java ├── MajorityElement.java ├── MajorityElementInSortedArray.java ├── MatrixInSpiral.java ├── MaxDiffWithLargerElementAfterSmallerElement.java ├── MaxInAllSubArrays.java ├── MaxIndexDiff.java ├── MaxMinWithMinComparisons.java ├── MaxSpan.java ├── MaximumSizeSquareSubMatrix.java ├── MaximumSumNonAdjacentSubSequence.java ├── MedianOfStream.java ├── MedianOfTwoSortedArrays.java ├── MergeArrayOfNIntoArrayOfMPlusN.java ├── MinimumDistanceBetweenTwoNos.java ├── MissingAndRepeatingElements.java ├── MissingNumber.java ├── NextGreaterElement.java ├── NextLargerNumber.java ├── NthSmallestNumber.java ├── NumberOccurringOddTimes.java ├── OccurrencesInSortedArray.java ├── PairDiff.java ├── PairSum.java ├── PivotedBinarySearch.java ├── ProductArrayPuzzle.java ├── ReservoirSampling.java ├── ReverseArray.java ├── RotateArray.java ├── RotateMatrixBy90Degrees.java ├── RotatedIndex.java ├── SearchInSorted2DArray.java ├── Segregate0s1sAnd2s.java ├── Segregate0sAnd1s.java ├── SegregateEvenAndOddNos.java ├── SmallestAndSecondSmallest.java ├── SmallestMissingNumber.java ├── SortedSubSequence.java ├── SubArrayOfSum.java ├── SubsetOfArray.java ├── SymmetricDifference.java ├── TripletOfSum.java ├── TwoElementsSumClosestToZero.java ├── TwoRepeatingElements.java ├── TwoStacksInOneArray.java └── UnsortedSubArray.java ├── backtracking ├── KnightTour.java └── RatInAMaze.java ├── base ├── AVLTree.java ├── BinaryNode.java ├── BinarySearchTree.java ├── BinaryTree.java ├── CircularSingleLinkedList.java ├── DoubleLinkedList.java ├── DoubleLinkedNode.java ├── Graph.java ├── GraphNode.java ├── LinkedList.java ├── LinkedQueue.java ├── LinkedStack.java ├── MaxHeap.java ├── MinHeap.java ├── Queue.java ├── SingleLinkedList.java ├── SingleLinkedNode.java ├── Stack.java ├── Tree.java ├── Trie.java └── UndirectedGraph.java ├── bits ├── AbsWithoutBranching.java ├── Addition.java ├── BinaryGap.java ├── BinaryString.java ├── BooleanArrayPuzzle.java ├── ConvertAToB.java ├── CountSetBits.java ├── CountSetBitsFromMinusNtoN.java ├── ElementOccurringOnce.java ├── FlippingBits.java ├── IntegerOverflow.java ├── LittleAndBigEndian.java ├── MaxWithoutBranching.java ├── Modulo.java ├── MultipleOf3.java ├── Multiply.java ├── NextHigherNumber.java ├── NextPowerOf2.java ├── OppositeSign.java ├── Parity.java ├── PowerOf2.java ├── PowerOf4.java ├── README.md ├── ReverseBits.java ├── RightShiftOperator.java ├── RightmostSetBit.java ├── RotateBits.java ├── ShiftByNegativeNumber.java ├── SmallestOf3Integers.java ├── StrCmp.java ├── SubBit.java ├── SwapBits.java └── TwoNonRepeatingElements.java ├── blockchain ├── Block.java ├── Blockchain.java ├── Message.java ├── MessageHandler.java ├── P2P.java └── Peer.java ├── database └── README.md ├── dynamicprogramming ├── FibonacciNumbers.java ├── LongestIncreasingSubSequence.java ├── MaximumRectangleOf1sInMatrix.java └── MinimumJumpsToReachEnd.java ├── java8 ├── DateTime.java ├── FlatMapInStreams.java ├── Lambdas.java └── Streams.java ├── linkedlists ├── AddNumbersInTwoLists.java ├── CloneWithRandPointers.java ├── DeleteAlternateNodes.java ├── DeleteLesserNodes.java ├── DeleteMnodesAfterNnodes.java ├── DeleteNode.java ├── DetectAndRemoveLoop.java ├── DetectLoop.java ├── DivideCircularListIntoTwo.java ├── FlattenMultiLevelLinkedList.java ├── Identical.java ├── InsertInSortedCircularLinkedList.java ├── InsertInSortedList.java ├── IntersectionAndUnionOf2Lists.java ├── IntersectionOf2SortedLists.java ├── IntersectionPointOfTwoLists.java ├── LRUCache.java ├── MaximumSumLinkedList.java ├── MergeSort.java ├── MergeSortDoubleLinkedList.java ├── MergeTwoLinkedListAlternatively.java ├── MergeTwoSortedLists.java ├── MiddleNode.java ├── MoveLastNodeToFirst.java ├── NthNodeFromLast.java ├── PairWiseSwap.java ├── Palindrome.java ├── QuickSort.java ├── RandomNode.java ├── RemoveDuplicates.java ├── RemoveMiddlePointsFromLineSegments.java ├── ReverseAlternateNodesAndAppendAtEnd.java ├── ReverseDoubleLinkedList.java ├── ReverseLinkedListInAlternateGroups.java ├── ReverseLinkedListInGroups.java ├── ReverseSingleLinkedList.java ├── RotateLinkedList.java ├── SegregateEvenOddNumbers.java ├── SortAlternativelySortedLinkedList.java ├── SortLinkedListOf0s1s2s.java ├── SortedDLLToBBST.java ├── StackWithOperationOnMiddleElement.java ├── SwapKthNode.java ├── SwapNodes.java └── TripletFromThreeLinkedLists.java ├── misc ├── BotTesting.java ├── BreakParagraph.java ├── CollectionIteration.java ├── DivideByZero.java ├── Equals.java ├── GarbageCollection.java ├── GenericNonGenericMix.java ├── HitCount.java ├── MapReduce.java ├── MapWithTimestamp.java ├── MethodLocalVSInner.java ├── MethodOverloading.java ├── Outer.java ├── OuterClassAccess.java ├── RandomTest.java ├── ReadFile.java ├── RecursiveWarmup.java ├── RegexReplaceAllSpaces.java ├── RegexValidateLatLong.java ├── ReverseAndAdd.java ├── TreeList.java ├── parenthesis.txt └── reverseandadd.txt ├── permutations ├── StringPermutations.java ├── StringPermutationsCount.java ├── StringPermutationsWithDuplicates.java └── UppercaseLowercasePermutations.java ├── searching ├── BinarySearch.java └── InterpolationSearch.java ├── sorting ├── BubbleSort.java ├── CheckSorted.java ├── HeapSort.java ├── MergeSort.java ├── MergeSortSpaceOptimized.java ├── PancakeSort.java ├── QuickSort.java ├── SelectionSort.java └── WiggleSort.java ├── stacks ├── BalancingParenthesis.java └── MaxRectangleAreaInHistogram.java ├── strings ├── AnagramsTogether.java ├── AnagramsTogetherLexicographically.java ├── BasicRegexParser.java ├── CompressString.java ├── IntegerToString.java ├── KeepOnlyKConsecutiveLetters.java ├── NearPalindrome.java ├── RemoveDuplicatesAndArrangeLetters.java ├── RemoveExtraSpaces.java ├── StringRotation.java ├── StringToInteger.java ├── SubStringCheck.java ├── SubStrings.java └── WithoutString.java ├── threads ├── Basics.java ├── NamePrint.java ├── ProducerConsumerUsingLockApi.java ├── ProducerConsumerUsingWaitNotify.java └── SimpleDeadlock.java └── trees ├── BFSUsingQueue.java ├── CheckForBST.java ├── ChildrenSum.java ├── ConnectNodesAtSameLevel.java ├── ConstructTreeFromInOrderAndPreOrder.java ├── DoubleTree.java ├── HeightBalanced.java ├── IdenticalTrees.java ├── InOrderUsingStack.java ├── InOrderWithoutStackAndRecursion.java ├── LeafNodes.java ├── LeastCommonAncestorInBST.java ├── LeastCommonAncestorInBT.java ├── MirrorTree.java ├── RandomNodeInBT.java ├── RootToLeafPaths.java ├── SecondSmallestInBST.java ├── SpiralTraversal.java ├── TreeToList.java └── TwoSwappedNodesInBST.java /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: rampatra # Replace with a single Patreon username 5 | open_collective: jbot # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: https://www.paypal.me/ramswaroop # Replace with a single custom sponsorship URL 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Do not version control these files 2 | *.class 3 | *.log 4 | *.ctxt 5 | .mtj.tmp/ 6 | *.jar 7 | *.war 8 | *.nar 9 | *.ear 10 | *.zip 11 | *.tar.gz 12 | *.rar 13 | hs_err_pid* 14 | .DS_Store 15 | .AppleDouble 16 | .LSOverride 17 | Icon 18 | ._* 19 | .DocumentRevisions-V100 20 | .fseventsd 21 | .Spotlight-V100 22 | .TemporaryItems 23 | .Trashes 24 | .VolumeIcon.icns 25 | .com.apple.timemachine.donotpresent 26 | .AppleDB 27 | .AppleDesktop 28 | Network Trash Folder 29 | Temporary Items 30 | .apdisk 31 | .idea/ 32 | cmake-build-debug/ 33 | cmake-build-release/ 34 | *.iws 35 | *.iml 36 | out/ 37 | .idea_modules/ 38 | atlassian-ide-plugin.xml 39 | com_crashlytics_export_strings.xml 40 | crashlytics.properties 41 | crashlytics-build.properties 42 | fabric.properties 43 | target/ 44 | pom.xml.tag 45 | pom.xml.releaseBackup 46 | pom.xml.versionsBackup 47 | pom.xml.next 48 | release.properties 49 | dependency-reduced-pom.xml 50 | buildNumber.properties 51 | .mvn/timing.properties 52 | !/.mvn/wrapper/maven-wrapper.jar 53 | *_Practice.java 54 | -------------------------------------------------------------------------------- /src/main/java/com/ctci/arraysandstrings/IsUnique.java: -------------------------------------------------------------------------------- 1 | package com.ctci.arraysandstrings; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 18/11/2018 6 | */ 7 | public class IsUnique { 8 | 9 | private static boolean hasAllUniqueCharacters(String str) { 10 | if (str == null || str.length() > 128) return false; 11 | 12 | boolean[] charSet = new boolean[128]; // assuming the string contains only ASCII characters 13 | for (int i = 0; i < str.length(); i++) { 14 | int charVal = str.charAt(i); 15 | if (charSet[charVal]) { 16 | return false; 17 | } 18 | charSet[charVal] = true; 19 | } 20 | return true; 21 | } 22 | 23 | private static boolean hasAllUniqueCharactersWhenStringContainsAllLowercase(String s) { 24 | int checker = 0; 25 | for (int i = 0; i < s.length(); i++) { 26 | int charValue = s.charAt(i) - 'a'; 27 | if ((checker & (1 << charValue)) > 0) { 28 | return false; 29 | } 30 | checker |= (1 << charValue); 31 | } 32 | return true; 33 | } 34 | 35 | public static void main(String[] args) { 36 | String s = "ram"; 37 | System.out.println(hasAllUniqueCharacters(s)); 38 | s = "rama"; 39 | System.out.println(hasAllUniqueCharacters(s)); 40 | s = "ramA"; 41 | System.out.println(hasAllUniqueCharacters(s)); 42 | System.out.println("-------"); 43 | s = "ram"; 44 | System.out.println(hasAllUniqueCharactersWhenStringContainsAllLowercase(s)); 45 | s = "rama"; 46 | System.out.println(hasAllUniqueCharactersWhenStringContainsAllLowercase(s)); 47 | // not working as the input contains different cases 48 | s = "ramA"; 49 | System.out.println(hasAllUniqueCharactersWhenStringContainsAllLowercase(s)); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/ctci/arraysandstrings/RotateMatrix.java: -------------------------------------------------------------------------------- 1 | package com.ctci.arraysandstrings; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 2019-01-20 6 | */ 7 | public class RotateMatrix { 8 | 9 | public static void rotateImage(int[][] pixels) { 10 | 11 | } 12 | 13 | public static void main(String[] args) { 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/ctci/arraysandstrings/StringCompression.java: -------------------------------------------------------------------------------- 1 | package com.ctci.arraysandstrings; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 24/11/2018 6 | */ 7 | public class StringCompression { 8 | 9 | /** 10 | * Compresses the string {@code s} such that a string {@code aabccccaaa} becomes {@code a2b1c4a3}. 11 | * Also, if the compressed string is not shorter than the original, returns the original string. 12 | * 13 | * @param str input string containing only a-z characters, both cases 14 | * @return which ever is the shorter string 15 | */ 16 | private static String compressString(String str) { 17 | StringBuilder compressedSb = new StringBuilder(); 18 | int countConsecutive = 0; 19 | for (int i = 0; i < str.length(); i++) { 20 | countConsecutive++; 21 | 22 | /* If next character is different than current, append this char to result. */ 23 | if (i + 1 >= str.length() || str.charAt(i) != str.charAt(i + 1)) { 24 | compressedSb.append(str.charAt(i)); 25 | compressedSb.append(countConsecutive); 26 | countConsecutive = 0; 27 | } 28 | } 29 | return compressedSb.length() < str.length() ? compressedSb.toString() : str; 30 | } 31 | 32 | public static void main(String[] args) { 33 | System.out.println("aabccccaaa: " + compressString("aabccccaaa")); 34 | System.out.println("aabccccAAAA: " + compressString("aabccccAAAA")); 35 | System.out.println("abcd: " + compressString("abcd")); 36 | System.out.println("a: " + compressString("a")); 37 | System.out.println("aabcccccccccccccccccccccccccaaa: " + compressString("aabcccccccccccccccccccccccccaaa")); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/ctci/arraysandstrings/StringRotation.java: -------------------------------------------------------------------------------- 1 | package com.ctci.arraysandstrings; 2 | 3 | /** 4 | * Assume you have a method isSubString which checks if one word is a substring of another. Given two 5 | * strings, S1 and S2, write code to check if S2 is a rotation of S1 using only one call to isSubString 6 | * (e.g., "waterbottle" is a rotation of" erbottlewat"). 7 | * 8 | * @author rampatra 9 | * @since 2019-01-22 10 | */ 11 | public class StringRotation { 12 | 13 | private static boolean isStringRotation(String s1, String s2) { 14 | if (s1.length() != s2.length()) { 15 | return false; 16 | } 17 | s2 = s2 + s2; 18 | return isSubString(s1, s2); 19 | } 20 | 21 | /** 22 | * Given method in question. 23 | * 24 | * @param s1 first string 25 | * @param s2 second string 26 | * @return {@code true} if s1 is a substring of s2 or else {@code false} 27 | */ 28 | private static boolean isSubString(String s1, String s2) { 29 | return s2.contains(s1); 30 | } 31 | 32 | public static void main(String[] args) { 33 | System.out.println(isStringRotation("waterbottle", "erbottlewat")); // true 34 | System.out.println(isStringRotation("rampatra", "atraramp")); // true 35 | System.out.println(isStringRotation("rampatra", "arampata")); // false 36 | System.out.println(isStringRotation("rampatra", "arampat")); // false 37 | System.out.println(isStringRotation("", "")); // true 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/ctci/arraysandstrings/URLify.java: -------------------------------------------------------------------------------- 1 | package com.ctci.arraysandstrings; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 19/11/2018 6 | */ 7 | public class URLify { 8 | 9 | /** 10 | * We space encode the string such that all spaces in the string are replaced with '%20'. The string {@code str} 11 | * contains extra spaces to accommodate the extra characters. 12 | * 13 | * @param str string with spaces 14 | * @return string with spaces replaced with %20 15 | */ 16 | private static String urlify(String str) { 17 | char[] chars = str.toCharArray(); 18 | int curr = chars.length - 1; // we will start backwards so that we don't have to worry about characters we overwrite 19 | int insertIndex = curr; 20 | 21 | // move the curr pointer to the last character which isn't a space 22 | while (chars[curr] == 32) { 23 | curr--; 24 | } 25 | 26 | while (curr >= 0) { 27 | if (chars[curr] == 32) { 28 | chars[insertIndex--] = '0'; 29 | chars[insertIndex--] = '2'; 30 | chars[insertIndex--] = '%'; 31 | } else { 32 | chars[insertIndex--] = chars[curr]; 33 | } 34 | curr--; 35 | } 36 | return String.valueOf(chars); 37 | } 38 | 39 | public static void main(String[] args) { 40 | System.out.println(urlify("Mr John Smith ")); 41 | System.out.println(urlify("Mr Ram Patra ")); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/ctci/bitmanipulation/Debugger.java: -------------------------------------------------------------------------------- 1 | package com.ctci.bitmanipulation; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 2019-03-17 6 | */ 7 | public class Debugger { 8 | 9 | /** 10 | * If after un-setting the least significant bit in n, it becomes 0 then it implies that it has only set bit. This 11 | * can also imply that n is a power of 2. 12 | * 13 | * @param n input integer 14 | * @return {@code true} if n has only set bit, {@code false} otherwise. 15 | */ 16 | private static boolean hasOneSetBit(int n) { 17 | // edge case 18 | if (n == 0) { 19 | return false; 20 | } 21 | return (n & (n - 1)) == 0; // (n & (n - 1)) un-sets the least significant bit 22 | } 23 | 24 | public static void main(String[] args) { 25 | System.out.println(hasOneSetBit(0)); 26 | System.out.println(hasOneSetBit(2)); 27 | System.out.println(hasOneSetBit(16)); 28 | System.out.println(hasOneSetBit(10)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/ctci/bitmanipulation/PairwiseSwap.java: -------------------------------------------------------------------------------- 1 | package com.ctci.bitmanipulation; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 2019-03-18 6 | */ 7 | public class PairwiseSwap { 8 | 9 | /** 10 | * Write a program to swap odd and even bits in an integer with as few instructions as 11 | * possible (e.g., bit O and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on). 12 | * 13 | * Approach: 14 | * Shift the odd bits to the left, shift the even bits to the right, and finally, OR both the results. 15 | * Note: You can operate on only odd bits or only even bits by using the appropriate masks, for e.g., 16 | * 0x55555555 for odd bits and 0xaaaaaaaa for even bits. 17 | * 18 | * @param n an input integer. 19 | * @return an integer with even and odd bits swapped. 20 | */ 21 | private static int swapBits(int n) { 22 | return ((n & 0x55555555) << 1) | ((n & 0xaaaaaaaa) >>> 1); 23 | } 24 | 25 | public static void main(String[] args) { 26 | System.out.println("Input: " + Integer.toBinaryString(1569) + 27 | "\nOutput: " + Integer.toBinaryString(swapBits(1569))); 28 | 29 | assert Integer.toBinaryString(swapBits(1569)).equals("100100010010"); 30 | 31 | System.out.println("Input: " + Integer.toBinaryString(2680) + 32 | "\nOutput: " + Integer.toBinaryString(swapBits(2680))); 33 | 34 | assert Integer.toBinaryString(swapBits(2680)).equals("10110110100"); 35 | 36 | // fyi 37 | System.out.println(Integer.toBinaryString(0x55555555)); 38 | System.out.println(Integer.toBinaryString(0xaaaaaaaa)); 39 | } 40 | } -------------------------------------------------------------------------------- /src/main/java/com/ctci/linkedlists/Node.java: -------------------------------------------------------------------------------- 1 | package com.ctci.linkedlists; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 21/11/2018 6 | */ 7 | class Node { 8 | int val; 9 | Node next; 10 | 11 | Node(int val) { 12 | this.val = val; 13 | } 14 | 15 | public void print() { 16 | Node curr = this; 17 | while (curr.next != null) { 18 | System.out.print(curr.val + "->"); 19 | curr = curr.next; 20 | } 21 | System.out.println(curr.val); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/ctci/stacksandqueues/QueueViaStacks.java: -------------------------------------------------------------------------------- 1 | package com.ctci.stacksandqueues; 2 | 3 | import java.util.NoSuchElementException; 4 | import java.util.Stack; 5 | 6 | /** 7 | * Implement a queue using two stacks. No other data structures to be used. 8 | * 9 | * @author rampatra 10 | * @since 2019-02-06 11 | */ 12 | public class QueueViaStacks { 13 | 14 | private Stack stackFront = new Stack<>(); 15 | private Stack stackRear = new Stack<>(); 16 | 17 | private T add(T item) { 18 | return stackRear.push(item); 19 | } 20 | 21 | private T remove() { 22 | if (stackFront.empty() && stackRear.empty()) { 23 | throw new NoSuchElementException(); 24 | } else if (!stackFront.empty()) { 25 | return stackFront.pop(); 26 | } else { 27 | while (!stackRear.empty()) { 28 | stackFront.push(stackRear.pop()); 29 | } 30 | return stackFront.pop(); 31 | } 32 | } 33 | 34 | private void print() { 35 | Stack tempStack = new Stack<>(); 36 | while (!stackFront.empty()) { 37 | tempStack.push(stackFront.pop()); 38 | } 39 | System.out.print("["); 40 | tempStack.forEach(item -> System.out.print(item + ",")); 41 | stackRear.forEach(item -> System.out.print(item + ",")); 42 | System.out.println("]"); 43 | while (!tempStack.empty()) { 44 | stackFront.push(tempStack.pop()); 45 | } 46 | } 47 | 48 | public static void main(String[] args) { 49 | QueueViaStacks queue = new QueueViaStacks<>(); 50 | queue.add(1); 51 | queue.add(2); 52 | queue.add(3); 53 | queue.print(); 54 | queue.remove(); 55 | queue.print(); 56 | queue.remove(); 57 | queue.print(); 58 | queue.remove(); 59 | queue.print(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/ctci/stacksandqueues/SortStack.java: -------------------------------------------------------------------------------- 1 | package com.ctci.stacksandqueues; 2 | 3 | import java.util.Arrays; 4 | import java.util.Stack; 5 | 6 | /** 7 | * Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary 8 | * stack, but you may not copy the elements into any other data structure (such as an array). The stack supports the 9 | * following operations: push, pop, peek, and isEmpty. 10 | * 11 | * @author rampatra 12 | * @since 2019-02-08 13 | */ 14 | public class SortStack { 15 | 16 | private static void sortStack(Stack stack) { 17 | Stack tempStack = new Stack<>(); 18 | while (!stack.empty()) { 19 | tempStack.push(stack.pop()); 20 | } 21 | while (!tempStack.empty()) { 22 | Integer item = tempStack.pop(); 23 | if (stack.empty()) { 24 | stack.push(item); 25 | } else { 26 | while (!stack.empty() && item > stack.peek()) { 27 | tempStack.push(stack.pop()); 28 | } 29 | stack.push(item); 30 | } 31 | } 32 | } 33 | 34 | private static void printStack(Stack stack) { 35 | System.out.println(Arrays.toString(stack.toArray())); 36 | } 37 | 38 | public static void main(String[] args) { 39 | Stack unsortedStack = new Stack<>(); 40 | unsortedStack.push(2); 41 | unsortedStack.push(5); 42 | unsortedStack.push(1); 43 | unsortedStack.push(3); 44 | printStack(unsortedStack); 45 | sortStack(unsortedStack); 46 | printStack(unsortedStack); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/ctci/stacksandqueues/StackMin.java: -------------------------------------------------------------------------------- 1 | package com.ctci.stacksandqueues; 2 | 3 | import com.sun.tools.javac.util.Assert; 4 | 5 | import java.util.Stack; 6 | 7 | /** 8 | * How would you design a stack which, in addition to push and pop, has a function min 9 | * which returns the minimum element? Push, pop and min should all operate in 0(1) time. 10 | * 11 | * @author rampatra 12 | * @since 2019-02-04 13 | */ 14 | public class StackMin { 15 | 16 | // the main stack to do push, pop, and min operations 17 | private static Stack stack = new Stack<>(); 18 | // another stack to store the mins (needed to make min() call O(1)) 19 | private static Stack minStack = new Stack<>(); 20 | 21 | private static int push(int item) { 22 | minPush(item); 23 | return stack.push(item); 24 | } 25 | 26 | private static int pop() { 27 | minPop(stack.peek()); 28 | return stack.pop(); 29 | } 30 | 31 | private static int min() { 32 | return minStack.peek(); 33 | } 34 | 35 | private static void minPush(int item) { 36 | if (minStack.empty() || item <= minStack.peek()) { 37 | minStack.push(item); 38 | } 39 | } 40 | 41 | private static void minPop(int item) { 42 | if (item == minStack.peek()) { 43 | minStack.pop(); 44 | } 45 | } 46 | 47 | public static void main(String[] args) { 48 | push(2); 49 | push(5); 50 | push(1); 51 | push(1); 52 | push(6); 53 | push(8); 54 | Assert.check(min() == 1); 55 | pop(); 56 | pop(); 57 | pop(); 58 | Assert.check(min() == 1); 59 | pop(); 60 | Assert.check(min() == 2); 61 | } 62 | } -------------------------------------------------------------------------------- /src/main/java/com/ctci/treesandgraphs/GraphNode.java: -------------------------------------------------------------------------------- 1 | package com.ctci.treesandgraphs; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * @author rampatra 8 | * @since 2019-03-21 9 | */ 10 | public class GraphNode { 11 | int value; 12 | Set adjacent = new HashSet<>(); 13 | 14 | GraphNode(int value) { 15 | this.value = value; 16 | } 17 | } -------------------------------------------------------------------------------- /src/main/java/com/ctci/treesandgraphs/MinimalTree.java: -------------------------------------------------------------------------------- 1 | package com.ctci.treesandgraphs; 2 | 3 | /** 4 | * Given a sorted (increasing order) array with unique integer elements, write 5 | * an algorithm to create a binary search tree with minimal height. 6 | * 7 | * @author rampatra 8 | * @since 2019-02-15 9 | */ 10 | public class MinimalTree { 11 | 12 | private static TreeNode constructBSTWithMinimalHeight(int[] arr, int start, int end) { 13 | if (start > end) return null; 14 | 15 | int mid = (start + end) / 2; 16 | TreeNode root = new TreeNode(arr[mid]); 17 | root.left = constructBSTWithMinimalHeight(arr, start, mid - 1); 18 | root.right = constructBSTWithMinimalHeight(arr, mid + 1, end); 19 | return root; 20 | } 21 | 22 | private static void inOrderTraversal(TreeNode node) { 23 | if (node == null) return; 24 | 25 | inOrderTraversal(node.left); 26 | System.out.print("->" + node.val); 27 | inOrderTraversal(node.right); 28 | } 29 | 30 | public static void main(String[] args) { 31 | TreeNode root = constructBSTWithMinimalHeight(new int[]{1, 2, 3, 4, 5, 6, 7}, 0, 6); 32 | inOrderTraversal(root); 33 | System.out.println(); 34 | root = constructBSTWithMinimalHeight(new int[]{1, 2, 3, 4, 5, 6, 7, 8}, 0, 7); 35 | inOrderTraversal(root); 36 | System.out.println(); 37 | root = constructBSTWithMinimalHeight(new int[]{1, 2}, 0, 1); 38 | inOrderTraversal(root); 39 | System.out.println(); 40 | root = constructBSTWithMinimalHeight(new int[]{1}, 0, 0); 41 | inOrderTraversal(root); 42 | } 43 | } -------------------------------------------------------------------------------- /src/main/java/com/ctci/treesandgraphs/TreeNode.java: -------------------------------------------------------------------------------- 1 | package com.ctci.treesandgraphs; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 2019-02-15 6 | */ 7 | public class TreeNode { 8 | public int val; 9 | public TreeNode left; 10 | public TreeNode right; 11 | 12 | public TreeNode(int val) { 13 | this.val = val; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/arraysandsorting/InsertionSort1.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.arraysandsorting; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * User: rampatra 8 | * Date: 3/1/15 9 | * Time: 8:58 PM 10 | * To change this template go to Preferences | IDE Settings | File and Code Templates 11 | */ 12 | public class InsertionSort1 { 13 | 14 | static void insertIntoSorted(int[] ar) { 15 | int V = ar[ar.length - 1], i = ar.length - 2; 16 | 17 | for (; i >= 0; i--) { 18 | if (V < ar[i]) { 19 | ar[i + 1] = ar[i]; 20 | } else { 21 | break; 22 | } 23 | printArray(ar); 24 | } 25 | 26 | ar[i + 1] = V; 27 | printArray(ar); 28 | } 29 | 30 | /* Tail starts here */ 31 | public static void main(String[] args) { 32 | Scanner in = new Scanner(System.in); 33 | int s = in.nextInt(); 34 | int[] ar = new int[s]; 35 | for (int i = 0; i < s; i++) { 36 | ar[i] = in.nextInt(); 37 | } 38 | insertIntoSorted(ar); 39 | } 40 | 41 | private static void printArray(int[] ar) { 42 | for (int n : ar) { 43 | System.out.print(n + " "); 44 | } 45 | System.out.println(""); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/arraysandsorting/InsertionSort2.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.arraysandsorting; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * User: rampatra 8 | * Date: 3/1/15 9 | * Time: 9:42 PM 10 | * To change this template go to Preferences | IDE Settings | File and Code Templates 11 | */ 12 | public class InsertionSort2 { 13 | 14 | static void insertionSortPart2(int[] ar) { 15 | for (int i = 1; i < ar.length; i++) { 16 | int V = ar[i], j; 17 | /** 18 | * keep shifting no.s to right until 19 | * right place for insertion(of V) is found 20 | */ 21 | for (j = i - 1; j >= 0 && ar[j] > V; j--) { 22 | ar[j + 1] = ar[j]; 23 | } 24 | ar[j + 1] = V; 25 | printArray(ar); 26 | } 27 | } 28 | 29 | public static void main(String[] args) { 30 | Scanner in = new Scanner(System.in); 31 | int s = in.nextInt(); 32 | int[] ar = new int[s]; 33 | for (int i = 0; i < s; i++) { 34 | ar[i] = in.nextInt(); 35 | } 36 | insertionSortPart2(ar); 37 | 38 | } 39 | 40 | private static void printArray(int[] ar) { 41 | for (int n : ar) { 42 | System.out.print(n + " "); 43 | } 44 | System.out.println(""); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/arraysandsorting/IntroTutorial.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.arraysandsorting; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * User: rampatra 9 | * Date: 3/1/15 10 | * Time: 3:38 PM 11 | * To change this template go to Preferences | IDE Settings | File and Code Templates 12 | */ 13 | public class IntroTutorial { 14 | static int search(int searchVal, int[] arr) { 15 | return Arrays.binarySearch(arr, searchVal); 16 | } 17 | 18 | public static void main(String[] args) { 19 | Scanner in = new Scanner(System.in); 20 | 21 | int searchVal = in.nextInt(); 22 | int arrSize = in.nextInt(); 23 | int[] arr = new int[arrSize]; 24 | // as nextInt() doesn't read new line character 25 | in.nextLine(); 26 | String next = in.nextLine(); 27 | String[] next_split = next.split(" "); 28 | 29 | for (int _a_i = 0; _a_i < arrSize; _a_i++) { 30 | arr[_a_i] = Integer.parseInt(next_split[_a_i]); 31 | } 32 | 33 | System.out.print(search(searchVal, arr)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/arraysandsorting/LoopInvariant.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.arraysandsorting; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * User: rampatra 8 | * Date: 3/2/15 9 | * Time: 3:26 PM 10 | * To change this template go to Preferences | IDE Settings | File and Code Templates 11 | */ 12 | public class LoopInvariant { 13 | 14 | public static void insertionSort(int[] A) { 15 | for (int i = 1; i < A.length; i++) { 16 | int value = A[i]; 17 | int j = i - 1; 18 | while (j >= 0 && A[j] > value) { 19 | A[j + 1] = A[j]; 20 | j = j - 1; 21 | } 22 | A[j + 1] = value; 23 | } 24 | 25 | printArray(A); 26 | } 27 | 28 | 29 | static void printArray(int[] ar) { 30 | for (int n : ar) { 31 | System.out.print(n + " "); 32 | } 33 | } 34 | 35 | public static void main(String[] args) { 36 | Scanner in = new Scanner(System.in); 37 | int n = in.nextInt(); 38 | int[] ar = new int[n]; 39 | for (int i = 0; i < n; i++) { 40 | ar[i] = in.nextInt(); 41 | } 42 | insertionSort(ar); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/arraysandsorting/QuickSort1.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.arraysandsorting; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * User: rampatra 8 | * Date: 3/2/15 9 | * Time: 5:13 PM 10 | * To change this template go to Preferences | IDE Settings | File and Code Templates 11 | */ 12 | public class QuickSort1 { 13 | 14 | static void partition(int[] ar) { 15 | int pivot = ar[0], j = 0; 16 | int[] arCopy = ar.clone(); 17 | 18 | for (int i = 0; i < arCopy.length; i++) { 19 | if (arCopy[i] < pivot) ar[j++] = arCopy[i]; 20 | } 21 | for (int i = 0; i < arCopy.length; i++) { 22 | if (arCopy[i] >= pivot) ar[j++] = arCopy[i]; 23 | } 24 | printArray(ar); 25 | } 26 | 27 | static void printArray(int[] ar) { 28 | for (int n : ar) { 29 | System.out.print(n + " "); 30 | } 31 | System.out.println(""); 32 | } 33 | 34 | public static void main(String[] args) { 35 | Scanner in = new Scanner(System.in); 36 | int n = in.nextInt(); 37 | int[] ar = new int[n]; 38 | for (int i = 0; i < n; i++) { 39 | ar[i] = in.nextInt(); 40 | } 41 | partition(ar); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/arraysandsorting/QuickSort2.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.arraysandsorting; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * User: rampatra 8 | * Date: 3/3/15 9 | * Time: 1:05 PM 10 | * To change this template go to Preferences | IDE Settings | File and Code Templates 11 | */ 12 | public class QuickSort2 { 13 | 14 | static int partition(int[] a, int start, int end) { 15 | 16 | int pivot = start, temp; 17 | 18 | for (int i = start + 1; i <= end; i++) { 19 | // maintains the relative positioning of elements in each partition 20 | if (a[i] < a[pivot]) { 21 | start++; 22 | temp = a[i]; 23 | int j; 24 | for (j = i; j > start; j--) { 25 | a[j] = a[j - 1]; 26 | } 27 | a[j] = temp; 28 | } 29 | } 30 | 31 | temp = a[pivot]; 32 | while (pivot < start) { 33 | a[pivot] = a[pivot + 1]; 34 | pivot++; 35 | } 36 | a[pivot] = temp; 37 | 38 | return pivot; 39 | } 40 | 41 | static void quickSort(int[] ar, int start, int end) { 42 | if (start < end) { 43 | int p = partition(ar, start, end); 44 | quickSort(ar, start, p - 1); 45 | quickSort(ar, p + 1, end); 46 | for (int i = start; i <= end; i++) { 47 | System.out.print(ar[i] + " "); 48 | } 49 | System.out.println(); 50 | } 51 | } 52 | 53 | public static void main(String[] args) { 54 | Scanner in = new Scanner(System.in); 55 | int n = in.nextInt(); 56 | int[] ar = new int[n]; 57 | for (int i = 0; i < n; i++) { 58 | ar[i] = in.nextInt(); 59 | } 60 | quickSort(ar, 0, n - 1); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/arraysandsorting/RunningTime.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.arraysandsorting; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * User: rampatra 8 | * Date: 3/2/15 9 | * Time: 5:02 PM 10 | * To change this template go to Preferences | IDE Settings | File and Code Templates 11 | */ 12 | public class RunningTime { 13 | static void insertionSortPart2(int[] ar) { 14 | int c = 0; 15 | for (int i = 1; i < ar.length; i++) { 16 | int V = ar[i], j; 17 | for (j = i - 1; j >= 0 && ar[j] > V; j--, c++) { 18 | ar[j + 1] = ar[j]; 19 | } 20 | ar[j + 1] = V; 21 | //printArray(ar); 22 | } 23 | System.out.print(c); 24 | } 25 | 26 | public static void main(String[] args) { 27 | Scanner in = new Scanner(System.in); 28 | int s = in.nextInt(); 29 | int[] ar = new int[s]; 30 | for (int i = 0; i < s; i++) { 31 | ar[i] = in.nextInt(); 32 | } 33 | insertionSortPart2(ar); 34 | 35 | } 36 | 37 | private static void printArray(int[] ar) { 38 | for (int n : ar) { 39 | System.out.print(n + " "); 40 | } 41 | System.out.println(""); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/implementation/CavityMap.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.implementation; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by rampatra on 08/05/2016. 7 | */ 8 | public class CavityMap { 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int n = in.nextInt(); 12 | String grid[] = new String[n]; 13 | for (int grid_i = 0; grid_i < n; grid_i++) { 14 | grid[grid_i] = in.next(); 15 | } 16 | for (int i = 1; i < n - 1; i++) { 17 | for (int j = 1; j < n - 1; j++) { 18 | if (Character.getNumericValue(grid[i].charAt(j)) > Character.getNumericValue(grid[i].charAt(j - 1)) 19 | && Character.getNumericValue(grid[i].charAt(j)) > Character.getNumericValue(grid[i].charAt(j + 1)) 20 | && Character.getNumericValue(grid[i].charAt(j)) > Character.getNumericValue(grid[i - 1].charAt(j)) 21 | && Character.getNumericValue(grid[i].charAt(j)) > Character.getNumericValue(grid[i + 1].charAt(j))) { 22 | grid[i] = grid[i].substring(0, j) + "X" + grid[i].substring(j + 1); 23 | } 24 | } 25 | } 26 | for (int grid_i = 0; grid_i < n; grid_i++) { 27 | System.out.println(grid[grid_i]); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/implementation/ExtraLongFactorials.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.implementation; 2 | 3 | import java.math.BigInteger; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * Created by rampatra on 29/05/2016. 8 | */ 9 | public class ExtraLongFactorials { 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int n = in.nextInt(); 13 | BigInteger res = BigInteger.ONE; 14 | for (int i = n; i > 0; i--) { 15 | res = res.multiply(BigInteger.valueOf(i)); 16 | } 17 | System.out.println(res); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/implementation/TheTimeInWords.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.implementation; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by rampatra on 29/05/2016. 7 | */ 8 | public class TheTimeInWords { 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int h = in.nextInt(); 12 | int m = in.nextInt(); 13 | String timeInWords; 14 | String[] words = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", 15 | "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", 16 | "nineteen", "twenty", "twenty one", "twenty two", "twenty three", "twenty four", "twenty five", "twenty six", 17 | "twenty seven", "twenty eight", "twenty nine"}; 18 | 19 | if (m == 0) { 20 | timeInWords = words[h] + " o' clock"; 21 | } else if (m == 1) { 22 | timeInWords = words[m] + " minute past " + words[h]; 23 | } else if (m == 15) { 24 | timeInWords = "quarter past " + words[h]; 25 | } else if (m < 30) { 26 | timeInWords = words[m] + " minutes past " + words[h]; 27 | } else if (m == 30) { 28 | timeInWords = "half past " + words[h]; 29 | } else if (m == 45) { 30 | timeInWords = "quarter to " + words[(h == 12) ? h - 11 : h + 1]; 31 | } else if (60 - m == 1) { 32 | timeInWords = words[60 - m] + " minute to " + words[(h == 12) ? h - 11 : h + 1]; 33 | } else { 34 | timeInWords = words[60 - m] + " minutes to " + words[(h == 12) ? h - 11 : h + 1]; 35 | } 36 | System.out.println(timeInWords); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/recursion/RecursiveDigitSum.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.recursion; 2 | 3 | import java.io.BufferedWriter; 4 | import java.io.FileWriter; 5 | import java.io.IOException; 6 | import java.util.Scanner; 7 | 8 | /** 9 | * Recursive Digit Sum Problem. 10 | * 11 | * @link https://www.hackerrank.com/challenges/recursive-digit-sum/problem 12 | * @author rpatra16 13 | * @since 06/11/2018 14 | */ 15 | public class RecursiveDigitSum { 16 | 17 | /** 18 | * Finds the recursive digit sum of n. 19 | * 20 | * @param n number 21 | * @param k the number would be repeated k times 22 | * @return recursive sum of the digits 23 | */ 24 | private static int superDigit(String n, int k) { 25 | if (n.length() == 1 && k == 0) { 26 | return Integer.parseInt(n); 27 | } 28 | 29 | Long sum = 0L; 30 | char[] num = n.toCharArray(); 31 | for (int i = 0; i < num.length; i++) { 32 | sum += Long.parseLong(String.valueOf(num[i])); 33 | } 34 | 35 | if (k != 0) sum *= k; 36 | 37 | return superDigit(sum.toString(), 0); 38 | } 39 | 40 | private static final Scanner scanner = new Scanner(System.in); 41 | 42 | public static void main(String[] args) throws IOException { 43 | BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); 44 | 45 | String[] nk = scanner.nextLine().split(" "); 46 | 47 | String n = nk[0]; 48 | 49 | int k = Integer.parseInt(nk[1]); 50 | 51 | int result = superDigit(n, k); 52 | 53 | bufferedWriter.write(String.valueOf(result)); 54 | bufferedWriter.newLine(); 55 | 56 | bufferedWriter.close(); 57 | 58 | scanner.close(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/strings/AlternatingCharacters.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.strings; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * 8 | * @author rampatra 9 | * @since 10/22/15 10 | * @time: 9:24 AM 11 | */ 12 | public class AlternatingCharacters { 13 | 14 | public static int countDeletions(String s) { 15 | int count = 0, index = 0; 16 | for (int i = 1; i < s.length(); i++) { 17 | if (s.charAt(i) == s.charAt(index)) { 18 | count++; 19 | } else { 20 | index = i; 21 | } 22 | } 23 | return count; 24 | } 25 | 26 | public static void main(String[] args) { 27 | Scanner in = new Scanner(System.in); 28 | int t = Integer.parseInt(in.nextLine()); 29 | String[] input = new String[t]; 30 | for (int i = 0; i < t; i++) { 31 | input[i] = in.nextLine(); 32 | } 33 | for (int i = 0; i < t; i++) { 34 | System.out.println(countDeletions(input[i])); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/strings/MakingAnagrams.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.strings; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @author rampatra 7 | * @version 28/09/2016 8 | */ 9 | public class MakingAnagrams { 10 | 11 | /** 12 | * Find number of characters to be deleted to make {@param a} 13 | * and {@param b} anagrams. 14 | * See: https://www.hackerrank.com/challenges/making-anagrams 15 | * 16 | * @param a 17 | * @param b 18 | * @return 19 | */ 20 | public static int makeAnagrams(String a, String b) { 21 | 22 | int i = 0, j = 0, c = 0; 23 | char[] s1 = a.toCharArray(); 24 | char[] s2 = b.toCharArray(); 25 | Arrays.sort(s1); 26 | Arrays.sort(s2); 27 | 28 | while (i < s1.length || j < s2.length) { 29 | if (i >= s1.length) { 30 | c++; 31 | j++; 32 | } else if (j >= s2.length) { 33 | c++; 34 | i++; 35 | } else if (s1[i] < s2[j]) { 36 | c++; 37 | i++; 38 | } else if (s1[i] > s2[j]) { 39 | c++; 40 | j++; 41 | } else { 42 | i++; 43 | j++; 44 | } 45 | } 46 | 47 | return c; 48 | } 49 | 50 | public static void main(String[] args) { 51 | System.out.println(makeAnagrams("abc", "cde")); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/strings/PalindromeIndex.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.strings; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * User: rampatra 8 | * Date: 3/18/15 9 | * Time: 12:27 PM 10 | * To change this template go to Preferences | IDE Settings | File and Code Templates 11 | */ 12 | public class PalindromeIndex { 13 | 14 | static int makePalindrome(String s) { 15 | int index = -1, l = s.length(); 16 | if (isPalindrome(s)) { 17 | return -1; 18 | } 19 | for (int i = 0; i < l; i++) { 20 | StringBuilder sb = new StringBuilder(s); 21 | sb.deleteCharAt(i); 22 | String str = sb.toString(); 23 | if (isPalindrome(str)) { 24 | return i; 25 | } 26 | } 27 | return index; 28 | } 29 | 30 | static boolean isPalindrome(String s) { 31 | int l = s.length(), i, j; 32 | for (i = 0, j = l - 1; i < l / 2; i++, j--) { 33 | if ((int) s.charAt(i) != (int) s.charAt(j)) { 34 | return false; 35 | } 36 | } 37 | return true; 38 | } 39 | 40 | public static void main(String[] args) { 41 | Scanner in = new Scanner(System.in); 42 | 43 | int t = in.nextInt(); 44 | String s[] = new String[t]; 45 | 46 | for (int i = 0; i < t; i++) { 47 | s[i] = in.next(); 48 | } 49 | 50 | for (int i = 0; i < t; i++) { 51 | System.out.println(makePalindrome(s[i])); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/strings/Pangram.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.strings; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * 8 | * @author rampatra 9 | * @since 10/22/15 10 | * @time: 8:47 AM 11 | */ 12 | public class Pangram { 13 | 14 | public static String isPangram(String s) { 15 | 16 | char c; 17 | s = s.replaceAll("\\s+", ""); 18 | s = s.toUpperCase(); 19 | int[] alphabets = new int[26]; 20 | 21 | // check if all alphabets are present only once 22 | for (int i = 0; i < s.length(); i++) { 23 | c = s.charAt(i); 24 | if (alphabets[c - 65] == 0) { 25 | alphabets[c - 65] = 1; 26 | } 27 | } 28 | 29 | // check if all alphabets are present in string at least once 30 | for (int i = 0; i < alphabets.length; i++) { 31 | if (alphabets[i] == 0) return "not pangram"; 32 | } 33 | 34 | return "pangram"; 35 | } 36 | 37 | public static void main(String[] args) { 38 | Scanner in = new Scanner(System.in); 39 | String s = in.nextLine(); 40 | System.out.println(isPangram(s)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/strings/TwoStrings.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.strings; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * 8 | * @author rampatra 9 | * @since 10/22/15 10 | * @time: 10:08 AM 11 | */ 12 | public class TwoStrings { 13 | 14 | public static String isSubstringInBoth(String[] a) { 15 | char[] alphabets = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 16 | 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'z'}; 17 | 18 | for (int i = 0; i < alphabets.length; i++) { 19 | if (a[0].indexOf(alphabets[i]) != -1 && a[1].indexOf(alphabets[i]) != -1) return "YES"; 20 | } 21 | 22 | return "NO"; 23 | } 24 | 25 | public static void main(String[] args) { 26 | Scanner in = new Scanner(System.in); 27 | 28 | int t = Integer.parseInt(in.nextLine()); 29 | String[][] input = new String[t][2]; 30 | 31 | for (int i = 0; i < t; i++) { 32 | input[i][0] = in.nextLine(); 33 | input[i][1] = in.nextLine(); 34 | } 35 | 36 | for (int i = 0; i < t; i++) { 37 | System.out.println(isSubstringInBoth(input[i])); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/warmup/FlippingBits.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.warmup; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * User: rampatra 8 | * Date: 2/28/15 9 | * Time: 12:41 PM 10 | * To change this template go to Preferences | IDE Settings | File and Code Templates 11 | */ 12 | public class FlippingBits { 13 | 14 | static long flipBits(long i) { 15 | return i ^ 4294967295l; 16 | } 17 | 18 | public static void main(String[] args) { 19 | Scanner in = new Scanner(System.in); 20 | 21 | int t = Integer.parseInt(in.nextLine()); 22 | long[] in_ar = new long[t]; 23 | 24 | for (int i = 0; i < t; i++) { 25 | in_ar[i] = in.nextLong(); 26 | } 27 | 28 | for (long i : in_ar) { 29 | System.out.println(flipBits(i)); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/warmup/LonelyInteger.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.warmup; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Scanner; 6 | 7 | /** 8 | * Created by IntelliJ IDEA. 9 | * User: rampatra 10 | * Date: 2/28/15 11 | * Time: 12:16 PM 12 | * To change this template go to Preferences | IDE Settings | File and Code Templates 13 | */ 14 | public class LonelyInteger { 15 | 16 | static int lonelyInteger(int[] a) { 17 | 18 | Map map = new HashMap<>(); 19 | for (int i : a) { 20 | map.put(i, map.get(i) == null ? 1 : map.get(i) + 1); 21 | } 22 | 23 | for (Map.Entry entry : map.entrySet()) { 24 | if (entry.getValue() == 1) { 25 | return entry.getKey(); 26 | } 27 | } 28 | 29 | return 1; 30 | } 31 | 32 | public static void main(String[] args) { 33 | Scanner in = new Scanner(System.in); 34 | int res; 35 | 36 | int _a_size = Integer.parseInt(in.nextLine()); 37 | int[] _a = new int[_a_size]; 38 | int _a_item; 39 | String next = in.nextLine(); 40 | String[] next_split = next.split(" "); 41 | 42 | for (int _a_i = 0; _a_i < _a_size; _a_i++) { 43 | _a_item = Integer.parseInt(next_split[_a_i]); 44 | _a[_a_i] = _a_item; 45 | } 46 | 47 | res = lonelyInteger(_a); 48 | System.out.println(res); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/warmup/LoveLetterMystery.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.warmup; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * User: rampatra 8 | * Date: 3/17/15 9 | * Time: 3:22 PM 10 | * To change this template go to Preferences | IDE Settings | File and Code Templates 11 | */ 12 | public class LoveLetterMystery { 13 | static int calcPalindromeSteps(String s) { 14 | int steps = 0, length = s.length(), a, b; 15 | for (int i = 0, j = length - 1; i < length / 2; i++, j--) { 16 | if ((a = (int) s.charAt(i)) != (b = (int) s.charAt(j))) { 17 | steps += Math.abs(a - b); 18 | } 19 | } 20 | return steps; 21 | } 22 | 23 | public static void main(String[] args) { 24 | Scanner in = new Scanner(System.in); 25 | 26 | int t = in.nextInt(); 27 | String s[] = new String[t]; 28 | 29 | for (int i = 0; i < t; i++) { 30 | s[i] = in.next(); 31 | } 32 | 33 | for (int i = 0; i < t; i++) { 34 | System.out.println(calcPalindromeSteps(s[i])); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/warmup/MaximizingXor.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.warmup; 2 | 3 | import java.util.Scanner; 4 | import java.util.TreeSet; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * User: rampatra 9 | * Date: 3/7/15 10 | * Time: 11:07 AM 11 | * To change this template go to Preferences | IDE Settings | File and Code Templates 12 | */ 13 | public class MaximizingXor { 14 | 15 | static int maxXor(int l, int r) { 16 | TreeSet res = new TreeSet(); 17 | for (int i = l; i <= r; i++) { 18 | for (int j = i; j <= r; j++) { 19 | res.add(i ^ j); 20 | } 21 | } 22 | return (int) res.last(); 23 | } 24 | 25 | public static void main(String[] args) { 26 | Scanner in = new Scanner(System.in); 27 | int res; 28 | int _l; 29 | _l = Integer.parseInt(in.nextLine()); 30 | 31 | int _r; 32 | _r = Integer.parseInt(in.nextLine()); 33 | 34 | res = maxXor(_l, _r); 35 | System.out.println(res); 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/algorithms/warmup/UtopianTree.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.algorithms.warmup; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * User: rampatra 8 | * Date: 3/1/15 9 | * Time: 3:07 PM 10 | * To change this template go to Preferences | IDE Settings | File and Code Templates 11 | */ 12 | public class UtopianTree { 13 | static int calcHeight(int growthCycles) { 14 | int h = 1; 15 | 16 | for (int i = 1; i <= growthCycles; i++) { 17 | if (i % 2 != 0) 18 | h *= 2; 19 | else 20 | h += 1; 21 | } 22 | 23 | return h; 24 | } 25 | 26 | public static void main(String[] args) { 27 | Scanner in = new Scanner(System.in); 28 | 29 | int t = in.nextInt(); 30 | int n[] = new int[t]; 31 | 32 | for (int i = 0; i < t; i++) { 33 | n[i] = in.nextInt(); 34 | } 35 | 36 | for (int i = 0; i < t; i++) { 37 | System.out.println(calcHeight(n[i])); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/bitmanipulation/CounterGame.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.bitmanipulation; 2 | 3 | import java.math.BigInteger; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * 9 | * @author rampatra 10 | * @since 6/24/15 11 | * @time: 12:03 PM 12 | */ 13 | public class CounterGame { 14 | 15 | public static boolean isPowerOf2(BigInteger n) { 16 | return !n.equals(BigInteger.ZERO) && (n.and(n.subtract(BigInteger.ONE))).equals(BigInteger.ZERO); 17 | } 18 | 19 | public static BigInteger nextLowerPowerOf2(BigInteger n) { 20 | BigInteger p = BigInteger.ONE; 21 | while (p.compareTo(n) == -1) { 22 | p = p.shiftLeft(1); 23 | } 24 | return (n.compareTo(BigInteger.ONE) == 1) ? p.shiftRight(1) : n; // check for n = 0 or 1; 25 | } 26 | 27 | public static String computeWinner(BigInteger n) { 28 | boolean louiseTurn = true; 29 | while (!n.equals(BigInteger.ONE)) { 30 | if (isPowerOf2(n)) { 31 | n = n.shiftRight(1); 32 | } else { 33 | n = n.subtract(nextLowerPowerOf2(n)); 34 | } 35 | louiseTurn = !louiseTurn; 36 | } 37 | return (louiseTurn) ? "Richard" : "Louise"; 38 | } 39 | 40 | public static void main(String[] args) { 41 | Scanner in = new Scanner(System.in); 42 | 43 | int t = Integer.parseInt(in.nextLine()); 44 | BigInteger[] in_ar = new BigInteger[t]; 45 | 46 | for (int i = 0; i < t; i++) { 47 | in_ar[i] = in.nextBigInteger(); 48 | } 49 | 50 | for (BigInteger i : in_ar) { 51 | System.out.println(computeWinner(i)); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/bitmanipulation/TwosCompliment.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.bitmanipulation; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * 8 | * @author rampatra 9 | * @since 6/24/15 10 | * @time: 10:25 PM 11 | */ 12 | public class TwosCompliment { 13 | 14 | public static long countSetBitsInRange(int start, int end) { 15 | int count = 0; 16 | for (int i = start; i <= end; i++) { 17 | count += Integer.bitCount(i); 18 | } 19 | return count; 20 | } 21 | 22 | public static void main(String[] args) { 23 | Scanner in = new Scanner(System.in); 24 | 25 | int t = Integer.parseInt(in.nextLine()); 26 | String[][] in_ar = new String[t][2]; 27 | 28 | for (int i = 0; i < t; i++) { 29 | in_ar[i] = in.nextLine().split(" "); 30 | } 31 | 32 | for (String[] i : in_ar) { 33 | System.out.println(countSetBitsInRange(Integer.parseInt(i[0]), Integer.parseInt(i[1]))); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/interviewpreparation/arrays/DS2DArrayProblem.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.interviewpreparation.arrays; 2 | 3 | import java.io.BufferedWriter; 4 | import java.io.FileWriter; 5 | import java.io.IOException; 6 | import java.util.Scanner; 7 | 8 | /** 9 | * @author rpatra16 10 | * @since 31/10/2018 11 | */ 12 | public class DS2DArrayProblem { 13 | 14 | private static final Scanner scanner = new Scanner(System.in); 15 | 16 | private static int hourglassSum(int[][] arr) { 17 | int maxSum = Integer.MIN_VALUE; 18 | int hourglassSum; 19 | for (int i = 0; i < arr.length - 2; i++) { 20 | for (int j = 0; j < arr[0].length - 2; j++) { 21 | hourglassSum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + 22 | arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]; 23 | if (hourglassSum > maxSum) { 24 | maxSum = hourglassSum; 25 | } 26 | } 27 | } 28 | return maxSum; 29 | } 30 | 31 | public static void main(String[] args) throws IOException { 32 | BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); 33 | 34 | int[][] arr = new int[6][6]; 35 | 36 | for (int i = 0; i < 6; i++) { 37 | String[] arrRowItems = scanner.nextLine().split(" "); 38 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 39 | 40 | for (int j = 0; j < 6; j++) { 41 | int arrItem = Integer.parseInt(arrRowItems[j]); 42 | arr[i][j] = arrItem; 43 | } 44 | } 45 | 46 | int result = hourglassSum(arr); 47 | 48 | bufferedWriter.write(String.valueOf(result)); 49 | bufferedWriter.newLine(); 50 | 51 | bufferedWriter.close(); 52 | 53 | scanner.close(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/interviewpreparation/arrays/NewYearChaos.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.interviewpreparation.arrays; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * @author rpatra16 7 | * @since 02/11/2018 8 | */ 9 | public class NewYearChaos { 10 | 11 | /** 12 | * To solve this question, we just need to count the number of persons 13 | * that overtake a particular person. 14 | * 15 | * @param q the queue 16 | */ 17 | private static void minimumBribes(int[] q) { 18 | int bribes = 0; 19 | for (int i = q.length - 1; i >= 0; i--) { 20 | if (q[i] - i - 1 > 2) { 21 | System.out.println("Too chaotic"); 22 | return; 23 | } 24 | for (int j = Math.max(0, q[i] - 2); j < i; j++) { 25 | if (q[j] > q[i]) bribes++; 26 | } 27 | } 28 | System.out.println(bribes); 29 | } 30 | 31 | private static final Scanner scanner = new Scanner(System.in); 32 | 33 | public static void main(String[] args) { 34 | int t = scanner.nextInt(); 35 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 36 | 37 | for (int tItr = 0; tItr < t; tItr++) { 38 | int n = scanner.nextInt(); 39 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 40 | 41 | int[] q = new int[n]; 42 | 43 | String[] qItems = scanner.nextLine().split(" "); 44 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 45 | 46 | for (int i = 0; i < n; i++) { 47 | int qItem = Integer.parseInt(qItems[i]); 48 | q[i] = qItem; 49 | } 50 | 51 | minimumBribes(q); 52 | } 53 | 54 | scanner.close(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/interviewpreparation/warmup/JumpingClouds.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.interviewpreparation.warmup; 2 | 3 | import java.io.BufferedWriter; 4 | import java.io.FileWriter; 5 | import java.io.IOException; 6 | import java.util.Scanner; 7 | 8 | /** 9 | * @author rpatra16 10 | * @since 31/10/2018 11 | */ 12 | public class JumpingClouds { 13 | 14 | private static final Scanner scanner = new Scanner(System.in); 15 | 16 | private static int jumpingOnClouds(int[] c) { 17 | int jumps = 0; 18 | int i = 0; 19 | while (i < c.length) { 20 | if (((i + 2) < c.length) && c[i + 2] != 1) { 21 | i += 2; 22 | } else if (((i + 1) < c.length) && c[i + 1] != 1) { 23 | i += 1; 24 | } 25 | jumps++; 26 | if (i == c.length - 1) { 27 | break; 28 | } 29 | } 30 | return jumps; 31 | } 32 | 33 | public static void main(String[] args) throws IOException { 34 | BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); 35 | 36 | int n = scanner.nextInt(); 37 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 38 | 39 | int[] c = new int[n]; 40 | 41 | String[] cItems = scanner.nextLine().split(" "); 42 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 43 | 44 | for (int i = 0; i < n; i++) { 45 | int cItem = Integer.parseInt(cItems[i]); 46 | c[i] = cItem; 47 | } 48 | 49 | int result = jumpingOnClouds(c); 50 | 51 | bufferedWriter.write(String.valueOf(result)); 52 | bufferedWriter.newLine(); 53 | 54 | bufferedWriter.close(); 55 | 56 | scanner.close(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/interviewpreparation/warmup/RepeatedString.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.interviewpreparation.warmup; 2 | 3 | import java.io.BufferedWriter; 4 | import java.io.FileWriter; 5 | import java.io.IOException; 6 | import java.util.Scanner; 7 | 8 | /** 9 | * Repeated String problem. 10 | * 11 | * @author rpatra16 12 | * @since 29/10/2018 13 | */ 14 | public class RepeatedString { 15 | 16 | private static final Scanner scanner = new Scanner(System.in); 17 | 18 | private static long repeatedString(String s, long n) { 19 | int extraLetters; 20 | long totalCount = 0, count = 0, stringLength = s.length(); 21 | // count the no of a in non-repeated string 22 | for (int i = 0; i < stringLength; i++) { 23 | if (s.charAt(i) == 'a') { 24 | count++; 25 | } 26 | } 27 | totalCount += (n / stringLength * count); 28 | extraLetters = (int) (n % stringLength); 29 | // count the no of a in the remainder of the string 30 | for (int i = 0; i < extraLetters; i++) { 31 | if (s.charAt(i) == 'a') { 32 | totalCount++; 33 | } 34 | } 35 | return totalCount; 36 | } 37 | 38 | public static void main(String[] args) throws IOException { 39 | BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); 40 | 41 | String s = scanner.nextLine(); 42 | 43 | long n = scanner.nextLong(); 44 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 45 | 46 | long result = repeatedString(s, n); 47 | 48 | bufferedWriter.write(String.valueOf(result)); 49 | bufferedWriter.newLine(); 50 | 51 | bufferedWriter.close(); 52 | 53 | scanner.close(); 54 | } 55 | } 56 | 57 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/java/bignumber/BigDecimal.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.java.bignumber; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | 7 | /** 8 | * Problem Link: https://www.hackerrank.com/challenges/java-bigdecimal/ 9 | * 10 | * @author rampatra 11 | * @since 2019-06-22 12 | */ 13 | class BigDecimal { 14 | public static void main(String[] args) { 15 | //Input 16 | Scanner sc = new Scanner(System.in); 17 | int n = sc.nextInt(); 18 | String[] s = new String[n + 2]; 19 | for (int i = 0; i < n; i++) { 20 | s[i] = sc.next(); 21 | } 22 | sc.close(); 23 | 24 | //Write your code here 25 | s = Arrays.copyOfRange(s, 0, s.length - 2); 26 | List input = Arrays.asList(s); 27 | Arrays.sort(s, (s1, s2) -> { 28 | int compare = new java.math.BigDecimal(s2).compareTo(new java.math.BigDecimal(s1)); 29 | if (compare == 0) { 30 | return Integer.compare(input.indexOf(s1), input.indexOf(s2)); 31 | } 32 | return compare; 33 | }); 34 | 35 | //Output 36 | for (int i = 0; i < n; i++) { 37 | System.out.println(s[i]); 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/java/oops/JavaInheritance.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.java.oops; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 7/19/15 8 | * @time: 3:36 PM 9 | */ 10 | public class JavaInheritance { 11 | 12 | public void JavaInheritance() { 13 | 14 | } 15 | 16 | public static void main(String[] args) { 17 | 18 | } 19 | } 20 | 21 | 22 | class Arithmetic { 23 | 24 | } 25 | 26 | class Adder extends Arithmetic { 27 | int add(int a, int b) { 28 | return a + b; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/projecteuler/MultiplesOf3and5.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.projecteuler; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * 8 | * @author rampatra 9 | * @since 1/1/16 10 | * @time: 8:48 AM 11 | */ 12 | public class MultiplesOf3and5 { 13 | 14 | public static void main(String[] args) { 15 | Scanner in = new Scanner(System.in); 16 | 17 | int t = Integer.parseInt(in.nextLine()); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/hackerrank/tutorials/ctci/QueuesWithTwoStacks.java: -------------------------------------------------------------------------------- 1 | package com.hackerrank.tutorials.ctci; 2 | 3 | import java.util.Scanner; 4 | import java.util.Stack; 5 | 6 | /** 7 | * Question: https://www.hackerrank.com/challenges/ctci-queue-using-two-stacks 8 | * Level: Medium 9 | * 10 | * @author rampatra 11 | * @version 07/10/2016 12 | */ 13 | public class QueuesWithTwoStacks { 14 | 15 | public static class MyQueue { 16 | Stack stackNewestOnTop = new Stack(); 17 | Stack stackOldestOnTop = new Stack(); 18 | 19 | public void enqueue(T value) { // Push onto newest stack 20 | stackNewestOnTop.push(value); 21 | } 22 | 23 | public T peek() { 24 | return stackOldestOnTop.isEmpty() ? stackNewestOnTop.firstElement() : stackOldestOnTop.peek(); 25 | } 26 | 27 | public T dequeue() { 28 | if (stackOldestOnTop.isEmpty()) { 29 | while (!stackNewestOnTop.isEmpty()) { 30 | stackOldestOnTop.push(stackNewestOnTop.pop()); 31 | } 32 | } 33 | return stackOldestOnTop.pop(); 34 | } 35 | } 36 | 37 | 38 | public static void main(String[] args) { 39 | MyQueue queue = new MyQueue<>(); 40 | 41 | Scanner scan = new Scanner(System.in); 42 | int n = scan.nextInt(); 43 | 44 | for (int i = 0; i < n; i++) { 45 | int operation = scan.nextInt(); 46 | if (operation == 1) { // enqueue 47 | queue.enqueue(scan.nextInt()); 48 | } else if (operation == 2) { // dequeue 49 | queue.dequeue(); 50 | } else if (operation == 3) { // print/peek 51 | System.out.println(queue.peek()); 52 | } 53 | } 54 | scan.close(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/leetcode/arrays/MajorityElement.java: -------------------------------------------------------------------------------- 1 | package com.leetcode.arrays; 2 | 3 | /** 4 | * Level: Easy 5 | * Problem Link: https://leetcode.com/problems/majority-element/ 6 | * Problem Description: 7 | * Given an array of size n, find the majority element. The majority element is the element 8 | * that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the 9 | * majority element always exist in the array. 10 | * 11 | * @author rampatra 12 | * @since 2019-04-27 13 | */ 14 | public class MajorityElement { 15 | 16 | /** 17 | * Time complexity: O(n) 18 | * Runtime: 1 ms. 19 | * 20 | * @param nums 21 | * @return 22 | */ 23 | public static int majorityElement(int[] nums) { 24 | int count = 1; 25 | int majElem = nums[0]; 26 | 27 | for (int i = 1; i < nums.length; i++) { 28 | if (count <= 0) { 29 | majElem = nums[i]; 30 | count = 0; 31 | } 32 | if (majElem == nums[i]) { 33 | count++; 34 | } else { 35 | count--; 36 | } 37 | } 38 | 39 | return majElem; 40 | } 41 | 42 | public static void main(String[] args) { 43 | System.out.println(majorityElement(new int[]{10, 9, 9, 9, 10})); 44 | System.out.println(majorityElement(new int[]{2, 3, 2, 2, 3, 2})); 45 | System.out.println(majorityElement(new int[]{2, 3, 2, 2, 2, 3})); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/leetcode/arrays/PascalsTriangle.java: -------------------------------------------------------------------------------- 1 | package com.leetcode.arrays; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Level: Easy 8 | * Problem: https://leetcode.com/problems/pascals-triangle/ 9 | * 10 | * @author rampatra 11 | * @since 2019-04-20 12 | */ 13 | public class PascalsTriangle { 14 | 15 | /** 16 | * Time complexity: O(numRows^2) 17 | * Space complexity: O(numRows^2) 18 | *

19 | * Runtime: 0 ms. 20 | * 21 | * @param numRows 22 | * @return 23 | */ 24 | public static List> generatePascalsTriangle(int numRows) { 25 | List> pascalsTriangle = new ArrayList<>(); 26 | 27 | if (numRows == 0) return pascalsTriangle; 28 | 29 | List firstRow = new ArrayList<>(); 30 | firstRow.add(1); 31 | pascalsTriangle.add(firstRow); 32 | 33 | List prevRow; 34 | for (int i = 1; i < numRows; i++) { 35 | prevRow = pascalsTriangle.get(i - 1); 36 | 37 | List currRow = new ArrayList<>(); 38 | currRow.add(1); 39 | for (int j = 0; j < prevRow.size() - 1; j++) { 40 | currRow.add(prevRow.get(j) + prevRow.get(j + 1)); 41 | } 42 | currRow.add(1); 43 | 44 | pascalsTriangle.add(currRow); 45 | } 46 | 47 | return pascalsTriangle; 48 | } 49 | 50 | public static void main(String[] args) { 51 | System.out.println(generatePascalsTriangle(5)); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/leetcode/arrays/binarysearch/SearchInsertPosition.java: -------------------------------------------------------------------------------- 1 | package com.leetcode.arrays.binarysearch; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | /** 6 | * Level: Easy 7 | * Link: https://leetcode.com/problems/search-insert-position/ 8 | * Description: 9 | * Given a sorted array and a target value, return the index if the target is found. If not, return the index where it 10 | * would be if it were inserted in order. 11 | *

12 | * You may assume no duplicates in the array. 13 | *

14 | * Example 1: 15 | * Input: [1,3,5,6], 5 16 | * Output: 2 17 | *

18 | * Example 2: 19 | * Input: [1,3,5,6], 2 20 | * Output: 1 21 | *

22 | * Example 3: 23 | * Input: [1,3,5,6], 7 24 | * Output: 4 25 | *

26 | * Example 4: 27 | * Input: [1,3,5,6], 0 28 | * Output: 0 29 | *

30 | * Similar question: {@link SmallestLetterGreaterThanTarget}. 31 | * 32 | * @author rampatra 33 | * @since 2019-08-19 34 | */ 35 | public class SearchInsertPosition { 36 | 37 | /** 38 | * Runtime: 0 ms. 39 | * 40 | * @param nums 41 | * @param target 42 | * @return 43 | */ 44 | public static int searchInsert(int[] nums, int target) { 45 | int low = 0; 46 | int high = nums.length - 1; 47 | while (low <= high) { 48 | int mid = low + (high - low) / 2; 49 | if (nums[mid] == target) { 50 | return mid; 51 | } else if (nums[mid] < target) { 52 | low = mid + 1; 53 | } else { 54 | high = mid - 1; 55 | } 56 | } 57 | return low; 58 | } 59 | 60 | public static void main(String[] args) { 61 | assertEquals(2, searchInsert(new int[]{1, 2}, 3)); 62 | assertEquals(1, searchInsert(new int[]{1, 3, 5, 6}, 2)); 63 | } 64 | } -------------------------------------------------------------------------------- /src/main/java/com/leetcode/arrays/binarysearch/SqrtX.java: -------------------------------------------------------------------------------- 1 | package com.leetcode.arrays.binarysearch; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | /** 6 | * Level: Easy 7 | * Link: https://leetcode.com/problems/sqrtx/ 8 | * Description: 9 | * Implement int sqrt(int x). 10 | * 11 | * Compute and return the square root of x, where x is guaranteed to be a non-negative integer. 12 | * 13 | * Since the return type is an integer, the decimal digits are truncated and only the integer part 14 | * of the result is returned. 15 | * 16 | * Example 1: 17 | * Input: 4 18 | * Output: 2 19 | * 20 | * Example 2: 21 | * Input: 8 22 | * Output: 2 23 | * Explanation: The square root of 8 is 2.82842..., and since 24 | * the decimal part is truncated, 2 is returned. 25 | * 26 | * @author rampatra 27 | * @since 2019-08-19 28 | */ 29 | public class SqrtX { 30 | 31 | /** 32 | * Runtime: 1 ms. 33 | * 34 | * @param x 35 | * @return 36 | */ 37 | public static int mySqrt(int x) { 38 | if (x == 0 || x == 1) { 39 | return x; 40 | } 41 | long low = 1; 42 | long high = x / 2; 43 | 44 | while (low <= high) { 45 | long mid = low + (high - low) / 2; 46 | if (mid * mid == x) { 47 | return (int) mid; 48 | } else if (mid * mid < x) { 49 | low = mid + 1; 50 | } else { 51 | high = mid - 1; 52 | } 53 | } 54 | return (int) high; 55 | } 56 | 57 | public static void main(String[] args) { 58 | assertEquals(2, mySqrt(8)); 59 | assertEquals(3, mySqrt(9)); 60 | assertEquals(46339, mySqrt(2147395599)); 61 | } 62 | } -------------------------------------------------------------------------------- /src/main/java/com/leetcode/hashtables/ContainsDuplicates.java: -------------------------------------------------------------------------------- 1 | package com.leetcode.hashtables; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | /** 8 | * Level: Easy 9 | * Problem Link: https://leetcode.com/problems/contains-duplicate/ 10 | * 11 | * @author rampatra 12 | * @since 2019-04-24 13 | */ 14 | public class ContainsDuplicates { 15 | 16 | public static boolean containsDuplicates(int[] nums) { 17 | Set numSet = new HashSet<>(); 18 | for (int num : nums) { 19 | if (!numSet.add(num)) { 20 | return true; 21 | } 22 | } 23 | return false; 24 | } 25 | 26 | /** 27 | * Runtime: 5 ms. 28 | * 29 | * @param nums 30 | * @return 31 | */ 32 | public static boolean containsDuplicatesWithoutSet(int[] nums) { 33 | Arrays.sort(nums); 34 | for (int i = 0; i < nums.length - 1; i++) { 35 | if (nums[i] == nums[i + 1]) { 36 | return true; 37 | } 38 | } 39 | return false; 40 | } 41 | 42 | public static void main(String[] args) { 43 | System.out.println(containsDuplicates(new int[]{1, 2, 3, 1})); 44 | System.out.println(containsDuplicates(new int[]{1, 2, 3, 4})); 45 | 46 | System.out.println(containsDuplicatesWithoutSet(new int[]{1, 2, 3, 1})); 47 | System.out.println(containsDuplicatesWithoutSet(new int[]{1, 2, 3, 4})); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/leetcode/linkedlists/Node.java: -------------------------------------------------------------------------------- 1 | package com.leetcode.linkedlists; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 21/11/2018 6 | */ 7 | class Node { 8 | int val; 9 | Node next; 10 | 11 | Node(int val) { 12 | this.val = val; 13 | } 14 | 15 | public void print() { 16 | Node curr = this; 17 | while (curr.next != null) { 18 | System.out.print(curr.val + "->"); 19 | curr = curr.next; 20 | } 21 | System.out.println(curr.val); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/leetcode/math/ExcelSheetColumnNumber.java: -------------------------------------------------------------------------------- 1 | package com.leetcode.math; 2 | 3 | /** 4 | * Level: Easy 5 | * Problem Link: https://leetcode.com/problems/excel-sheet-column-number/ 6 | * Problem Description: 7 | * Given a column title as appear in an Excel sheet, return its corresponding column number. 8 | * 9 | * For example: 10 | * 11 | * A -> 1 12 | * B -> 2 13 | * C -> 3 14 | * ... 15 | * Z -> 26 16 | * AA -> 27 17 | * AB -> 28 18 | * ... 19 | * 20 | * Example 1: 21 | * Input: "A" 22 | * Output: 1 23 | * 24 | * Example 2: 25 | * Input: "AB" 26 | * Output: 28 27 | * 28 | * Example 3: 29 | * Input: "ZY" 30 | * Output: 701 31 | * 32 | * @author rampatra 33 | * @since 2019-05-31 34 | */ 35 | public class ExcelSheetColumnNumber { 36 | 37 | private static int titleToNumber(String title) { 38 | return 0; 39 | } 40 | 41 | public static void main(String[] args) { 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/leetcode/recursion/NestedInteger.java: -------------------------------------------------------------------------------- 1 | package com.leetcode.recursion; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Class needed for various problems like {@link NestedListWeightSumII}, {@link FlattenNestListIterator}, etc. 8 | * 9 | * @author rampatra 10 | * @since 2019-08-12 11 | */ 12 | public class NestedInteger { 13 | 14 | private Integer integer; 15 | private List list; 16 | 17 | public NestedInteger() { 18 | this.list = new ArrayList<>(); 19 | } 20 | 21 | public NestedInteger(int integer) { 22 | this.integer = integer; 23 | this.list = new ArrayList<>(); 24 | } 25 | 26 | public boolean isInteger() { 27 | return this.integer != null; 28 | } 29 | 30 | public Integer getInteger() { 31 | return integer; 32 | } 33 | 34 | public void setInteger(Integer integer) { 35 | this.integer = integer; 36 | } 37 | 38 | public List getList() { 39 | return list; 40 | } 41 | 42 | public NestedInteger add(NestedInteger nestedInteger) { 43 | this.list.add(nestedInteger); 44 | return this; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/leetcode/strings/CountAndSay.java: -------------------------------------------------------------------------------- 1 | package com.leetcode.strings; 2 | 3 | /** 4 | * Level: Easy 5 | * Problem: https://leetcode.com/problems/count-and-say/ 6 | * 7 | * @author rampatra 8 | * @since 2019-04-20 9 | */ 10 | public class CountAndSay { 11 | 12 | /** 13 | * Time complexity: 14 | * Runtime: 1 ms. 15 | * 16 | * @param n 17 | * @return 18 | */ 19 | public static String countAndSay(int n) { 20 | if (n == 1) return "1"; 21 | 22 | String s = countAndSay(n - 1); 23 | StringBuilder sb = new StringBuilder(); 24 | int count = 0; 25 | 26 | for (int i = 0; i < s.length(); i++) { 27 | count++; 28 | 29 | if (i + 1 >= s.length() || s.charAt(i) != s.charAt(i + 1)) { 30 | sb.append(count); 31 | sb.append(s.charAt(i)); 32 | count = 0; 33 | } 34 | } 35 | 36 | return sb.toString(); 37 | } 38 | 39 | public static void main(String[] args) { 40 | System.out.println(countAndSay(1)); 41 | System.out.println(countAndSay(2)); 42 | System.out.println(countAndSay(3)); 43 | System.out.println(countAndSay(4)); 44 | System.out.println(countAndSay(5)); 45 | System.out.println(countAndSay(6)); 46 | System.out.println(countAndSay(10)); 47 | } 48 | } -------------------------------------------------------------------------------- /src/main/java/com/leetcode/strings/LongestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | package com.leetcode.strings; 2 | 3 | /** 4 | * Level: Easy 5 | * Problem: https://leetcode.com/problems/longest-common-prefix/ 6 | * 7 | * @author rampatra 8 | * @since 2019-04-20 9 | */ 10 | public class LongestCommonPrefix { 11 | 12 | /** 13 | * Time complexity: O(r * c) 14 | * where, 15 | * r = no. of strings 16 | * c = max. no. of characters in a particular string 17 | *

18 | * Runtime: 1 ms. 19 | * 20 | * @param strs 21 | * @return 22 | */ 23 | public static String longestCommonPrefix(String[] strs) { 24 | if (strs == null || strs.length == 0) return ""; 25 | 26 | int row; 27 | for (int col = 0; col < strs[0].length(); col++) { 28 | for (row = 0; row < strs.length - 1; row++) { 29 | // once we find a different character under one column, return the characters read so far 30 | if (col == strs[row].length() 31 | || col == strs[row + 1].length() 32 | || strs[row].charAt(col) != strs[row + 1].charAt(col)) { 33 | return strs[row].substring(0, col); 34 | } 35 | } 36 | } 37 | 38 | return strs[0]; 39 | } 40 | 41 | public static void main(String[] args) { 42 | System.out.println(longestCommonPrefix(new String[]{})); 43 | System.out.println(longestCommonPrefix(new String[]{""})); 44 | System.out.println(longestCommonPrefix(new String[]{"a"})); 45 | System.out.println(longestCommonPrefix(new String[]{"flower", "flow", "flight"})); 46 | System.out.println(longestCommonPrefix(new String[]{"dog", "racecar", "car"})); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/leetcode/strings/RansomNote.java: -------------------------------------------------------------------------------- 1 | package com.leetcode.strings; 2 | 3 | /** 4 | * Level: Easy 5 | * Problem: https://leetcode.com/problems/ransom-note/ 6 | * 7 | * @author rampatra 8 | * @since 2019-04-19 9 | */ 10 | public class RansomNote { 11 | 12 | /** 13 | * Runtime: 4 ms/a>. 14 | * 15 | * @param ransomNote 16 | * @param magazine 17 | * @return 18 | */ 19 | public static boolean canConstruct(String ransomNote, String magazine) { 20 | char[] charCount = new char[26]; 21 | 22 | for (int i = 0; i < magazine.length(); i++) { 23 | charCount[magazine.charAt(i) - 'a']++; 24 | } 25 | 26 | for (int i = 0; i < ransomNote.length(); i++) { 27 | if (charCount[ransomNote.charAt(i) - 'a']-- == 0) { 28 | return false; 29 | } 30 | } 31 | return true; 32 | } 33 | 34 | public static void main(String[] args) { 35 | System.out.println(canConstruct("", "")); 36 | System.out.println(canConstruct("a", "a")); 37 | System.out.println(canConstruct("ab", "ab")); 38 | System.out.println(canConstruct("aab", "ab")); 39 | } 40 | } -------------------------------------------------------------------------------- /src/main/java/com/leetcode/strings/ReverseStringII.java: -------------------------------------------------------------------------------- 1 | package com.leetcode.strings; 2 | 3 | /** 4 | * Level: Easy 5 | * Problem: https://leetcode.com/problems/reverse-string-ii/ 6 | * 7 | * @author rampatra 8 | * @since 2019-04-20 9 | */ 10 | public class ReverseStringII { 11 | 12 | /** 13 | * Time complexity: O(n) 14 | * where, 15 | * n = no. of characters in string 16 | *

17 | * Runtime: 0 ms. 18 | * 19 | * @param str 20 | * @param k 21 | * @return 22 | */ 23 | public static String reverseStr(String str, int k) { 24 | char[] chars = str.toCharArray(); 25 | int len = str.length(); 26 | for (int i = 0; i < len; i += 2 * k) { 27 | reverse(chars, i, Math.min(len, i + k)); 28 | } 29 | return new String(chars); 30 | } 31 | 32 | private static void reverse(char[] chars, int start, int end) { 33 | char temp; 34 | for (int i = start, j = end - 1; i < j; i++, j--) { 35 | temp = chars[i]; 36 | chars[i] = chars[j]; 37 | chars[j] = temp; 38 | } 39 | } 40 | 41 | public static void main(String[] args) { 42 | System.out.println(reverseStr("abcdefg", 2)); 43 | System.out.println(reverseStr("abcdef", 2)); 44 | System.out.println(reverseStr("abcde", 2)); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/leetcode/strings/StringCompression.java: -------------------------------------------------------------------------------- 1 | package com.leetcode.strings; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 2019-04-16 6 | */ 7 | public class StringCompression { 8 | 9 | private static int compress(char[] chars) { 10 | return -1; 11 | } 12 | 13 | public static void main(String[] args) { 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/leetcode/strings/UniqueCharacterInString.java: -------------------------------------------------------------------------------- 1 | package com.leetcode.strings; 2 | 3 | /** 4 | * Level: Easy 5 | * Problem: https://leetcode.com/problems/first-unique-character-in-a-string/ 6 | * 7 | * @author rampatra 8 | * @since 2019-04-16 9 | */ 10 | public class UniqueCharacterInString { 11 | 12 | /** 13 | * Time complexity: O(n) 14 | * Runtime: 7 ms on leetcode. 15 | * 16 | * @param str the input string 17 | * @return the index of the first non-repeating character in {@code str}, {@code -1} otherwise. 18 | */ 19 | private static int findFirstUniqueCharacterInString(String str) { 20 | int[] charCount = new int[26]; 21 | 22 | for (int i = 0; i < str.length(); i++) { 23 | charCount[str.charAt(i) - 'a']++; 24 | } 25 | 26 | for (int i = 0; i < str.length(); i++) { 27 | if (charCount[str.charAt(i) - 'a'] == 1) { 28 | return i; 29 | } 30 | } 31 | return -1; 32 | } 33 | 34 | public static void main(String[] args) { 35 | System.out.println(findFirstUniqueCharacterInString("leetcode")); 36 | System.out.println(findFirstUniqueCharacterInString("loveleetcode")); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/leetcode/trees/TreeNode.java: -------------------------------------------------------------------------------- 1 | package com.leetcode.trees; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 2019-07-25 6 | */ 7 | public class TreeNode { 8 | 9 | int val; 10 | TreeNode left; 11 | TreeNode right; 12 | 13 | public TreeNode(int val) { 14 | this.val = val; 15 | } 16 | 17 | @Override 18 | public String toString() { 19 | return val + ""; 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/CountDivisors.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 31/05/2016 6 | */ 7 | public class CountDivisors { 8 | 9 | /** 10 | * Counts the number of integers in the range {@code begin} 11 | * and {@code end} that are divisible by {@code n}. 12 | * 13 | * @param begin 14 | * @param end 15 | * @param n 16 | * @return 17 | */ 18 | private static int countDivisorsInRange(int begin, int end, int n) { 19 | int b = end / n + 1; // From 0 to end the integers divisible by n 20 | int a = begin / n + 1; // From 0 to begin the integers divisible by n 21 | 22 | if (begin % n == 0) { // "begin" is inclusive; if divisible by n then 23 | --a; // remove 1 from "a" 24 | } 25 | return b - a; // return integers in range 26 | } 27 | 28 | public static void main(String[] args) { 29 | System.out.println(countDivisorsInRange(0, 0, 5)); 30 | System.out.println(countDivisorsInRange(1, 1, 5)); 31 | System.out.println(countDivisorsInRange(0, 1, 5)); 32 | System.out.println(countDivisorsInRange(0, 10, 5)); 33 | System.out.println(countDivisorsInRange(0, 2000000000, 5)); 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/CountSmallerElementsOnRHS.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * 8 | * @author rampatra 9 | * @since 9/19/15 10 | * @time: 11:33 PM 11 | */ 12 | public class CountSmallerElementsOnRHS { 13 | 14 | public static int[] getSmallerElementsCountOnRHSNaive(int[] a) { 15 | // TODO 16 | return null; 17 | } 18 | 19 | public static void main(String[] args) { 20 | System.out.println(Arrays.toString(getSmallerElementsCountOnRHSNaive(new int[]{12, 1, 2, 3, 0, 11, 4}))); 21 | System.out.println(Arrays.toString(getSmallerElementsCountOnRHSNaive(new int[]{5, 4, 3, 2, 1}))); 22 | System.out.println(Arrays.toString(getSmallerElementsCountOnRHSNaive(new int[]{1, 2, 3, 4, 5}))); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/DistinctPairs.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * Level: Easy 8 | * Problem Description: 9 | * Given an array and a target sum, return the number of distinct pairs whose sum is equal to the target sum. 10 | *

11 | * For Example, given an array [1, 2, 3, 6, 7, 8, 9, 1] and a target sum of 10, 12 | * the 7 pairs, i.e, (1, 9), (2, 8), (3, 7), (8, 2), (9, 1), (9, 1), and (1, 9) all sum to 10 but there are only 13 | * three distinct pairs, i.e, (1, 9), (2, 8), and (3, 7) so the answer would be 3. 14 | * 15 | * @author rampatra 16 | * @since 2019-06-03 17 | */ 18 | public class DistinctPairs { 19 | 20 | /** 21 | * Time complexity: O(n), n = size of the array 22 | * Space complexity: O(n) 23 | * 24 | * @param arr 25 | * @param targetSum 26 | * @return 27 | */ 28 | private static int numberOfDistinctPairs(int[] arr, int targetSum) { 29 | Set numSet = new HashSet<>(); 30 | Set> pairSet = new HashSet<>(); 31 | 32 | for (int i = 0; i < arr.length; i++) { 33 | if (numSet.contains(targetSum - arr[i])) { 34 | Set pair = new HashSet<>(); 35 | pair.add(arr[i]); 36 | pair.add(targetSum - arr[i]); 37 | pairSet.add(pair); 38 | } 39 | numSet.add(arr[i]); 40 | } 41 | 42 | return pairSet.size(); 43 | } 44 | 45 | public static void main(String[] args) { 46 | System.out.println(numberOfDistinctPairs(new int[]{1, 2, 3, 6, 7, 8, 9, 1}, 1)); 47 | System.out.println(numberOfDistinctPairs(new int[]{1, 2, 3, 6, 7, 8, 9, 1}, 2)); 48 | System.out.println(numberOfDistinctPairs(new int[]{1, 2, 3, 6, 7, 8, 9, 1}, 10)); 49 | } 50 | } -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/DuplicatesInArrayWithinKDistance.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * 9 | * @author rampatra 10 | * @since 10/18/15 11 | */ 12 | public class DuplicatesInArrayWithinKDistance { 13 | 14 | /** 15 | * Finds duplicates in an unsorted array {@code a} which are 16 | * only k distance apart from each other. 17 | * 18 | * @param a 19 | * @param k 20 | * @return 21 | */ 22 | public static int[] findDuplicatesInArrayWithinKDistance(int[] a, int k) { 23 | int index = 0; 24 | int[] duplicates = new int[a.length]; 25 | 26 | HashSet hashSet = new HashSet<>(); 27 | 28 | for (int i = 0; i < a.length; i++) { 29 | if (hashSet.contains(a[i])) { 30 | duplicates[index++] = a[i]; 31 | } else { 32 | hashSet.add(a[i]); 33 | } 34 | 35 | if (i >= k) { 36 | hashSet.remove(a[i - k]); 37 | } 38 | } 39 | 40 | return Arrays.copyOf(duplicates, index); 41 | } 42 | 43 | public static void main(String[] args) { 44 | System.out.println(Arrays.toString(findDuplicatesInArrayWithinKDistance(new int[]{1, 2, 8, 1, 3, 4, 5, 6, 6, 7}, 3))); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/EqualProbabilityRandomNoGenerator.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import java.util.Random; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * Given a random number generator f(n) which generates a random number 8 | * from {@code 0} (inclusive) to {@code n} (exclusive), design a method 9 | * which uses f(n) to generate non repeating random numbers from 10 | * {@code 0} (inclusive) to {@code n} (exclusive)? 11 | * 12 | * @author rampatra 13 | * @since 8/13/15 14 | * @time: 1:41 PM 15 | */ 16 | public class EqualProbabilityRandomNoGenerator { 17 | 18 | static int[] bucket; 19 | static int size; 20 | 21 | /** 22 | * The algorithm is to create a bucket of numbers and then to keep on 23 | * removing the elements from the bucket which are returned. 24 | * 25 | * @return 26 | */ 27 | public static int getRandom() { 28 | int random = f(size--); 29 | int result = bucket[random]; 30 | bucket[random] = bucket[size]; 31 | return result; 32 | } 33 | 34 | public static int f(int n) { 35 | return new Random().nextInt(n); 36 | } 37 | 38 | public static void main(String[] args) { 39 | Scanner in = new Scanner(System.in); 40 | 41 | System.out.println("How many random numbers you would like to generate?"); 42 | size = in.nextInt(); 43 | 44 | bucket = new int[size]; 45 | 46 | for (int i = 0; i < bucket.length; i++) { 47 | bucket[i] = i; 48 | } 49 | for (int i = 0; i < bucket.length; i++) { 50 | System.out.println(getRandom()); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/FixedPoint.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 9/8/15 8 | * @time: 11:34 PM 9 | */ 10 | public class FixedPoint { 11 | 12 | /** 13 | * Finds the FIXED POINT in an array {@param a} of n distinct integers sorted 14 | * in ascending order. If there is no fixed point it returns -1. 15 | * FIXED POINT in an array is an index i such that arr[i] is equal to i. Note that 16 | * integers in array can be negative. 17 | * 18 | * @param a 19 | * @return 20 | */ 21 | public static int findFixedPoint(int[] a) { 22 | int low = 0, high = a.length - 1, mid; 23 | while (low <= high) { 24 | mid = (low + high) / 2; 25 | if (a[mid] == mid) { 26 | return mid; 27 | } else if (a[mid] > mid) { 28 | high = mid - 1; 29 | } else { 30 | low = mid + 1; 31 | } 32 | } 33 | return -1; 34 | } 35 | 36 | public static void main(String[] args) { 37 | System.out.println(findFixedPoint(new int[]{-10, -5, 0, 3, 7})); 38 | System.out.println(findFixedPoint(new int[]{0, 2, 5, 8, 17})); 39 | System.out.println(findFixedPoint(new int[]{-10, -5, 3, 4, 7, 9})); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/FlattenArray.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class FlattenArray { 7 | 8 | /** 9 | * Given a nested array like [[1, 2], 3, [4]], return an array like [1, 2, 3, 4, 5]. 10 | * 11 | * @param nestedArray an Object array 12 | * @return a list of all elements in the nestedArray but all at the same level 13 | */ 14 | private static List flattenArray(Object[] nestedArray) { 15 | if (nestedArray == null || nestedArray.length == 0) return new ArrayList<>(); 16 | 17 | List flattenedArray = new ArrayList<>(); 18 | 19 | for (Object obj : nestedArray) { 20 | if (obj instanceof Object[]) { 21 | flattenedArray.addAll(flattenArray((Object[]) obj)); 22 | } else if (obj instanceof Integer) { 23 | flattenedArray.add((Integer) obj); 24 | } 25 | } 26 | 27 | return flattenedArray; 28 | } 29 | 30 | public static void main(String[] args) { 31 | System.out.println(flattenArray(null)); 32 | System.out.println(flattenArray(new Object[]{null})); 33 | System.out.println(flattenArray(new Object[]{new Object[]{}})); 34 | System.out.println(flattenArray(new Object[]{new Object[]{1, 2}})); 35 | System.out.println(flattenArray(new Object[]{1, 2, new Object[]{4, 5}, 6})); 36 | System.out.println(flattenArray(new Object[]{new Object[]{4, 5}, 1, 2, 6})); 37 | System.out.println(flattenArray(new Object[]{1, 2, 6, new Object[]{4, 5}})); 38 | } 39 | } -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/KLargestElements.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import com.rampatra.base.MinHeap; 4 | 5 | import java.util.Arrays; 6 | 7 | /** 8 | * Created by IntelliJ IDEA. 9 | * 10 | * @author rampatra 11 | * @since 8/3/15 12 | * @time: 3:47 PM 13 | */ 14 | public class KLargestElements { 15 | 16 | /** 17 | * Finds {@param k} largest elements in array {@param a}. 18 | *

19 | * Algorithm: 20 | * 1) Build a Min Heap MH of the first k elements (arr[0] to arr[k-1]) of the given array. This takes O(k) time. 21 | *

22 | * 2) For each element, after the kth element (arr[k] to arr[n-1]), compare it with root of MH. 23 | * ……a) If the element is greater than the root then make it root and call buildHeap for MH 24 | * ……b) Else ignore it. 25 | * This step takes (n-k) * O(k) time. 26 | *

27 | * 3) Finally, MH has k largest elements and root of the MH is the kth largest element. 28 | *

29 | * Therefore, the total time complexity of the above algorithm is: O(k) + (n-k) * O(k). 30 | * 31 | * @param a 32 | * @param k 33 | * @return 34 | */ 35 | public static int[] getKLargestElements(int[] a, int k) { 36 | 37 | int[] kElements = Arrays.copyOfRange(a, 0, k); 38 | 39 | MinHeap minHeap = new MinHeap(kElements); 40 | minHeap.buildMinHeap(); 41 | 42 | for (int i = k; i < a.length; i++) { 43 | if (a[i] > minHeap.findMin()) { 44 | minHeap.extractMin(); 45 | minHeap.insert(a[i]); 46 | } 47 | } 48 | 49 | return minHeap.getHeap(); 50 | } 51 | 52 | public static void main(String[] args) { 53 | System.out.println(Arrays.toString(getKLargestElements(new int[]{2, 3, 4, 1, 5, 7, 9}, 3))); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/KthLargestElement.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import com.rampatra.sorting.MergeSort; 4 | import com.rampatra.base.MaxHeap; 5 | 6 | import java.util.Arrays; 7 | 8 | /** 9 | * Created by IntelliJ IDEA. 10 | * 11 | * @author rampatra 12 | * @since 8/1/15 13 | * @time: 11:26 PM 14 | */ 15 | public class KthLargestElement { 16 | 17 | /** 18 | * Naive approach. 19 | *

20 | * Time complexity: O(n log n) 21 | * 22 | * @param a 23 | * @param k 24 | * @return 25 | */ 26 | public static int getKthLargestElementNaive(int[] a, int k) { 27 | if (k >= a.length) return -1; 28 | 29 | a = MergeSort.mergeSort(a); 30 | 31 | return a[a.length - k]; 32 | } 33 | 34 | /** 35 | * Determines the kth largest element by building a max heap 36 | * k times removing the root each time. 37 | * 38 | * @param a 39 | * @param k 40 | * @return 41 | */ 42 | public static int getKthLargestElement(int[] a, int k) { 43 | MaxHeap maxHeap = new MaxHeap(a); 44 | maxHeap.buildMaxHeap(); 45 | while (true) { 46 | if (k == 1) break; 47 | 48 | maxHeap.extractMax(); 49 | k--; 50 | } 51 | 52 | return maxHeap.findMax(); 53 | } 54 | 55 | public static void main(String[] args) { 56 | int[] ar = new int[]{2, 4, 5, 7, 1, 8, 9}; 57 | System.out.println(Arrays.toString(ar)); 58 | System.out.println(getKthLargestElementNaive(ar, 3)); 59 | System.out.println(Arrays.toString(ar)); 60 | System.out.println(getKthLargestElement(ar, 3)); 61 | System.out.println(Arrays.toString(ar)); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/LargestProductContiguousSubArray.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 5/28/15 8 | * @time: 12:44 PM 9 | */ 10 | public class LargestProductContiguousSubArray { 11 | 12 | /** 13 | * @param a 14 | * @return 15 | */ 16 | public static int getLargestProductContiguousSubArray(int[] a) { 17 | return 0; 18 | } 19 | 20 | public static void main(String[] args) { 21 | System.out.println(getLargestProductContiguousSubArray(new int[]{-2, 1, -3, 4, 5, -1, 4})); 22 | System.out.println(getLargestProductContiguousSubArray(new int[]{6, -3, -10, 0, 2})); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/LeadersInArray.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * 8 | * @author rampatra 9 | * @since 7/29/15 10 | * @time: 12:06 PM 11 | */ 12 | public class LeadersInArray { 13 | 14 | /** 15 | * Returns an array containing all leaders present in {@param a}. 16 | * An element is a LEADER if its greater than all elements to 17 | * the right of it in the array. 18 | * 19 | * @param a 20 | * @return 21 | */ 22 | public static int[] getAllLeaders(int[] a) { 23 | 24 | int i = a.length - 2, j = 0; 25 | int[] leaders = new int[a.length]; 26 | 27 | // rightmost element is always a leader 28 | leaders[0] = a[a.length - 1]; 29 | 30 | for (; i >= 0; i--) { 31 | if (a[i] > leaders[j]) { 32 | leaders[++j] = a[i]; 33 | } 34 | } 35 | 36 | // omit the extra space which aren't filled with leaders 37 | return Arrays.copyOfRange(leaders, 0, j + 1); 38 | } 39 | 40 | public static void main(String[] args) { 41 | System.out.println(Arrays.toString(getAllLeaders(new int[]{16, 17, 4, 3, 5, 2}))); 42 | System.out.println(Arrays.toString(getAllLeaders(new int[]{16, 1, 4, 3, 5, 12}))); 43 | System.out.println(Arrays.toString(getAllLeaders(new int[]{16, 15, 14, 13, 12, 10}))); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/MajorityElement.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | /** 4 | * The algorithm for finding a possible candidate 5 | * works in O(n) which is known as Moore’s Voting Algorithm. 6 | * Basic idea of the algorithm is if we cancel out each 7 | * occurrence of an element e with all the other elements 8 | * that are different from e then e will exist until end 9 | * if it is a majority element. 10 | *

11 | * Time Complexity: O(n) 12 | * Auxiliary Space : O(1) 13 | * 14 | * @author rampatra 15 | * @since 5/20/15 16 | */ 17 | public class MajorityElement { 18 | 19 | /** 20 | * Uses Moore’s Voting Algorithm to 21 | * get a candidate for majority element. 22 | * 23 | * @param a 24 | * @return 25 | */ 26 | public static int findCandidate(int[] a) { 27 | int candidate = a[0], count = 1; 28 | for (int i = 1; i < a.length; i++) { 29 | if (candidate == a[i]) { 30 | count++; 31 | } else { 32 | count--; 33 | } 34 | if (count == 0) { 35 | candidate = a[i]; 36 | count = 1; 37 | } 38 | } 39 | return candidate; 40 | } 41 | 42 | public static void majorityElement(int[] a) { 43 | int candidate = findCandidate(a), 44 | count = 0; 45 | 46 | // check if the candidate is really a majority element 47 | for (int i = 0; i < a.length; i++) { 48 | if (candidate == a[i]) { 49 | count++; 50 | } 51 | } 52 | if (count > a.length / 2) { 53 | System.out.print(candidate); 54 | } else { 55 | System.out.print("NONE"); 56 | } 57 | } 58 | 59 | public static void main(String[] args) { 60 | majorityElement(new int[]{1, 6, 2, 2, 2, 1, 2, 2, 7, 2}); 61 | } 62 | } -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/MaxDiffWithLargerElementAfterSmallerElement.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 8/12/15 8 | * @time: 5:40 PM 9 | */ 10 | public class MaxDiffWithLargerElementAfterSmallerElement { 11 | 12 | /** 13 | * Finds the difference between any two elements such that larger 14 | * element appears after the smaller number in array {@param a}. 15 | *

16 | * Example: 17 | * If array is [2, 3, 10, 6, 4, 8, 1] then returned value should be 8 (Diff between 10 and 2). 18 | * If array is [ 7, 9, 5, 6, 3, 2 ] then returned value should be 2 (Diff between 7 and 9). 19 | * 20 | * @param a 21 | * @return 22 | */ 23 | public static int getMaxDiffWithLargerElementAfterSmallerElement(int[] a) { 24 | int minElement = a[0], maxDiff = a[1] - a[0]; 25 | 26 | for (int i = 1; i < a.length; i++) { 27 | if (a[i] < minElement) { 28 | minElement = a[i]; 29 | } 30 | if (a[i] - minElement > maxDiff) { 31 | maxDiff = a[i] - minElement; 32 | } 33 | } 34 | 35 | return maxDiff; 36 | } 37 | 38 | public static void main(String[] args) { 39 | System.out.println(getMaxDiffWithLargerElementAfterSmallerElement(new int[]{2, 1, 4, 5, 10, 0})); 40 | System.out.println(getMaxDiffWithLargerElementAfterSmallerElement(new int[]{2, -6, 4, 5, 10, 1})); 41 | System.out.println(getMaxDiffWithLargerElementAfterSmallerElement(new int[]{-2, -6, -4, -5, -10, -1})); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/MaxMinWithMinComparisons.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * 8 | * @author rampatra 9 | * @since 7/31/15 10 | * @time: 3:16 PM 11 | */ 12 | public class MaxMinWithMinComparisons { 13 | 14 | /** 15 | * Finds the minimum and maximum number in array {@param a} 16 | * with minimum no. of comparisons. 17 | *

18 | * If length of array is even: 19 | * No. of comparisons = 1+3*(n-2)/2 20 | * and if length is odd: 21 | * No. of comparisons = 3*(n-1)/2 22 | * 23 | * @param a 24 | * @return 25 | */ 26 | public static int[] getMaxMinWithMinComparisons(int[] a) { 27 | int min, max, i; 28 | 29 | if (a.length % 2 == 0) { // this is not a comparison 30 | if (a[0] < a[1]) { // this is a comparison 31 | min = a[0]; 32 | max = a[1]; 33 | } else { 34 | min = a[1]; 35 | max = a[0]; 36 | } 37 | i = 2; 38 | } else { 39 | min = max = a[0]; 40 | i = 1; 41 | } 42 | 43 | for (; i < a.length - 1; i += 2) { 44 | if (a[i] < a[i + 1]) { // 1st comparison 45 | if (a[i] < min) min = a[i]; // 2nd comparison 46 | if (a[i + 1] > max) max = a[i + 1]; // 3rd comparison 47 | } else { 48 | if (a[i] > max) max = a[i]; // 2nd comparison 49 | if (a[i + 1] < min) min = a[i + 1]; // 3rd comparison 50 | } 51 | } 52 | 53 | return new int[]{min, max}; 54 | } 55 | 56 | public static void main(String[] args) { 57 | System.out.println(Arrays.toString(getMaxMinWithMinComparisons(new int[]{2, 5, 1, 6, 7, 9, 0, 8, 10}))); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/MaxSpan.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import com.sun.tools.javac.util.Assert; 4 | 5 | /** 6 | * Consider the leftmost and rightmost appearances of some value in an array. We'll say that the "span" is the 7 | * number of elements between the two inclusive. A single value has a span of 1. Returns the largest span found 8 | * in the given array. 9 | *

10 | * Examples: 11 | * maxSpan([1, 2, 1, 1, 3]) → 4 12 | * maxSpan([1, 4, 2, 1, 4, 1, 4]) → 6 13 | * maxSpan([1, 4, 2, 1, 4, 4, 4]) → 6 14 | *

15 | * Level: Easy 16 | * 17 | * @author rampatra 18 | * @link https://codingbat.com/prob/p189576 19 | * @since 2019-01-23 20 | */ 21 | public class MaxSpan { 22 | 23 | public static int maxSpan(int[] nums) { 24 | if (nums.length == 0) return 0; 25 | int largestSpan = 1; 26 | for (int i = 0; i < nums.length; i++) { 27 | for (int j = nums.length - 1; j > i; j--) { 28 | if (nums[i] == nums[j]) { 29 | if (j - i + 1 > largestSpan) { 30 | largestSpan = j - i + 1; 31 | } 32 | } 33 | } 34 | } 35 | return largestSpan; 36 | } 37 | 38 | public static void main(String[] args) { 39 | Assert.check(maxSpan(new int[]{1, 2, 1, 1, 3}) == 4); 40 | Assert.check(maxSpan(new int[]{1, 4, 2, 1, 4, 1, 4}) == 6); 41 | Assert.check(maxSpan(new int[]{1, 4, 2, 1, 4, 4, 4}) == 6); 42 | Assert.check(maxSpan(new int[]{1}) == 1); 43 | Assert.check(maxSpan(new int[]{}) == 0); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/MaximumSumNonAdjacentSubSequence.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 7/29/15 8 | * @time: 9:18 AM 9 | */ 10 | public class MaximumSumNonAdjacentSubSequence { 11 | 12 | /** 13 | * Given an array of positive numbers, finds the maximum sum of a sub-sequence 14 | * with the constraint that no 2 numbers in the sub-sequence should be adjacent 15 | * in the array. 16 | *

17 | * Example: 18 | * 1) 3 2 7 10 should return 13 (sum of 3 and 10) 19 | * 2) 3 2 5 10 7 should return 15 (sum of 3, 5 and 7). 20 | *

21 | * Here we maintain 2 variables incl and excl which is max sum till now (satisfying the constraint) 22 | * including the current element and excluding the current element respectively. 23 | * 24 | * @param a 25 | * @return 26 | */ 27 | public static int maximumSumNonAdjacentSubSequence(int[] a) { 28 | int incl = a[0], excl = 0, prevIncl = incl; // incl is max sum including the current element 29 | // and excl is max sum excluding the current element 30 | for (int i = 1; i < a.length; i++) { 31 | incl = excl + a[i]; // because we have to exclude the previous element if we consider the current element 32 | excl = Math.max(prevIncl, excl); // we are excluding the current element so we can consider the previous element or dont 33 | prevIncl = incl; 34 | } 35 | return Math.max(incl, excl); 36 | } 37 | 38 | public static void main(String[] args) { 39 | System.out.println(maximumSumNonAdjacentSubSequence(new int[]{3, 2, 7, 10})); 40 | System.out.println(maximumSumNonAdjacentSubSequence(new int[]{3, 2, 5, 10, 7})); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/MissingAndRepeatingElements.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * 8 | * @author rampatra 9 | * @since 9/7/15 10 | * @time: 10:54 AM 11 | */ 12 | public class MissingAndRepeatingElements { 13 | 14 | /** 15 | * Finds two numbers in an unsorted array of size n with elements in range from 16 | * 1 to n where one number from set {1, 2, …n} is missing and one number occurs 17 | * twice in array. 18 | * 19 | * @param a 20 | * @return an array where 1st element is the repeating element and 2nd is the missing one 21 | */ 22 | public static int[] findMissingAndRepeatingElements(int[] a) { 23 | int[] result = new int[2]; 24 | for (int i = 0; i < a.length; i++) { 25 | // we use indices to mark already encountered numbers 26 | if (a[Math.abs(a[i]) - 1] < 0) { 27 | result[0] = Math.abs(a[i]); // repeating element 28 | } else { 29 | a[Math.abs(a[i]) - 1] = -a[Math.abs(a[i]) - 1]; 30 | } 31 | } 32 | // no. is +ve means its index wasn't encountered 33 | for (int i = 0; i < a.length; i++) { 34 | if (a[i] > 0) { 35 | result[1] = i + 1; // missing element 36 | } 37 | } 38 | return result; 39 | } 40 | 41 | public static void main(String[] args) { 42 | System.out.println(Arrays.toString(findMissingAndRepeatingElements(new int[]{3, 1, 3}))); 43 | System.out.println(Arrays.toString(findMissingAndRepeatingElements(new int[]{4, 3, 6, 2, 1, 1}))); 44 | System.out.println(Arrays.toString(findMissingAndRepeatingElements(new int[]{4, 4, 6, 2, 5, 1}))); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/MissingNumber.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 5/28/15 8 | * @time: 4:34 PM 9 | */ 10 | 11 | /** 12 | * You are given a list of n-1 integers and these integers are in the 13 | * range of 1 to n. There are no duplicates in list. One of the integers 14 | * is missing in the list. Write an efficient code to find the missing integer. 15 | */ 16 | public class MissingNumber { 17 | 18 | public static int missingNumber(int a[], int n) { 19 | int sum = n * (n + 1) / 2; 20 | int arraySum = 0; 21 | 22 | for (int i = 0; i < a.length; i++) { 23 | arraySum += a[i]; 24 | } 25 | return sum - arraySum; 26 | } 27 | 28 | /** 29 | * Using XOR: 30 | * 1) XOR all the array elements, let the result of XOR be X1. 31 | * 2) XOR all numbers from 1 to n, let XOR be X2. 32 | * 3) XOR of X1 and X2 gives the missing number. 33 | * 34 | * @param a 35 | * @param n 36 | * @return 37 | */ 38 | public static int missingNumberUsingXOR(int a[], int n) { 39 | int nXOR = 0, arrayXOR = 0; 40 | 41 | for (int i = 1; i <= n; i++) { 42 | nXOR ^= i; 43 | } 44 | 45 | for (int i = 0; i < a.length; i++) { 46 | arrayXOR ^= a[i]; 47 | } 48 | return nXOR ^ arrayXOR; 49 | } 50 | 51 | public static void main(String[] args) { 52 | System.out.println("Missing No: " + missingNumber(new int[]{2, 3, 1, 4, 6, 7, 8}, 8)); 53 | System.out.println("Missing No using XOR: " + missingNumberUsingXOR(new int[]{2, 3, 1, 4, 6, 7, 8}, 8)); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/NumberOccurringOddTimes.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 5/20/15 8 | * @time: 11:09 PM 9 | */ 10 | 11 | import com.rampatra.bits.TwoNonRepeatingElements; 12 | 13 | /** 14 | * Given an array of positive integers. All numbers occur 15 | * even number of times except one number which occurs odd 16 | * number of times. Find the number in O(n) time & constant space. 17 | *

18 | * See {@link TwoNonRepeatingElements} for a more 19 | * complex problem which is solved in a similar approach. 20 | */ 21 | public class NumberOccurringOddTimes { 22 | 23 | public static int numberOccurringOddTimes(int a[]) { 24 | int res = a[0]; 25 | for (int i = 1; i < a.length; i++) { 26 | res ^= a[i]; 27 | } 28 | return res; 29 | } 30 | 31 | public static void main(String[] args) { 32 | System.out.print(numberOccurringOddTimes(new int[]{2, 3, 3, 3, 1, 2, 1})); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/ReverseArray.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * 8 | * @author rampatra 9 | * @since 7/27/15 10 | * @time: 8:40 PM 11 | */ 12 | public class ReverseArray { 13 | 14 | /** 15 | * Iterative method to reverse the entire array. 16 | * 17 | * @param a 18 | */ 19 | public static void reverse(int[] a) { 20 | int temp; 21 | for (int i = 0, j = a.length - 1; i < j; i++, j--) { 22 | // swap elements 23 | temp = a[i]; 24 | a[i] = a[j]; 25 | a[j] = temp; 26 | } 27 | } 28 | 29 | /** 30 | * Recursive method to reverse the array elements from 31 | * {@param i} index to {@param j} index (both inclusive). 32 | * 33 | * @param a 34 | * @param i 35 | * @param j 36 | */ 37 | public static void reverseRecursive(int[] a, int i, int j) { 38 | if (i > j) return; 39 | 40 | int temp = a[i]; 41 | a[i] = a[j]; 42 | a[j] = temp; 43 | reverseRecursive(a, ++i, --j); 44 | } 45 | 46 | public static void main(String[] args) { 47 | int[] ar = new int[]{1, 2, 3, 4, 5}; 48 | System.out.println(Arrays.toString(ar)); 49 | reverse(ar); 50 | System.out.println(Arrays.toString(ar)); 51 | reverseRecursive(ar, 0, ar.length - 1); 52 | System.out.println(Arrays.toString(ar)); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/RotateMatrixBy90Degrees.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 8/22/15 8 | * @time: 4:03 PM 9 | */ 10 | public class RotateMatrixBy90Degrees { 11 | 12 | /** 13 | * Rotates a 2-D array by 90 degrees clockwise. 14 | *

15 | * The algorithm is simple: 16 | * 1st row = last column 17 | * 2nd row = 2nd last column 18 | * and so on... 19 | * 20 | * @param a 21 | * @return 22 | */ 23 | public static int[][] rotateMatrixBy90DegreesRight(int[][] a) { 24 | int rows = a.length, columns = a[0].length; 25 | int[][] rotatedMatrix = new int[columns][rows]; 26 | 27 | for (int i = 0; --rows >= 0 && i < a.length; i++) { 28 | for (int j = 0; j < a[0].length; j++) { 29 | rotatedMatrix[j][rows] = a[i][j]; 30 | } 31 | } 32 | 33 | return rotatedMatrix; 34 | } 35 | 36 | private static void print2DMatrix(int[][] a) { 37 | for (int i = 0; i < a.length; i++) { 38 | for (int j = 0; j < a[0].length; j++) { 39 | System.out.print(a[i][j]); 40 | } 41 | System.out.println(); 42 | } 43 | } 44 | 45 | public static void main(String[] args) { 46 | int[][] ar = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; 47 | print2DMatrix(ar); 48 | System.out.println("--------"); 49 | print2DMatrix(rotateMatrixBy90DegreesRight(ar)); 50 | 51 | System.out.println("========"); 52 | 53 | ar = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {0, 5, 7}}; 54 | print2DMatrix(ar); 55 | System.out.println("--------"); 56 | print2DMatrix(rotateMatrixBy90DegreesRight(ar)); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/Segregate0sAnd1s.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * 8 | * @author rampatra 9 | * @since 7/31/15 10 | * @time: 5:13 PM 11 | */ 12 | public class Segregate0sAnd1s { 13 | 14 | /** 15 | * Segregate 0s and 1s by traversing the array only once. 16 | * 17 | * @param a 18 | */ 19 | public static void segregate0sAnd1s(int[] a) { 20 | for (int i = 0, j = a.length - 1; i < j; i++, j--) { 21 | if (a[i] > a[j]) { 22 | // swap if a[i] > a[j] 23 | a[i] = a[i] + a[j]; 24 | a[j] = a[i] - a[j]; 25 | a[i] = a[i] - a[j]; 26 | } 27 | } 28 | } 29 | 30 | public static void main(String[] args) { 31 | int[] ar = new int[]{0, 1, 1, 1, 0, 0, 1}; 32 | segregate0sAnd1s(ar); 33 | System.out.println(Arrays.toString(ar)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/SegregateEvenAndOddNos.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * 8 | * @author rampatra 9 | * @since 7/31/15 10 | * @time: 5:13 PM 11 | */ 12 | public class SegregateEvenAndOddNos { 13 | 14 | /** 15 | * Segregate even and odd numbers by traversing the 16 | * array {@param a} only once. 17 | *

18 | * This is similar to {@link Segregate0sAnd1s}. 19 | * 20 | * @param a 21 | */ 22 | public static void segregateEvenAndOddNos(int[] a) { 23 | for (int i = 0, j = a.length - 1; i < j; ) { 24 | if (a[i] % 2 != 0 && a[j] % 2 == 0) { 25 | // swap 26 | a[i] = a[i] + a[j]; 27 | a[j] = a[i] - a[j]; 28 | a[i] = a[i] - a[j]; 29 | i++; 30 | j--; 31 | } else if (a[i] % 2 == 0 && a[j] % 2 == 0) { 32 | i++; 33 | } else if (a[i] % 2 != 0 && a[j] % 2 != 0) { 34 | j--; 35 | } else { 36 | i++; 37 | j--; 38 | } 39 | } 40 | } 41 | 42 | public static void main(String[] args) { 43 | int[] ar = new int[]{12, 34, 45, 9, 8, 90, 3}; 44 | segregateEvenAndOddNos(ar); 45 | System.out.println(Arrays.toString(ar)); 46 | int[] ar1 = new int[]{34, 1, 45, 9, 8, 67, 3, 56, 78, 79, 101, 100}; 47 | segregateEvenAndOddNos(ar1); 48 | System.out.println(Arrays.toString(ar1)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/SmallestAndSecondSmallest.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * 8 | * @author rampatra 9 | * @since 7/30/15 10 | */ 11 | public class SmallestAndSecondSmallest { 12 | 13 | private static int[] getSmallestAndSecondSmallest(int[] a) { 14 | int smallest = Integer.MAX_VALUE, secondSmallest = Integer.MAX_VALUE; 15 | 16 | for (int i = 0; i < a.length; i++) { 17 | if (a[i] < smallest) { 18 | secondSmallest = smallest; 19 | smallest = a[i]; 20 | } else if (a[i] < secondSmallest && a[i] != smallest) { // a[i] != smallest; if numbers are repeated in array 21 | secondSmallest = a[i]; 22 | } 23 | } 24 | 25 | return new int[]{smallest, secondSmallest}; 26 | } 27 | 28 | public static void main(String[] args) { 29 | System.out.println(Arrays.toString(getSmallestAndSecondSmallest(new int[]{100, 1, 60, -10, -80, 85, 70, -80}))); 30 | System.out.println(Arrays.toString(getSmallestAndSecondSmallest(new int[]{100, 1, 60, 10, 80, 85, 70, 0}))); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/SubArrayOfSum.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 9/27/15 8 | * @time: 7:32 PM 9 | */ 10 | public class SubArrayOfSum { 11 | 12 | /** 13 | * Prints the sub-array in array {@param a} with sum {@param sum}. 14 | *

15 | * Algorithm: Keep on adding the elements, once the sum is larger 16 | * than the required sum start deleting the elements from the sum. 17 | * (Google Interview Question) 18 | * 19 | * @param a 20 | * @param sum 21 | */ 22 | public static void printSubArrayOfSum(int[] a, int sum) { 23 | int currSum = 0, startIndex = 0; 24 | for (int i = 0; i < a.length; i++) { 25 | 26 | currSum += a[i]; 27 | 28 | while (currSum > sum && startIndex < i) { 29 | currSum -= a[startIndex++]; 30 | } 31 | 32 | if (currSum == sum) { 33 | System.out.println("Sub-array lies between indexes: " + startIndex + " and " + i); 34 | return; 35 | } 36 | } 37 | System.out.println("Sub-array with sum " + sum + " not found!"); 38 | } 39 | 40 | public static void main(String[] args) { 41 | printSubArrayOfSum(new int[]{1, 4, 20, 3, 10, 5}, 33); 42 | printSubArrayOfSum(new int[]{1, 4, 20, 3, 10, 5}, 38); 43 | printSubArrayOfSum(new int[]{1, 4, 20, 3, 10, 5}, 13); 44 | printSubArrayOfSum(new int[]{1, 4, 0, 0, 3, 10, 5}, 0); 45 | printSubArrayOfSum(new int[]{1, 4}, 0); 46 | printSubArrayOfSum(new int[]{1, 4}, -4); 47 | printSubArrayOfSum(new int[]{1, -4}, -3); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/TripletOfSum.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import com.rampatra.sorting.QuickSort; 4 | 5 | import java.util.Arrays; 6 | 7 | /** 8 | * Created by IntelliJ IDEA. 9 | * 10 | * @author rampatra 11 | * @since 9/28/15 12 | * @time: 10:39 PM 13 | */ 14 | public class TripletOfSum { 15 | 16 | /** 17 | * Finds any 3 numbers in array {@param a} 18 | * whose sum is equal to {@param sum}. 19 | *

20 | * Time complexity: O(n^2) 21 | * 22 | * @param a 23 | * @param sum 24 | * @return 25 | */ 26 | public static int[] getTripletOfSum(int[] a, int sum) { 27 | 28 | QuickSort.quickSort(a); 29 | 30 | int len = a.length; 31 | for (int i = 0, j = i + 1, k = len - 1; i < len - 2; i++) { 32 | while (j < k) { 33 | if (a[i] + a[j] + a[k] == sum) { 34 | return new int[]{a[i], a[j], a[k]}; 35 | } else if (a[i] + a[j] + a[k] < sum) { 36 | j++; 37 | } else { 38 | k--; 39 | } 40 | } 41 | } 42 | return new int[]{-1}; 43 | } 44 | 45 | public static void main(String[] args) { 46 | System.out.println(Arrays.toString(getTripletOfSum(new int[]{12, 3, 4, 5, 1, 6, 9}, 24))); 47 | System.out.println(Arrays.toString(getTripletOfSum(new int[]{12, 3, 4, 5, 1, 6, 9}, 19))); 48 | System.out.println(Arrays.toString(getTripletOfSum(new int[]{1, 2, 3}, 6))); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/arrays/TwoElementsSumClosestToZero.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.arrays; 2 | 3 | import com.rampatra.sorting.QuickSort; 4 | 5 | import java.util.Arrays; 6 | 7 | /** 8 | * Created by IntelliJ IDEA. 9 | * 10 | * @author rampatra 11 | * @since 7/30/15 12 | * @time: 5:44 PM 13 | */ 14 | public class TwoElementsSumClosestToZero { 15 | 16 | /** 17 | * An array of integers is given containing both +ve and -ve numbers. You 18 | * need to find two elements such that their sum is closest to zero. 19 | * 20 | * @param a 21 | * @return 22 | */ 23 | public static int[] getTwoElementsWhoseSumIsClosestToZero(int[] a) { 24 | QuickSort.quickSort(a); 25 | 26 | int minDiff = Math.abs(0 - (a[0] + a[a.length - 1])), n1 = a[0], n2 = a[a.length - 1]; 27 | 28 | for (int i = 1, j = a.length - 2; i < j; ) { 29 | if (Math.abs(0 - (a[i] + a[j])) < minDiff) { 30 | minDiff = Math.abs(0 - (a[i] + a[j])); 31 | n1 = a[i]; 32 | n2 = a[j]; 33 | i++; 34 | } else { 35 | j--; 36 | } 37 | } 38 | 39 | return new int[]{n1, n2}; 40 | } 41 | 42 | public static void main(String[] args) { 43 | System.out.println(Arrays.toString(getTwoElementsWhoseSumIsClosestToZero(new int[]{1, 60, -10, -80, 85, 70}))); 44 | System.out.println(Arrays.toString(getTwoElementsWhoseSumIsClosestToZero(new int[]{-3, -100, -10, -80, 85, 70}))); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/base/AVLTree.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.base; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 4/25/15 8 | * @time: 10:25 AM 9 | */ 10 | public class AVLTree> extends Tree { 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/base/BinaryNode.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.base; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * User: rampatra 6 | * Date: 4/11/15 7 | * Time: 7:11 PM 8 | * To change this template go to Preferences | IDE Settings | File and Code Templates 9 | */ 10 | public class BinaryNode> { 11 | 12 | public E value; 13 | public BinaryNode left; 14 | public BinaryNode right; 15 | 16 | public BinaryNode(E value, BinaryNode left, BinaryNode right) { 17 | this.value = value; 18 | this.left = left; 19 | this.right = right; 20 | } 21 | 22 | public BinaryNode(BinaryNode node) { 23 | if (node == null) return; 24 | 25 | this.value = node.value; 26 | this.left = node.left; 27 | this.right = node.right; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/base/DoubleLinkedNode.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.base; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 6/18/15 8 | * @time: 2:42 PM 9 | */ 10 | public class DoubleLinkedNode> { 11 | 12 | public E item; 13 | public DoubleLinkedNode next; 14 | public DoubleLinkedNode prev; 15 | 16 | public DoubleLinkedNode(E item) { 17 | this(null, item, null); 18 | } 19 | 20 | public DoubleLinkedNode(DoubleLinkedNode prev, E item, DoubleLinkedNode next) { 21 | this.item = item; 22 | this.next = next; 23 | this.prev = prev; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/base/Graph.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.base; 2 | 3 | /** 4 | * A rudimentary Graph having all the basic methods. 5 | * 6 | * @author rampatra 7 | * @since 2019-02-10 8 | */ 9 | public class Graph> { 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/base/GraphNode.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.base; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * The class for a node in a graph. Ideally, you should make member variable {@code private} and have 8 | * getters, setters, etc. but to keep it simple, I have omitted all those boilerplate code. 9 | * 10 | * @author rampatra 11 | * @since 2019-02-10 12 | */ 13 | public class GraphNode> { 14 | public E value; 15 | public Set> adjacentNodes = new HashSet<>(); 16 | 17 | public GraphNode(E value) { 18 | this(value, null); 19 | } 20 | 21 | public GraphNode(E value, Set> adjacentNodes) { 22 | this.value = value; 23 | if (adjacentNodes != null) { 24 | this.adjacentNodes = adjacentNodes; 25 | } 26 | } 27 | 28 | @Override 29 | public boolean equals(Object o) { 30 | if (this == o) return true; 31 | if (o == null || getClass() != o.getClass()) return false; 32 | 33 | GraphNode graphNode = (GraphNode) o; 34 | 35 | return value.equals(graphNode.value); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/base/Queue.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.base; 2 | 3 | /** 4 | * A generic interface for a queue. 5 | * 6 | * @author rampatra 7 | * @since 4/12/15 8 | */ 9 | public interface Queue { 10 | 11 | 12 | /** 13 | * Inserts the specified element into this queue. 14 | * 15 | * @param item 16 | * @return 17 | */ 18 | public E add(E item); 19 | 20 | 21 | /** 22 | * Retrieves and removes the head of this queue. This method throws an 23 | * exception if this queue is empty. 24 | * 25 | * @return 26 | */ 27 | public E remove(); 28 | 29 | 30 | /** 31 | * Retrieves, but does not remove, the head of this queue. This method throws an 32 | * exception if this queue is empty. 33 | * 34 | * @return 35 | */ 36 | public E element(); 37 | 38 | 39 | /** 40 | * Returns the size of this queue. 41 | * 42 | * @return 43 | */ 44 | public int size(); 45 | 46 | 47 | /** 48 | * Tests whether the queue is empty or not. 49 | * 50 | * @return 51 | */ 52 | public boolean isEmpty(); 53 | 54 | 55 | /** 56 | * Prints the content of the queue. 57 | */ 58 | public void print(); 59 | 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/base/SingleLinkedNode.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.base; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 6/18/15 8 | * @time: 2:37 PM 9 | */ 10 | public class SingleLinkedNode> { 11 | 12 | public E item; 13 | public SingleLinkedNode next; 14 | 15 | public SingleLinkedNode(E item) { 16 | this(item, null); 17 | } 18 | 19 | public SingleLinkedNode(E item, SingleLinkedNode next) { 20 | this.item = item; 21 | this.next = next; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/base/Stack.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.base; 2 | 3 | /** 4 | * A generic interface for a stack. 5 | * 6 | * @author rampatra 7 | * @since 4/3/15 8 | */ 9 | public interface Stack { 10 | /** 11 | * Pushes an item onto the top of this stack. 12 | * 13 | * @param item 14 | */ 15 | public E push(E item); 16 | 17 | /** 18 | * Removes the object at the top of this stack and returns it. 19 | * This method throws an exception if this queue is empty. 20 | * 21 | * @return 22 | */ 23 | public E pop(); 24 | 25 | /** 26 | * Looks at the object at the top of this stack without 27 | * removing it from the stack. This method throws an 28 | * exception if this queue is empty. 29 | * 30 | * @return 31 | */ 32 | public E peek(); 33 | 34 | /** 35 | * Returns the number of items currently in the stack. 36 | * 37 | * @return 38 | */ 39 | public int size(); 40 | 41 | /** 42 | * Tests if this stack is empty. 43 | * 44 | * @return 45 | */ 46 | public boolean isEmpty(); 47 | 48 | /** 49 | * Prints the content of the stack. 50 | */ 51 | public void print(); 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/base/Tree.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.base; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * User: rampatra 6 | * Date: 4/19/15 7 | * Time: 6:30 PM 8 | * To change this template go to Preferences | IDE Settings | File and Code Templates 9 | */ 10 | public class Tree> { 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/bits/AbsWithoutBranching.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.bits; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 6/9/15 8 | * @time: 12:26 PM 9 | */ 10 | public class AbsWithoutBranching { 11 | 12 | /** 13 | * Returns the absolute value of any integer. 14 | *

15 | * EXPLANATION: 16 | * For example, consider int takes 4 bits: 17 | * So for input = -5, we have 18 | * -5 = 1011 19 | * mask = 1111 20 | * mask + n = 1010 21 | * (mask + n)^mask = 0101 (which is 5) 22 | * 23 | * @param n 24 | * @return 25 | */ 26 | public static int abs(int n) { 27 | int mask = n >> 31; 28 | return (mask + n) ^ mask; 29 | } 30 | 31 | public static void main(String[] args) { 32 | System.out.println(abs(-5)); 33 | System.out.println(abs(5)); 34 | System.out.println(abs(0)); 35 | System.out.println(abs(-0)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/bits/BinaryGap.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.bits; 2 | 3 | /** 4 | * Created by rampatra on 30/05/2016. 5 | */ 6 | public class BinaryGap { 7 | 8 | /** 9 | * A binary gap of a positive integer N is any maximal 10 | * sequence of consecutive zeros that is surrounded by ones 11 | * at both ends in the binary representation of N. 12 | * 13 | * @param n 14 | * @return 15 | */ 16 | public static int findBinaryGap(long n) { 17 | int gap = 0; 18 | int maxGap = 0; 19 | while (n > 0) { 20 | if ((n & 1) == 1) { 21 | while (n >>> 1 > 0 && (n >>> 1 & 1) == 0) { 22 | gap++; 23 | n = n >>> 1; 24 | } 25 | if (gap > maxGap) { 26 | maxGap = gap; 27 | } 28 | gap = 0; 29 | } 30 | n = n >>> 1; 31 | } 32 | 33 | return maxGap; 34 | } 35 | 36 | public static int findMaxNoOf0sBetweenTwo1s(long n) { 37 | return findBinaryGap(n); 38 | } 39 | 40 | public static void main(String[] args) { 41 | System.out.println(findBinaryGap(2)); 42 | System.out.println(findBinaryGap(8)); 43 | System.out.println(findBinaryGap(9)); 44 | System.out.println(findBinaryGap(16)); 45 | System.out.println(findBinaryGap(17)); 46 | System.out.println(findMaxNoOf0sBetweenTwo1s(121)); 47 | System.out.println(findMaxNoOf0sBetweenTwo1s(1041)); 48 | System.out.println(findMaxNoOf0sBetweenTwo1s(2_147_483_64889L)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/bits/BinaryString.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.bits; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 2019-03-21 6 | */ 7 | public class BinaryString { 8 | 9 | /** 10 | * Returns the binary representation of a {@code byte}. 11 | * 12 | * @param b a byte. 13 | * @return the binary representation of the input byte. 14 | */ 15 | private static String toBinaryString(byte b) { 16 | StringBuilder sb = new StringBuilder(); 17 | for (int i = 0; i < Byte.SIZE; i++) { 18 | sb.append(b & (byte) 1); 19 | b >>= 1; 20 | } 21 | return sb.reverse().toString(); 22 | } 23 | 24 | public static void main(String[] args) { 25 | System.out.println(toBinaryString((byte) 0xff)); 26 | System.out.println(toBinaryString((byte) (0xff >> 3))); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/bits/BooleanArrayPuzzle.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.bits; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * 8 | * @author rampatra 9 | * @since 6/12/15 10 | * @time: 3:31 PM 11 | */ 12 | public class BooleanArrayPuzzle { 13 | 14 | /** 15 | * Change 1 to 0 in an array of length 2 containing 16 | * one 0 and the other either 1 or 0. 17 | * 18 | * @param a 19 | * @return 20 | */ 21 | public static int[] change1To0InArray(int a[]) { 22 | a[a[1]] = a[a[0]]; 23 | return a; 24 | } 25 | 26 | public static void main(String[] args) { 27 | System.out.println(Arrays.toString(change1To0InArray(new int[]{0, 0}))); 28 | System.out.println(Arrays.toString(change1To0InArray(new int[]{0, 1}))); 29 | System.out.println(Arrays.toString(change1To0InArray(new int[]{1, 0}))); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/bits/ConvertAToB.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.bits; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 6/7/15 8 | * @time: 1:53 PM 9 | */ 10 | public class ConvertAToB { 11 | 12 | /** 13 | * Returns the number of bits required to be 14 | * flipped to convert {@param a} to {@param b}. 15 | * 16 | * @param a 17 | * @param b 18 | * @return 19 | */ 20 | public static int getBitsToConvertAToB(int a, int b) { 21 | return CountSetBits.countSetBits(a ^ b); 22 | } 23 | 24 | public static void main(String[] args) { 25 | System.out.println(getBitsToConvertAToB(3, 4)); 26 | System.out.println(getBitsToConvertAToB(3, 5)); 27 | System.out.println(getBitsToConvertAToB(5, 3)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/bits/CountSetBitsFromMinusNtoN.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.bits; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 7/22/15 8 | * @time: 12:42 PM 9 | */ 10 | public class CountSetBitsFromMinusNtoN { 11 | 12 | /** 13 | * Explanation: 14 | *

15 | * -3: 101 16 | * -2: 110 17 | * -1: 111 18 | * 0: 000 19 | * 1: 001 20 | * 2: 010 21 | * 3: 110 22 | *

23 | * If you fold the above representation between -1 and 0, the total no. of set bits from -3 to 2 24 | * will be equal to the total no. of bits in nos. from -3 to 2. 25 | * 26 | * @param n 27 | * @return 28 | */ 29 | public static int countSetBitsFromMinusNtoN(int n) { 30 | return n * 32 + CountSetBits.countSetBits((long) n); // 32 because int is of 32 bits in java 31 | } 32 | 33 | public static void main(String[] args) { 34 | System.out.println(countSetBitsFromMinusNtoN(3)); 35 | System.out.println(countSetBitsFromMinusNtoN(0)); 36 | System.out.println(countSetBitsFromMinusNtoN(9)); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/bits/FlippingBits.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.bits; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 6/5/15 8 | * @time: 3:50 PM 9 | */ 10 | public class FlippingBits { 11 | 12 | /** 13 | * Returns the number by flipping/inverting its bits using 14 | * XOR operation with 1......11 (size of int i.e, 32 1's). 15 | * 16 | * @param n 17 | * @return 18 | */ 19 | public static int getNumberByFlippingBits(int n) { 20 | return n ^ 0xffffffff; // equivalent to 11....1 (32 times) in binary 21 | } 22 | 23 | /** 24 | * Returns the number by flipping/inverting its bits using 25 | * the NOT operator. 26 | * 27 | * @param n 28 | * @return 29 | */ 30 | public static int getNumberByFlippingBits_V1(int n) { 31 | return ~n; 32 | } 33 | 34 | public static void main(String[] args) { 35 | System.out.println(getNumberByFlippingBits(5)); 36 | System.out.println(getNumberByFlippingBits_V1(5)); 37 | } 38 | } 39 | 40 | /** 41 | * EXPLANATION: 42 | *

43 | * For input: 5 44 | *

45 | * Binary: 000.....101 46 | * Inverted: 111.....010 (which is the 2's compliment of -6) 47 | *

48 | * Therefore, result is -6. 49 | */ 50 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/bits/IntegerOverflow.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.bits; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 6/4/15 8 | * @time: 4:28 PM 9 | */ 10 | public class IntegerOverflow { 11 | 12 | /** 13 | * Adds {@param a} and {@param b} and if the result can't 14 | * be stored as an integer it throws an exception 15 | * 16 | * @param a 17 | * @param b 18 | * @return 19 | */ 20 | public static int add(int a, int b) throws Exception { 21 | 22 | if (a > Integer.MAX_VALUE - b) { 23 | throw new Exception("Integer Overflow"); 24 | } else { 25 | return a + b; 26 | } 27 | } 28 | 29 | /** 30 | * Adds {@param a} and {@param b} and if the result can't 31 | * be stored as an integer it throws an exception 32 | * 33 | * @param a 34 | * @param b 35 | * @return 36 | */ 37 | public static int add_V1(int a, int b) throws Exception { 38 | 39 | if ((a > 0 && b > 0 && a + b < 0) || (a < 0 && b < 0 && a + b > 0)) { 40 | throw new Exception("Integer Overflow"); 41 | } else { 42 | return a + b; 43 | } 44 | } 45 | 46 | public static void main(String[] args) { 47 | try { 48 | System.out.println(add(2, 3)); 49 | System.out.println(add(2147483647, 999999999)); 50 | System.out.println(add(-2147483647, -999999999)); 51 | System.out.println(add_V1(2, 3)); 52 | System.out.println(add_V1(2147483647, 999999999)); 53 | System.out.println(add_V1(-2147483647, -999999999)); 54 | } catch (Exception e) { 55 | e.printStackTrace(); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/bits/LittleAndBigEndian.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.bits; 2 | 3 | import java.nio.ByteOrder; 4 | 5 | /** 6 | * Created by IntelliJ IDEA. 7 | * 8 | * @author rampatra 9 | * @since 6/5/15 10 | * @time: 3:10 PM 11 | * @link http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Data/endian.html 12 | */ 13 | public class LittleAndBigEndian { 14 | 15 | public static boolean isLittleEndian() { 16 | return ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN); 17 | } 18 | 19 | public static void main(String[] args) { 20 | System.out.println(isLittleEndian()); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/bits/Modulo.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.bits; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 6/8/15 8 | * @time: 11:28 PM 9 | */ 10 | public class Modulo { 11 | 12 | /** 13 | * Returns {@param n} modulo {@param d} provided 14 | * {@param d} is a power of 2. 15 | * 16 | * @param n 17 | * @param d 18 | * @return 19 | */ 20 | public static int getNmoduloD(int n, int d) { 21 | return n & (d - 1); 22 | } 23 | 24 | public static void main(String[] args) { 25 | System.out.println(getNmoduloD(18, 8)); 26 | System.out.println(getNmoduloD(18, 4)); 27 | System.out.println(getNmoduloD(13, 4)); 28 | System.out.println(getNmoduloD(13, 1)); 29 | System.out.println(getNmoduloD(2, 2)); 30 | System.out.println(getNmoduloD(13, 16)); 31 | } 32 | } 33 | 34 | /** 35 | * Consider example, for 18 % 8 36 | *

37 | * 18 = 10010 38 | * 7 = 00111 (8 = 2 ^ 3, therefore mask has to have three 1's) 39 | * 2 = 00010 (remainder = 18 & (8-1)) 40 | */ 41 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/bits/OppositeSign.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.bits; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 6/14/15 8 | * @time: 12:24 AM 9 | */ 10 | public class OppositeSign { 11 | 12 | public static int isOppositeSign(int a, int b) { 13 | return (a ^ b) >>> 31; 14 | } 15 | 16 | public static void main(String[] args) { 17 | System.out.println(isOppositeSign(-5, -3)); 18 | System.out.println(isOppositeSign(-5, 3)); 19 | System.out.println(isOppositeSign(5, -3)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/bits/PowerOf4.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.bits; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 6/9/15 8 | * @time: 12:56 PM 9 | */ 10 | public class PowerOf4 { 11 | 12 | /** 13 | * Determines whether any +ve number 14 | * is power of 4 or not. 15 | * 16 | * @param n 17 | * @return 18 | */ 19 | public static boolean isPowerOf4(int n) { 20 | int zeroBitCount = 0; 21 | // first check whether only 1 bit is set 22 | if (n > 0 && (n & (n - 1)) == 0) { 23 | // count no. of unset bits after the set bit 24 | while (n > 1) { 25 | zeroBitCount++; 26 | n >>= 1; 27 | } 28 | // if no. of unset bits are even then its a power of 4 29 | return zeroBitCount % 2 == 0; 30 | } 31 | return false; 32 | } 33 | 34 | public static void main(String[] args) { 35 | System.out.println(isPowerOf4(0)); 36 | System.out.println(isPowerOf4(1)); 37 | System.out.println(isPowerOf4(4)); 38 | System.out.println(isPowerOf4(16)); 39 | System.out.println(isPowerOf4(18)); 40 | System.out.println(isPowerOf4(64)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/bits/RotateBits.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.bits; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 6/8/15 8 | * @time: 5:12 PM 9 | *

10 | * A ROTATION (OR CIRCULAR SHIFT) is an operation similar to 11 | * shift except that the bits that fall off at one end are put 12 | * back to the other end. 13 | *

14 | * For example, 000…11100101 becomes 00..0011100101000 if the number 15 | * is rotated 3 times towards left and becomes 101000..0011100 if the 16 | * number is rotated 3 times towards right. 17 | */ 18 | public class RotateBits { 19 | 20 | public static int leftRotateBits(int n, int times) { 21 | return n << times | n >>> (32 - times); 22 | } 23 | 24 | public static int rightRotateBits(int n, int times) { 25 | return n >>> times | n << (32 - times); 26 | } 27 | 28 | public static void main(String[] args) { 29 | System.out.println(leftRotateBits(5, 3)); 30 | System.out.println(leftRotateBits(234324, 3)); 31 | System.out.println(rightRotateBits(5, 3)); 32 | System.out.println(rightRotateBits(234324, 3)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/bits/ShiftByNegativeNumber.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.bits; 2 | 3 | /** 4 | * Understanding shifting in Java. What happens when you shift a number by a negative number. 5 | * 6 | * @author rampatra 7 | * @link https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.19 8 | * @link https://stackoverflow.com/a/10516830/1385441 9 | * @since 18/11/2018 10 | */ 11 | public class ShiftByNegativeNumber { 12 | /** 13 | * These both are the same as in java if the left operand is int only the low five bits are considered 14 | * for shifting and if the left operand is a long then the low six bits are considered. 15 | * Binary representation of -2 is 11.....11110. The last 5 bits are 11110 which is 30. 16 | * 17 | * @param args 18 | */ 19 | public static void main(String[] args) { 20 | int v1 = 1 << -2; 21 | int v2 = 1 << 30; 22 | System.out.println(v1); 23 | System.out.println(v2); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/bits/SmallestOf3Integers.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.bits; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 6/12/15 8 | * @time: 6:18 PM 9 | */ 10 | public class SmallestOf3Integers { 11 | 12 | /** 13 | * Returns min of 2 numbers without using 14 | * any comparison operators. 15 | * 16 | * @param x 17 | * @param y 18 | * @return 19 | */ 20 | private static int min(int x, int y) { 21 | return y + ((x - y) & ((x - y) >> 31)); 22 | } 23 | 24 | /** 25 | * Returns the smallest element in an 26 | * array of length 3. 27 | * 28 | * @param a 29 | * @return 30 | */ 31 | public static int getSmallest(int a[]) { 32 | return min(a[0], min(a[1], a[2])); 33 | } 34 | 35 | /** 36 | * This method uses repeated subtraction to 37 | * find the smallest element in an array. 38 | * 39 | * @param a 40 | * @return 41 | */ 42 | public static int getSmallest_V1(int a[]) { 43 | int c = 0; 44 | while (a[0] > 0 && a[1] > 0 && a[2] > 0) { 45 | a[0]--; 46 | a[1]--; 47 | a[2]--; 48 | c++; 49 | } 50 | return c; 51 | } 52 | 53 | public static void main(String[] args) { 54 | System.out.println(getSmallest(new int[]{4, 5, 6})); 55 | System.out.println(getSmallest_V1(new int[]{4, 5, 6})); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/bits/SubBit.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.bits; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 6/4/15 8 | * @time: 10:54 PM 9 | */ 10 | public class SubBit { 11 | 12 | /** 13 | * Returns the number formed with the bits from {@param start} 14 | * and {@param end} of {@param num} (both inclusive). 15 | * 16 | * @param num 17 | * @param start > 0 and <= 32 18 | * @param end > 0 and <= 32 19 | * @return 20 | */ 21 | public static int getNumberFromSubBits(int num, int start, int end) { 22 | return num << (32 - end) >>> (start - end + 31); // more intuitive (start - 1 + 32 - end) 23 | } 24 | 25 | public static void main(String[] args) { 26 | System.out.println(getNumberFromSubBits(5, 1, 2)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/dynamicprogramming/FibonacciNumbers.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.dynamicprogramming; 2 | 3 | import java.util.Arrays; 4 | 5 | import static java.lang.System.out; 6 | 7 | /** 8 | * Created by IntelliJ IDEA. 9 | * 10 | * @author rampatra 11 | * @since 9/10/15 12 | */ 13 | public class FibonacciNumbers { 14 | 15 | /** 16 | * Computes first {@code k} fibonacci numbers using 17 | * bottom-up DP approach. 18 | *

19 | * Time complexity: O(k) 20 | * 21 | * @param k 22 | */ 23 | public static int[] getFirstKFibonacciNumbers(int k) { 24 | int[] fib = new int[k]; 25 | int i = 1; 26 | while (i < k) { 27 | if (i == 1 || i == 2) { 28 | fib[i] = 1; 29 | } else { 30 | fib[i] = fib[i - 1] + fib[i - 2]; 31 | } 32 | i++; 33 | } 34 | return fib; 35 | } 36 | 37 | public static void main(String[] args) { 38 | out.println(Arrays.toString(getFirstKFibonacciNumbers(0))); 39 | out.println(Arrays.toString(getFirstKFibonacciNumbers(10))); 40 | out.println(Arrays.toString(getFirstKFibonacciNumbers(46))); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/java8/DateTime.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.java8; 2 | 3 | import java.time.Instant; 4 | import java.time.LocalDateTime; 5 | import java.time.ZoneId; 6 | import java.util.Date; 7 | 8 | /** 9 | * @author rampatra 10 | * @since 2019-05-15 11 | */ 12 | public class DateTime { 13 | 14 | private static long getCurrentTimestampFromInstant() { 15 | return Instant.now().toEpochMilli(); 16 | } 17 | 18 | private static String addTwoDays() { 19 | LocalDateTime now = LocalDateTime.ofInstant(Instant.now(), ZoneId.of("UTC")); 20 | LocalDateTime afterTwoDays = now.plusDays(2); 21 | return afterTwoDays.getDayOfMonth() + "-" + afterTwoDays.getMonthValue() + "-" + afterTwoDays.getYear(); 22 | } 23 | 24 | public static void main(String[] args) { 25 | System.out.println("Timestamp from Instant: " + getCurrentTimestampFromInstant() + 26 | "\nTimestamp from Legacy Date: " + new Date().getTime()); 27 | System.out.println("Add Two days: " + addTwoDays()); 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/com/rampatra/java8/Lambdas.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.java8; 2 | 3 | import java.util.function.Consumer; 4 | 5 | /** 6 | * @author rampatra 7 | * @version 21/02/2017 8 | */ 9 | public class Lambdas { 10 | 11 | private int a = 1; 12 | 13 | public void testScopeOfLambda(Consumer consumer) { 14 | consumer.accept("Lambda"); 15 | } 16 | 17 | public static void main(String[] args) { 18 | Lambdas l = new Lambdas(); 19 | l.testScopeOfLambda(x -> System.out.println(x)); 20 | l.testScopeOfLambda(x -> System.out.println(x + l.a)); 21 | l.a = 2; 22 | l.testScopeOfLambda(x -> System.out.println(x + l.a)); 23 | /*for (int i = 0; i < 10; i++) { 24 | l.testScopeOfLambda(x -> System.out.println(x + i)); 25 | }*/ 26 | /*l.testScopeOfLambda(x -> { 27 | int a = 2; 28 | System.out.println(x + l.a); 29 | });*/ 30 | l.testScopeOfLambda(new Consumer() { 31 | int a = 2; 32 | 33 | @Override 34 | public void accept(String s) { 35 | 36 | } 37 | }); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/linkedlists/DeleteAlternateNodes.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.linkedlists; 2 | 3 | import com.rampatra.base.SingleLinkedList; 4 | import com.rampatra.base.SingleLinkedNode; 5 | 6 | /** 7 | * Delete alternate nodes in a single linked list. 8 | * 9 | * @author rampatra 10 | * @since 6/27/15 11 | */ 12 | public class DeleteAlternateNodes { 13 | 14 | public static > void deleteAlternateNodes(SingleLinkedList list) { 15 | deleteAlternateNodes(list.head); 16 | } 17 | 18 | public static > void deleteAlternateNodes(SingleLinkedNode node) { 19 | if (node == null || node.next == null) return; 20 | 21 | node.next = node.next.next; 22 | 23 | deleteAlternateNodes(node.next); 24 | } 25 | 26 | public static void main(String[] args) { 27 | SingleLinkedList linkedList = new SingleLinkedList<>(); 28 | linkedList.add(0); 29 | linkedList.add(1); 30 | linkedList.add(2); 31 | linkedList.add(3); 32 | linkedList.add(4); 33 | linkedList.add(5); 34 | linkedList.printList(); 35 | deleteAlternateNodes(linkedList); 36 | linkedList.printList(); 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/linkedlists/DeleteNode.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.linkedlists; 2 | 3 | import com.rampatra.base.SingleLinkedList; 4 | import com.rampatra.base.SingleLinkedNode; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * 9 | * @author rampatra 10 | * @since 6/18/15 11 | * @time: 2:35 PM 12 | */ 13 | public class DeleteNode { 14 | 15 | /** 16 | * Given a pointer to a node, delete it. 17 | * 18 | * @param node 19 | * @param 20 | */ 21 | public static > void deleteNode(SingleLinkedNode node) { 22 | // assert node isn't the last node in the linked list 23 | node.item = node.next.item; 24 | node.next = node.next.next; 25 | } 26 | 27 | public static void main(String[] args) { 28 | SingleLinkedList linkedList = new SingleLinkedList<>(); 29 | linkedList.add(0); 30 | linkedList.add(1); 31 | linkedList.add(2); 32 | linkedList.printList(); 33 | deleteNode(linkedList.getNode(1)); 34 | linkedList.printList(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/linkedlists/DivideCircularListIntoTwo.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.linkedlists; 2 | 3 | import com.rampatra.base.CircularSingleLinkedList; 4 | import com.rampatra.base.SingleLinkedNode; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * 9 | * @author rampatra 10 | * @since 6/23/15 11 | * @time: 6:01 PM 12 | */ 13 | public class DivideCircularListIntoTwo> extends CircularSingleLinkedList { 14 | 15 | public static > CircularSingleLinkedList[] divideIntoTwoHalves(CircularSingleLinkedList list) { 16 | SingleLinkedNode middleNode = list.getNode(list.size - 1 >> 1), 17 | lastNode = list.getNode(list.size - 1), 18 | secondHead = middleNode.next; 19 | // make the 2nd half circular first 20 | lastNode.next = middleNode.next; 21 | // then make the 1st half circular 22 | middleNode.next = list.head; 23 | 24 | return new CircularSingleLinkedList[]{getLinkedList(list.head), getLinkedList(secondHead)}; 25 | } 26 | 27 | public static void main(String[] args) { 28 | CircularSingleLinkedList linkedList = new CircularSingleLinkedList<>(); 29 | linkedList.add(00); 30 | linkedList.add(11); 31 | linkedList.add(22); 32 | linkedList.add(33); 33 | linkedList.add(44); 34 | CircularSingleLinkedList linkedLists[] = divideIntoTwoHalves(linkedList); 35 | linkedLists[0].printList(); 36 | linkedLists[1].printList(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/linkedlists/InsertInSortedList.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.linkedlists; 2 | 3 | import com.rampatra.base.SingleLinkedList; 4 | import com.rampatra.base.SingleLinkedNode; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * 9 | * @author rampatra 10 | * @since 6/21/15 11 | * @time: 10:20 PM 12 | */ 13 | public class InsertInSortedList> extends SingleLinkedList { 14 | 15 | /** 16 | * Inserts an element in the sorted linked 17 | * list maintaining the sorted property. 18 | * 19 | * @param item 20 | */ 21 | public void insert(E item) { 22 | SingleLinkedNode node = head; 23 | 24 | while (node != null) { 25 | if (node.item.compareTo(item) > 0) { // new node is to be inserted before head 26 | head = new SingleLinkedNode<>(item, node); 27 | return; 28 | } else if (node.next == null || node.next.item.compareTo(item) > 0) { // new node to be inserted anywhere else 29 | node.next = new SingleLinkedNode<>(item, node.next); 30 | return; 31 | } 32 | node = node.next; 33 | } 34 | } 35 | 36 | public static void main(String[] args) { 37 | InsertInSortedList linkedList = new InsertInSortedList<>(); 38 | linkedList.add(00); 39 | linkedList.add(11); 40 | linkedList.add(22); 41 | linkedList.add(33); 42 | linkedList.printList(); 43 | linkedList.insert(-2); 44 | linkedList.insert(9); 45 | linkedList.insert(44); 46 | linkedList.printList(); 47 | } 48 | } -------------------------------------------------------------------------------- /src/main/java/com/rampatra/linkedlists/MiddleNode.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.linkedlists; 2 | 3 | import com.rampatra.base.SingleLinkedList; 4 | import com.rampatra.base.SingleLinkedNode; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * 9 | * @author rampatra 10 | * @since 6/18/15 11 | */ 12 | public class MiddleNode { 13 | 14 | public static > SingleLinkedNode getMiddleNode(SingleLinkedList list) { 15 | SingleLinkedNode slow = list.head, fast = list.head; 16 | while (fast != null && fast.next != null) { 17 | slow = slow.next; 18 | fast = fast.next.next; 19 | } 20 | return slow; 21 | } 22 | 23 | public static void main(String[] args) { 24 | SingleLinkedList linkedList = new SingleLinkedList<>(); 25 | linkedList.add(00); 26 | linkedList.add(11); 27 | linkedList.add(22); 28 | linkedList.add(33); 29 | linkedList.add(44); 30 | linkedList.add(55); 31 | linkedList.add(66); 32 | linkedList.add(77); 33 | linkedList.add(88); 34 | System.out.println(getMiddleNode(linkedList).item); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/linkedlists/MoveLastNodeToFirst.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.linkedlists; 2 | 3 | import com.rampatra.base.SingleLinkedList; 4 | import com.rampatra.base.SingleLinkedNode; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * 9 | * @author rampatra 10 | * @since 6/23/15 11 | * @time: 7:52 PM 12 | */ 13 | public class MoveLastNodeToFirst { 14 | 15 | public static > void moveLastNodeToFirst(SingleLinkedList list) { 16 | if (list.size <= 1) return; 17 | 18 | SingleLinkedNode curr = list.getNode(0), prev = curr; 19 | while (curr.next != null) { 20 | prev = curr; 21 | curr = curr.next; 22 | } 23 | prev.next = null; 24 | curr.next = list.head; 25 | list.head = curr; 26 | } 27 | 28 | public static void main(String[] args) { 29 | SingleLinkedList linkedList = new SingleLinkedList<>(); 30 | linkedList.add(00); 31 | linkedList.add(11); 32 | linkedList.add(22); 33 | linkedList.add(33); 34 | linkedList.printList(); 35 | moveLastNodeToFirst(linkedList); 36 | linkedList.printList(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/linkedlists/PairWiseSwap.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.linkedlists; 2 | 3 | import com.rampatra.base.SingleLinkedList; 4 | import com.rampatra.base.SingleLinkedNode; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * 9 | * @author rampatra 10 | * @since 6/24/15 11 | * @time: 3:48 PM 12 | */ 13 | public class PairWiseSwap { 14 | 15 | /** 16 | * Recursively swaps adjacent nodes of a linked list. 17 | *

18 | * Example: 19 | * Input: 11->22->33->44->55 20 | * Output: 22->11->44->33->55 21 | * 22 | * @param node 23 | * @return new starting node after swapping adjacent nodes. 24 | */ 25 | public static > SingleLinkedNode pairWiseSwap(SingleLinkedNode node) { 26 | if (node == null || node.next == null) return node; 27 | 28 | SingleLinkedNode nextNode = node.next, nextOfNextNode = nextNode.next; 29 | 30 | nextNode.next = node; 31 | node.next = pairWiseSwap(nextOfNextNode); 32 | 33 | return nextNode; 34 | } 35 | 36 | public static void main(String[] args) { 37 | SingleLinkedList linkedList = new SingleLinkedList<>(); 38 | linkedList.add(11); 39 | linkedList.add(22); 40 | linkedList.add(33); 41 | linkedList.add(44); 42 | linkedList.add(55); 43 | linkedList.add(66); 44 | linkedList.add(77); 45 | linkedList.printList(); 46 | linkedList.printList(pairWiseSwap(linkedList.head)); 47 | } 48 | } -------------------------------------------------------------------------------- /src/main/java/com/rampatra/linkedlists/RandomNode.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.linkedlists; 2 | 3 | import com.rampatra.arrays.ReservoirSampling; 4 | import com.rampatra.base.SingleLinkedList; 5 | import com.rampatra.base.SingleLinkedNode; 6 | 7 | import java.util.Random; 8 | 9 | /** 10 | * Created by IntelliJ IDEA. 11 | * 12 | * @author rampatra 13 | * @since 7/21/15 14 | * @time: 12:57 PM 15 | */ 16 | public class RandomNode { 17 | 18 | /** 19 | * Returns a random node from linked list with each node having an equal probability. 20 | *

21 | * This method uses the simplified version of Reservoir Sampling ({@link ReservoirSampling}) 22 | * where k = 1. 23 | * 24 | * @param node 25 | * @param 26 | * @return 27 | */ 28 | public static > SingleLinkedNode getRandomNode(SingleLinkedNode node) { 29 | SingleLinkedNode result = node, curr = node; 30 | for (int i = 2; curr != null; i++) { 31 | 32 | int rand = new Random().nextInt(i); 33 | 34 | if (rand % i == 0) result = curr; 35 | 36 | curr = curr.next; 37 | } 38 | 39 | return result; 40 | } 41 | 42 | public static void main(String[] args) { 43 | SingleLinkedList linkedList = new SingleLinkedList<>(); 44 | linkedList.add(00); 45 | linkedList.add(11); 46 | linkedList.add(22); 47 | linkedList.add(33); 48 | linkedList.add(44); 49 | linkedList.add(55); 50 | linkedList.add(66); 51 | linkedList.add(77); 52 | linkedList.add(88); 53 | System.out.println(getRandomNode(linkedList.head).item); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/linkedlists/ReverseDoubleLinkedList.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.linkedlists; 2 | 3 | import com.rampatra.base.DoubleLinkedList; 4 | import com.rampatra.base.DoubleLinkedNode; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * 9 | * @author rampatra 10 | * @since 6/19/15 11 | * @time: 9:24 AM 12 | */ 13 | public class ReverseDoubleLinkedList { 14 | 15 | /** 16 | * Reverses the doubly linked list. 17 | * 18 | * @param list 19 | */ 20 | public static > void reverseList(DoubleLinkedList list) { 21 | 22 | DoubleLinkedNode curr = list.getNode(0); 23 | DoubleLinkedNode temp = curr; 24 | 25 | while (curr != null) { 26 | temp = curr.prev; 27 | curr.prev = curr.next; 28 | curr.next = temp; 29 | curr = curr.prev; 30 | } 31 | 32 | // temp will be null if linked list has only one node 33 | if (temp != null) { 34 | list.head = temp.prev; 35 | } 36 | } 37 | 38 | public static void main(String[] args) { 39 | DoubleLinkedList linkedList = new DoubleLinkedList<>(); 40 | linkedList.add(11); 41 | linkedList.add(22); 42 | linkedList.add(33); 43 | linkedList.add(44); 44 | linkedList.add(55); 45 | linkedList.add(66); 46 | linkedList.printList(); 47 | reverseList(linkedList); 48 | linkedList.printList(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/linkedlists/SortLinkedListOf0s1s2s.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.linkedlists; 2 | 3 | import com.rampatra.base.SingleLinkedList; 4 | import com.rampatra.base.SingleLinkedNode; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * 9 | * @author rampatra 10 | * @since 7/5/15 11 | * @time: 1:47 PM 12 | */ 13 | public class SortLinkedListOf0s1s2s { 14 | 15 | /** 16 | * Sorts {@param list} consisting of only 0s, 1s and 2s as their node values. 17 | *

18 | * Time complexity: O(n) 19 | * Space complexity: O(1) 20 | * 21 | * @param list 22 | */ 23 | public static void sort(SingleLinkedList list) { 24 | int[] count = new int[3]; 25 | SingleLinkedNode curr = list.head; 26 | 27 | // keep count of 0s, 1s and 2s 28 | while (curr != null) { 29 | count[curr.item]++; 30 | curr = curr.next; 31 | } 32 | 33 | // make a linked list of that many 0s, 1s and 2s 34 | list.clear(); 35 | for (int i = 0; i < count.length; i++) { 36 | for (int j = 0; j < count[i]; j++) { 37 | list.add(i); 38 | } 39 | } 40 | } 41 | 42 | public static void main(String[] args) { 43 | SingleLinkedList linkedList = new SingleLinkedList<>(); 44 | linkedList.add(0); 45 | linkedList.add(1); 46 | linkedList.add(2); 47 | linkedList.add(0); 48 | linkedList.add(1); 49 | linkedList.add(2); 50 | linkedList.add(1); 51 | linkedList.printList(); 52 | sort(linkedList); 53 | linkedList.printList(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/misc/BreakParagraph.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.misc; 2 | 3 | import java.text.BreakIterator; 4 | import java.util.Locale; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * 9 | * @author rampatra 10 | * @since 9/22/15 11 | * @time: 10:02 AM 12 | */ 13 | public class BreakParagraph { 14 | public static void main(String[] args) { 15 | String paragraph = 16 | "Line boundary analysis determines where a text " + 17 | "string can be broken when line-wrapping. The " + 18 | "mechanism correctly handles punctuation and " + 19 | "hyphenated words. Mr.Ram is a good boy. Actual line breaking needs to " + 20 | "also consider the available line width and is " + 21 | "handled by higher-level software. "; 22 | 23 | BreakIterator iterator = 24 | BreakIterator.getSentenceInstance(Locale.US); 25 | 26 | int sentences = count(iterator, paragraph); 27 | System.out.println("Number of sentences: " + sentences); 28 | } 29 | 30 | private static int count(BreakIterator bi, String source) { 31 | int counter = 0; 32 | bi.setText(source); 33 | 34 | int lastIndex = bi.first(); 35 | while (lastIndex != BreakIterator.DONE) { 36 | int firstIndex = lastIndex; 37 | lastIndex = bi.next(); 38 | 39 | if (lastIndex != BreakIterator.DONE) { 40 | String sentence = source.substring(firstIndex, lastIndex); 41 | System.out.println("sentence = " + sentence); 42 | counter++; 43 | } 44 | } 45 | return counter; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/misc/DivideByZero.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.misc; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * User: rampatra 6 | * Date: 4/18/15 7 | * Time: 2:50 PM 8 | * To change this template go to Preferences | IDE Settings | File and Code Templates 9 | */ 10 | public class DivideByZero { 11 | public static void main(String[] args) { 12 | System.out.println(5.0 / 0); // doesn't throw any exception 13 | System.out.println(5 / 0); // throws runtime exception or unchecked exception (does NOT need explicit handling). To be specific, throws an arithmetic exception. 14 | } 15 | } -------------------------------------------------------------------------------- /src/main/java/com/rampatra/misc/Equals.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.misc; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * User: rampatra 6 | * Date: 3/14/15 7 | * Time: 4:38 PM 8 | * To change this template go to Preferences | IDE Settings | File and Code Templates 9 | */ 10 | public class Equals { 11 | public static void main(String[] args) { 12 | Short i = new Short((short) 12); 13 | Short j = new Short((short) 12); 14 | System.out.print(j == i); // prints false as compiler compares 2 references instead of their values 15 | System.out.print(12 == i); // prints true as the compiler unboxes "i" and then compares the value 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/misc/GarbageCollection.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.misc; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 10/2/15 8 | * @time: 12:44 AM 9 | */ 10 | public class GarbageCollection { 11 | public void finalize() { 12 | System.out.println("object is garbage collected"); 13 | } 14 | 15 | public static void main(String args[]) { 16 | GarbageCollection s1 = new GarbageCollection(); 17 | GarbageCollection s2 = new GarbageCollection(); 18 | s1 = null; 19 | s2 = null; 20 | System.gc(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/misc/GenericNonGenericMix.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.misc; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * User: rampatra 9 | * Date: 3/26/15 10 | * Time: 3:06 PM 11 | * To change this template go to Preferences | IDE Settings | File and Code Templates 12 | */ 13 | public class GenericNonGenericMix { 14 | static List add(ArrayList list) { 15 | list.add(new String("100")); 16 | list.add(new Integer(10)); // will throw exception at runtime 17 | return list; 18 | } 19 | 20 | public static void main(String[] args) { 21 | ArrayList stringArrayList = new ArrayList<>(); 22 | stringArrayList.add("ram"); 23 | add(stringArrayList); 24 | for (String s : stringArrayList) { 25 | System.out.println(s); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/misc/MapWithTimestamp.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.misc; 2 | 3 | import java.util.Date; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | /** 8 | * @author rampatra 9 | * @since 2019-05-15 10 | */ 11 | public class MapWithTimestamp { 12 | 13 | private final Map> map = new HashMap<>(); 14 | 15 | public V get(K key, Long timestamp) { 16 | Map entry = map.get(key); 17 | 18 | return entry != null ? entry.get(timestamp) : null; 19 | } 20 | 21 | public void put(K key, Long timestamp, V value) { 22 | Map entry = map.get(key); 23 | 24 | if (entry == null) { 25 | map.put(key, new HashMap() {{ 26 | put(timestamp, value); 27 | }}); 28 | } else { 29 | entry.put(timestamp, value); 30 | } 31 | } 32 | 33 | public static void main(String[] args) throws Exception { 34 | MapWithTimestamp mapWithTimestamp = new MapWithTimestamp<>(); 35 | long timestamp1; 36 | long timestamp2; 37 | long timestamp3; 38 | 39 | mapWithTimestamp.put(1, timestamp1 = new Date().getTime(), 10_0); 40 | mapWithTimestamp.put(2, timestamp2 = new Date().getTime(), 20_0); 41 | Thread.sleep(100); 42 | mapWithTimestamp.put(2, new Date().getTime(), 20_1); 43 | Thread.sleep(100); 44 | mapWithTimestamp.put(2, new Date().getTime(), 20_2); 45 | mapWithTimestamp.put(3, timestamp3 = new Date().getTime(), 30_0); 46 | System.out.println(mapWithTimestamp.get(2, timestamp2)); 47 | System.out.println(mapWithTimestamp.get(3, timestamp2)); 48 | System.out.println(mapWithTimestamp.get(3, timestamp3)); 49 | } 50 | } -------------------------------------------------------------------------------- /src/main/java/com/rampatra/misc/MethodLocalVSInner.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.misc; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * User: rampatra 6 | * Date: 4/14/15 7 | * Time: 11:39 AM 8 | * To change this template go to Preferences | IDE Settings | File and Code Templates 9 | */ 10 | class A { 11 | void m() { 12 | System.out.println("outer"); 13 | } 14 | } 15 | 16 | public class MethodLocalVSInner { 17 | 18 | public static void main(String[] args) { 19 | new MethodLocalVSInner().go(); 20 | } 21 | 22 | void go() { 23 | new A().m(); 24 | class A { 25 | void m() { 26 | System.out.println("inner"); 27 | } 28 | } 29 | } 30 | 31 | class A { 32 | void m() { 33 | System.out.println("middle"); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/misc/MethodOverloading.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.misc; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 5/8/15 8 | * @time: 12:08 PM 9 | */ 10 | class MethodOverloading { 11 | 12 | static void go(float x) { 13 | System.out.print("float "); 14 | } 15 | 16 | static void go(Long x) { 17 | System.out.print("Long "); 18 | } 19 | 20 | static void go(double x) { 21 | System.out.print("double "); 22 | } 23 | 24 | static void go(Double x) { 25 | System.out.print("Double "); 26 | } 27 | 28 | static void go(int x, int y) { 29 | System.out.print("int,int "); 30 | } 31 | 32 | static void go(byte... x) { 33 | System.out.print("byte... "); 34 | } 35 | 36 | static void go(Long x, Long y) { 37 | System.out.print("Long,Long "); 38 | } 39 | 40 | static void go(long... x) { 41 | System.out.print("long... "); 42 | } 43 | 44 | public static void main(String[] args) { 45 | byte b = 5; 46 | short s = 5; 47 | long l = 5; 48 | float f = 5.0f; 49 | // widening beats autoboxing 50 | go(b); 51 | go(s); 52 | go(l); 53 | go(f); 54 | // widening beats var-args 55 | go(b, b); 56 | // auto-boxing beats var-args 57 | go(l, l); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/misc/Outer.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.misc; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 9/30/15 8 | * @time: 9:37 AM 9 | */ 10 | class BigOuter { 11 | static class Nest { 12 | void go() { 13 | System.out.println("hi"); 14 | } 15 | } 16 | } 17 | 18 | public class Outer { 19 | static class B2 { 20 | void goB2() { 21 | System.out.println("hi 2"); 22 | } 23 | } 24 | 25 | public static void main(String[] args) { 26 | BigOuter.Nest n = new BigOuter.Nest(); 27 | n.go(); 28 | B2 b2 = new B2(); 29 | b2.goB2(); 30 | //B2.goB2(); not possible 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/misc/OuterClassAccess.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.misc; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 11/13/15 8 | * @time: 11:39 AM 9 | */ 10 | public class OuterClassAccess { 11 | private int size = 7; 12 | private static int length = 3; 13 | 14 | public static void main(String[] args) { 15 | new OuterClassAccess().go(); 16 | } 17 | 18 | void go() { 19 | int size = 5; 20 | System.out.println(new Inner().adder()); 21 | } 22 | 23 | class Inner { 24 | int adder() { 25 | return size * length; // inner class can access static members of outer class 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/misc/RandomTest.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.misc; 2 | 3 | import java.util.Random; 4 | 5 | /** 6 | * @author rampatra 7 | * @since 2/23/15 8 | */ 9 | public class RandomTest { 10 | public static void main(String[] args) { 11 | Random r = new Random(); 12 | System.out.println(r.nextInt(1)); 13 | System.out.println(randInt(0, 1, false)); 14 | //System.out.print(randInts(1, 0)); 15 | } 16 | 17 | public static int randInt(int start, int end, boolean startInclusive) { 18 | int diff = end - start; 19 | if (start < 0 || end < 0 || diff <= 0) return -1; 20 | 21 | Random random = new Random(); 22 | if (startInclusive) { 23 | return random.nextInt(diff + 1) + start; 24 | } else { 25 | return random.nextInt(diff) + start + 1; 26 | } 27 | } 28 | 29 | public static int randInt(int max, int exclude) { 30 | // some validation 31 | if (max <= 0) return -1; 32 | Random random = new Random(); 33 | int randInt = random.nextInt(max); 34 | if (randInt == exclude) { 35 | return (randInt == max) ? randInt - 1 : randInt + 1; 36 | } else { 37 | return randInt; 38 | } 39 | } 40 | 41 | public static int[] randInts(int max, int exclude) { 42 | int[] randInts = new int[2]; 43 | randInts[0] = randInt(max, exclude); 44 | do { 45 | randInts[1] = randInt(max, exclude); 46 | } while ((randInts[0] != -1 & randInts[1] != -1) && (randInts[0] == randInts[1])); 47 | 48 | return randInts; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/misc/RegexReplaceAllSpaces.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.misc; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 11/3/15 6 | */ 7 | public class RegexReplaceAllSpaces { 8 | 9 | public static String replaceAll(String str, String regex, String replacement) { 10 | return str.replaceAll(regex, replacement); 11 | } 12 | 13 | public static void main(String[] args) { 14 | System.out.println(replaceAll("ram s", "\\s+", "")); 15 | } 16 | } 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/misc/RegexValidateLatLong.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.misc; 2 | 3 | import java.util.Scanner; 4 | import java.util.regex.Matcher; 5 | import java.util.regex.Pattern; 6 | 7 | /** 8 | * @author rampatra 9 | * @since 9/12/15 10 | */ 11 | public class RegexValidateLatLong { 12 | 13 | /** 14 | * Validates latitude/longitude in the form (+75, 180) etc. 15 | * 16 | * @param s 17 | * @return 18 | */ 19 | public static String validateLatLong(String s) { 20 | String regex_coords = "^(\\(\\-?\\d+(\\.\\d+)?),\\s*(\\-?\\d+(\\.\\d+)?\\))$"; 21 | Pattern compiledPattern2 = Pattern.compile(regex_coords, Pattern.CASE_INSENSITIVE); 22 | Matcher matcher2 = compiledPattern2.matcher(s); 23 | while (matcher2.find()) { 24 | return "Valid"; 25 | } 26 | return "Invalid"; 27 | } 28 | 29 | public static void main(String[] args) { 30 | Scanner in = new Scanner(System.in); 31 | 32 | int t = Integer.parseInt(in.nextLine()); 33 | String[] in_ar = new String[t]; 34 | 35 | for (int i = 0; i < t; i++) { 36 | in_ar[i] = in.nextLine(); 37 | } 38 | 39 | for (String i : in_ar) { 40 | System.out.println(validateLatLong(i)); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/permutations/StringPermutations.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.permutations; 2 | 3 | /** 4 | * Prints all the permutations of a string by using the characters in the 5 | * input only once. 6 | * 7 | * @author rampatra 8 | * @link http://www.ericleschinski.com/c/java_permutations_recursion/ 9 | * @link http://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html 10 | * @link me.rampatra.strings.StringPermutationCount for a modification of this problem 11 | * @since 9/24/15 12 | */ 13 | public class StringPermutations { 14 | 15 | /** 16 | * Generates and prints all possible permutations (in order) 17 | * of string {@param s}. 18 | * 19 | * @param prefix empty string, needed for the recursive method 20 | * @param s input string with no repeated characters 21 | */ 22 | public static void printAllPermutations(String prefix, String s) { 23 | int len = s.length(); 24 | if (len == 0) { 25 | System.out.println(prefix); 26 | } else { 27 | for (int i = 0; i < len; i++) { 28 | printAllPermutations(prefix + s.charAt(i), s.substring(0, i) + s.substring(i + 1)); 29 | } 30 | } 31 | } 32 | 33 | public static void main(String[] args) { 34 | printAllPermutations("", "a"); 35 | System.out.println("-------"); 36 | printAllPermutations("", "ab"); 37 | System.out.println("-------"); 38 | printAllPermutations("", "abc"); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/permutations/StringPermutationsCount.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.permutations; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | *

6 | * You have 2 string, one smaller, one larger. Write an algorithm to figure out how many permutations of the 7 | * smaller string exist in the bigger string. 8 | * 9 | * @author rampatra 10 | * @since 10/15/15 11 | * @time: 10:32 AM 12 | * @see: StringPermutations for a simpler version 13 | */ 14 | public class StringPermutationsCount { 15 | 16 | /** 17 | * Finds the number of permutations of string {@param s1} that exists in string {@param s2}. 18 | * 19 | * @param prefix 20 | * @param s1 21 | * @param s2 22 | * @param count 23 | * @return 24 | */ 25 | public static int getStringPermutationsCount(String prefix, String s1, String s2, int count) { 26 | if (s1.isEmpty()) { 27 | if (s2.indexOf(prefix) != -1) count++; 28 | } 29 | 30 | for (int i = 0; i < s1.length(); i++) { 31 | count = getStringPermutationsCount(prefix + s1.substring(i, i + 1), s1.substring(0, i) + s1.substring(i + 1), s2, count); 32 | } 33 | 34 | return count; 35 | } 36 | 37 | public static void main(String[] args) { 38 | System.out.println(getStringPermutationsCount("", "abc", "abcba", 0)); 39 | System.out.println(getStringPermutationsCount("", "abc", "abcbacb", 0)); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/permutations/StringPermutationsWithDuplicates.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.permutations; 2 | 3 | /** 4 | * A slight variation of {@link StringPermutations} where the input may 5 | * contain repeated characters. 6 | * 7 | * @author rampatra 8 | * @since 16/11/2018 9 | */ 10 | public class StringPermutationsWithDuplicates { 11 | 12 | /** 13 | * Generates and prints all possible permutations (in order) 14 | * of string {@param s}. 15 | * 16 | * @param prefix empty string, needed for the recursive method 17 | * @param s input string with repeated characters 18 | */ 19 | public static void printAllPermutations(String prefix, String s) { 20 | // TODO 21 | } 22 | 23 | public static void main(String[] args) { 24 | printAllPermutations("", "aba"); 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/permutations/UppercaseLowercasePermutations.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.permutations; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 9/26/15 8 | * @time: 4:43 PM 9 | */ 10 | public class UppercaseLowercasePermutations { 11 | 12 | /** 13 | * Generates all possible case combinations for string {@param s}. 14 | *

15 | * For example, 16 | * Input: 0ab 17 | * Output: ["0ab","0AB","0aB","0Ab"] 18 | * 19 | * @param prefix 20 | * @param s 21 | */ 22 | public static void printUppercaseLowercasePermutations(String prefix, String s) { 23 | 24 | if (s.isEmpty()) { 25 | System.out.println(prefix); 26 | return; 27 | } 28 | 29 | if (isNumber(s.charAt(0))) { 30 | printUppercaseLowercasePermutations(prefix + s.charAt(0), s.substring(1)); 31 | } else { 32 | printUppercaseLowercasePermutations(prefix + Character.toUpperCase(s.charAt(0)), s.substring(1)); 33 | printUppercaseLowercasePermutations(prefix + Character.toLowerCase(s.charAt(0)), s.substring(1)); 34 | } 35 | } 36 | 37 | public static boolean isNumber(char s) { 38 | try { 39 | Integer.parseInt(String.valueOf(s)); 40 | } catch (Exception e) { 41 | return false; 42 | } 43 | return true; 44 | } 45 | 46 | public static void main(String[] args) { 47 | printUppercaseLowercasePermutations("", "0ab"); 48 | System.out.println("========"); 49 | printUppercaseLowercasePermutations("", "01"); 50 | System.out.println("========"); 51 | printUppercaseLowercasePermutations("", "0a1"); 52 | System.out.println("========"); 53 | printUppercaseLowercasePermutations("", "0ab1c"); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/searching/InterpolationSearch.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.searching; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 9/1/15 8 | * @time: 4:57 PM 9 | */ 10 | public class InterpolationSearch { 11 | 12 | /** 13 | * @param a 14 | * @param k 15 | * @return 16 | */ 17 | public static int search(int[] a, int k) { 18 | int low = 0, high = a.length - 1, mid; 19 | 20 | while (a[low] != a[high] && k >= a[low] && k <= a[high]) { 21 | mid = low + (k - a[low]) * (high - low) / a[high] - a[low]; 22 | 23 | if (k < a[mid]) { 24 | high = mid - 1; 25 | } else if (k > a[mid]) { 26 | low = mid + 1; 27 | } else { 28 | return mid; 29 | } 30 | } 31 | 32 | if (k == a[low]) { 33 | return low; 34 | } else { 35 | return -1; 36 | } 37 | } 38 | 39 | public static void main(String[] args) { 40 | System.out.println(search(new int[]{0, 2}, 2)); 41 | System.out.println(search(new int[]{0, 1}, 2)); 42 | System.out.println(search(new int[]{0, 1, 2, 3}, 2)); 43 | System.out.println(search(new int[]{0, 1, 2, 3}, 3)); 44 | System.out.println(search(new int[]{0, 2}, 0)); 45 | System.out.println(search(new int[]{0, 1, 2, 2, 2, 3, 3}, 2)); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/sorting/BubbleSort.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.sorting; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @author rpatra16 7 | * @since 03/11/2018 8 | */ 9 | public class BubbleSort { 10 | 11 | /** 12 | * In bubble sort, we start at the beginning of the array and swap 13 | * the first two elements if the first is greater than the second. 14 | * Then, we go to the next pair, and so on, continuously making sweeps 15 | * of the array until it is sorted. In doing so, the smaller items 16 | * slowly "bubble" up to the beginning of the list and in each inner 17 | * iteration the largest element is sorted. Ergo, the inner loop runs 18 | * until {@code length - i - 1} times. Time complexity: O(n^2). Space 19 | * complexity: O(1), in place. To learn more: {@see https://youtu.be/6Gv8vg0kcHc} 20 | * 21 | * @param ar to be sorted 22 | */ 23 | private static void bubbleSort(int[] ar) { 24 | for (int i = 0; i < ar.length - 1; i++) { 25 | for (int j = 0; j < ar.length - i - 1; j++) { 26 | if (ar[j] > ar[j + 1]) { 27 | swap(ar, j, j + 1); 28 | } 29 | } 30 | } 31 | } 32 | 33 | private static void swap(int[] ar, int i, int j) { 34 | int temp = ar[i]; 35 | ar[i] = ar[j]; 36 | ar[j] = temp; 37 | } 38 | 39 | public static void main(String[] args) { 40 | int[] ar = {2, 5, 1, 7, 8}; 41 | System.out.println(Arrays.toString(ar)); 42 | bubbleSort(ar); 43 | System.out.println(Arrays.toString(ar)); 44 | ar = new int[]{7, 5, 1, 7, 8, 0, 23}; 45 | System.out.println(Arrays.toString(ar)); 46 | bubbleSort(ar); 47 | System.out.println(Arrays.toString(ar)); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/sorting/WiggleSort.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.sorting; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Wiggle Sort: Arrange the elements in the array such that elements in 7 | * even indices are greater than or equal to its neighbouring elements 8 | * and elements in odd indices are less than or equal to its neighbouring 9 | * elements. In other words, all elements in array {@code a} are arranged 10 | * such that, a[i-1] <= a[i] => a[i+1] 11 | *

12 | * Ex: {1, 3, 2, 5, 4, 6} 13 | * 14 | * @author rampatra 15 | * @version 01/09/2016 16 | */ 17 | public class WiggleSort { 18 | 19 | public static int[] wiggleSortEasyWay(int[] a) { 20 | a = MergeSort.mergeSort(a); 21 | for (int i = 1; i < a.length; i += 2) { 22 | swap(a, i, i + 1); 23 | } 24 | return a; 25 | } 26 | 27 | private static void swap(int[] a, int index1, int index2) { 28 | if (index2 >= a.length) return; 29 | 30 | a[index1] = a[index1] + a[index2]; 31 | a[index2] = a[index1] - a[index2]; 32 | a[index1] = a[index1] - a[index2]; 33 | } 34 | 35 | public static void main(String[] args) { 36 | int[] ar = {3, 5, 6, 7, 8, 1, 2}; 37 | System.out.println(Arrays.toString(wiggleSortEasyWay(ar))); 38 | int[] ar1 = {3, 5, 6, 7, 2, 1}; 39 | System.out.println(Arrays.toString(wiggleSortEasyWay(ar1))); 40 | int[] ar2 = {3, 5, 6, 7, 8, 1}; 41 | System.out.println(Arrays.toString(wiggleSortEasyWay(ar2))); 42 | int[] ar3 = {3, 5, 6, 5, 8, 1}; 43 | System.out.println(Arrays.toString(wiggleSortEasyWay(ar3))); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/strings/AnagramsTogether.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.strings; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | /** 10 | * Created by IntelliJ IDEA. 11 | * 12 | * @author rampatra 13 | * @since 9/23/15 14 | */ 15 | public class AnagramsTogether { 16 | 17 | /** 18 | * Prints all the anagrams together from the string array {@code strings}. 19 | *

20 | * Anagrams are words consisting of the same letters but in the same or different 21 | * order. For example, "cat" and "tac" are anagrams. Same as "god" and "dog". 22 | * 23 | * @param strings 24 | */ 25 | private static void printAnagramsTogether(String[] strings) { 26 | 27 | // each key holds all the indexes of a anagram 28 | HashMap> hashMap = new HashMap<>(); 29 | 30 | for (int i = 0; i < strings.length; i++) { 31 | char[] chars = strings[i].toCharArray(); 32 | Arrays.sort(chars); 33 | 34 | List indexes = hashMap.get(String.valueOf(chars)); 35 | if (indexes == null) { 36 | indexes = new ArrayList<>(); 37 | } 38 | indexes.add(i); 39 | hashMap.put(String.valueOf(chars), indexes); 40 | } 41 | 42 | for (Map.Entry> entry : hashMap.entrySet()) { 43 | for (int i = 0; i < entry.getValue().size(); i++) { 44 | System.out.println(strings[entry.getValue().get(i)]); 45 | } 46 | System.out.println("------"); 47 | } 48 | } 49 | 50 | public static void main(String[] args) { 51 | printAnagramsTogether(new String[]{"cat", "dog", "tac", "god", "act"}); 52 | printAnagramsTogether(new String[]{"cat", "tac", "act", "god", "dog"}); 53 | } 54 | } -------------------------------------------------------------------------------- /src/main/java/com/rampatra/strings/IntegerToString.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.strings; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 2019-04-01 6 | */ 7 | public class IntegerToString { 8 | 9 | private static final int[] sizeTable = {9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 10 | 999999999, Integer.MAX_VALUE}; 11 | 12 | private static String getStringFromInteger(int num) { 13 | boolean isNegative = num < 0; 14 | num = isNegative ? -num : num; 15 | int size = getStringSize(num); 16 | size = isNegative ? size + 1 : size; 17 | char[] chars = new char[size]; 18 | 19 | int rem; 20 | for (int i = size - 1; isNegative ? i > 0 : i >= 0; i--) { 21 | rem = num % 10; 22 | num = num / 10; 23 | chars[i] = (char) (rem + '0'); 24 | } 25 | 26 | if (isNegative) { 27 | chars[0] = '-'; 28 | } 29 | 30 | return new String(chars); 31 | } 32 | 33 | private static int getStringSize(int num) { 34 | if (num == Integer.MAX_VALUE) return 10; 35 | 36 | for (int i = 0; ; i++) { 37 | if (num < sizeTable[i]) { 38 | return i + 1; 39 | } 40 | } 41 | } 42 | 43 | public static void main(String[] args) { 44 | System.out.println(getStringFromInteger(0)); 45 | System.out.println(getStringFromInteger(123)); 46 | System.out.println(getStringFromInteger(+123)); 47 | System.out.println(getStringFromInteger(-123)); 48 | System.out.println(getStringFromInteger(Integer.MAX_VALUE)); 49 | System.out.println(getStringFromInteger(Integer.MIN_VALUE)); // not working 50 | } 51 | } -------------------------------------------------------------------------------- /src/main/java/com/rampatra/strings/KeepOnlyKConsecutiveLetters.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.strings; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 30/11/2018 6 | */ 7 | public class KeepOnlyKConsecutiveLetters { 8 | 9 | /** 10 | * A method which takes a string {@code str} and a number {@code k} and 11 | * returns a string with at most {@code k} consecutive characters in the 12 | * string. 13 | *

14 | * For example, 15 | * 1) aaaaaabbbbbccccc, 3 -> aaabbbccc 16 | * 2) abc, 2 -> abc 17 | * 3) aabbccc, 3 -> aabbccc 18 | * 19 | * @param str input string 20 | * @param k 21 | * @return a string with at most {@code k} consecutive characters 22 | */ 23 | private static String keepOnlyKConsecutiveLetters(String str, int k) { 24 | StringBuilder sb = new StringBuilder(); 25 | int count = 0; 26 | 27 | for (int i = 0; i < str.length(); i++) { 28 | if (i != 0 && str.charAt(i) != str.charAt(i - 1)) { 29 | count = 0; 30 | } 31 | if (count < k) { 32 | sb.append(str.charAt(i)); 33 | count++; 34 | } 35 | } 36 | 37 | return sb.toString(); 38 | } 39 | 40 | public static void main(String[] args) { 41 | System.out.println("aaaaabbbbbccccc, 5: " + keepOnlyKConsecutiveLetters("aaaaabbbbbccccc", 5)); 42 | System.out.println("aaaaabbbbbccccc, 2: " + keepOnlyKConsecutiveLetters("aaaaabbbbbccccc", 2)); 43 | System.out.println("aaaaabbbbbccccc, 1: " + keepOnlyKConsecutiveLetters("aaaaabbbbbccccc", 1)); 44 | System.out.println("aabbcc, 2: " + keepOnlyKConsecutiveLetters("aabbcc", 2)); 45 | System.out.println("aabbcc, 0: " + keepOnlyKConsecutiveLetters("aabbcc", 0)); 46 | System.out.println("abc, 2: " + keepOnlyKConsecutiveLetters("abc", 2)); 47 | } 48 | } -------------------------------------------------------------------------------- /src/main/java/com/rampatra/strings/NearPalindrome.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.strings; 2 | 3 | /** 4 | * @author rampatra 5 | * @since 05/12/2018 6 | */ 7 | public class NearPalindrome { 8 | 9 | /** 10 | * Checks if a string can be a palindrome by changing just one character in the string {@code str}. 11 | * 12 | * @param str the input string 13 | * @return {@code true} if it can be converted to a palindrome with one character change or else {@code false} 14 | */ 15 | private static boolean isStringPalindromeByChangingOneChar(String str) { 16 | int diffCount = 0; 17 | for (int i = 0, j = str.length() - 1; i < str.length() / 2; i++, j--) { 18 | if (str.charAt(i) != str.charAt(j)) { 19 | if (diffCount > 0) { 20 | return false; 21 | } else { 22 | diffCount++; 23 | } 24 | } 25 | } 26 | return true; 27 | } 28 | 29 | public static void main(String[] args) { 30 | System.out.println(isStringPalindromeByChangingOneChar("")); 31 | System.out.println(isStringPalindromeByChangingOneChar("a")); 32 | System.out.println(isStringPalindromeByChangingOneChar("ab")); 33 | System.out.println(isStringPalindromeByChangingOneChar("aabbca")); 34 | System.out.println(isStringPalindromeByChangingOneChar("abccaa")); 35 | System.out.println(isStringPalindromeByChangingOneChar("abbcca")); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/strings/RemoveDuplicatesAndArrangeLetters.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.strings; 2 | 3 | import java.util.Set; 4 | import java.util.TreeSet; 5 | import java.util.stream.Collectors; 6 | 7 | /** 8 | * @author rampatra 9 | * @since 2019-04-02 10 | */ 11 | public class RemoveDuplicatesAndArrangeLetters { 12 | 13 | private static String removeDuplicatesAndArrangeLettersLexicographically(String str) { 14 | Set charSet = new TreeSet<>(); 15 | char[] chars = str.toCharArray(); 16 | 17 | for (char ch : chars) { 18 | charSet.add(ch); 19 | } 20 | 21 | return charSet.toString(); 22 | } 23 | 24 | private static String removeDuplicatesAndArrangeLettersLexicographically_Java8(String str) { 25 | return str.chars() 26 | .distinct() 27 | .sorted() 28 | .mapToObj(i -> (char) i) 29 | .map(String::valueOf) 30 | .collect(Collectors.joining()); 31 | } 32 | 33 | public static void main(String[] args) { 34 | System.out.println(removeDuplicatesAndArrangeLettersLexicographically("algo&dsInJava")); 35 | System.out.println(removeDuplicatesAndArrangeLettersLexicographically_Java8("algo&dsInJava")); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/strings/StringRotation.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.strings; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 10/21/15 8 | * @time: 10:06 AM 9 | * @see: me.rampatra.strings.SubString for a similar problem. 10 | */ 11 | public class StringRotation { 12 | 13 | /** 14 | * Determines if string {@param s2} is a rotation of string {@param s1}. 15 | * 16 | * @param s1 17 | * @param s2 18 | * @return 19 | */ 20 | public static boolean isStringRotation(String s1, String s2) { 21 | char[] c1 = s1.toCharArray(); 22 | char[] c2 = s2.toCharArray(); 23 | 24 | int l1 = c1.length, 25 | l2 = c2.length, 26 | i, j, k; 27 | 28 | for (i = 0; i < l1; i++) { 29 | for (j = 0; j < l2 && i + j < l1; j++) { 30 | if (c1[i + j] != c2[j]) break; 31 | } 32 | k = 0; 33 | while (k < l1 && j < l2) { 34 | if (c1[k++] != c2[j]) break; 35 | j++; 36 | } 37 | if (j == l2) { 38 | return true; 39 | } 40 | } 41 | return false; 42 | } 43 | 44 | public static void main(String[] args) { 45 | System.out.println(isStringRotation("rampatra", "swaroopram")); 46 | System.out.println(isStringRotation("rampatra", "swaroopramramram")); 47 | System.out.println(isStringRotation("rampatra", "mswaroopra")); 48 | System.out.println(isStringRotation("rampatra", "swarooppram")); 49 | System.out.println(isStringRotation("rampatra", "")); 50 | System.out.println(isStringRotation("mswaroopra", "rampatra")); 51 | System.out.println(isStringRotation("amam", "mama")); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/strings/SubStringCheck.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.strings; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 10/20/15 8 | * @time: 1:15 PM 9 | * @see: StringRotation for a similar problem. 10 | */ 11 | public class SubStringCheck { 12 | 13 | /** 14 | * Naive approach to determine whether string {@param s2} is a 15 | * substring of string {@param s1}. 16 | * 17 | * @param s1 18 | * @param s2 19 | * @return 20 | */ 21 | public static boolean isSubString(String s1, String s2) { 22 | char[] c1 = s1.toCharArray(), 23 | c2 = s2.toCharArray(); 24 | int l1 = c1.length, 25 | l2 = c2.length, 26 | i, j; 27 | 28 | for (i = 0; i <= l1 - l2; i++) { 29 | for (j = 0; j < l2 && i + j < l1; j++) { 30 | if (c1[i + j] != c2[j]) break; 31 | } 32 | if (j == l2) { 33 | return true; 34 | } 35 | } 36 | return false; 37 | } 38 | 39 | public static void main(String[] args) { 40 | System.out.println(isSubString("rampatra", "rampatra")); 41 | System.out.println(isSubString("rampatra", "")); 42 | System.out.println(isSubString("rampatra", "ram")); 43 | System.out.println(isSubString("rampatra", "rams")); 44 | System.out.println(isSubString("rampatra", "ramss")); 45 | System.out.println(isSubString("rampatra", "ar")); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/strings/SubStrings.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.strings; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * 6 | * @author rampatra 7 | * @since 10/22/15 8 | * @time: 11:16 AM 9 | */ 10 | public class SubStrings { 11 | 12 | /** 13 | * Prints all sub-strings of string {@param s} iteratively. 14 | * 15 | * @param s 16 | */ 17 | public static void printAllSubStrings(String s) { 18 | for (int i = 0; i < s.length(); i++) { 19 | for (int j = i; j < s.length(); j++) { 20 | System.out.println(s.substring(i, j + 1)); 21 | } 22 | } 23 | } 24 | 25 | /** 26 | * Prints all sub-strings of string {@param s} recursively. 27 | * 28 | * @param s 29 | */ 30 | public static void printAllSubStringsRecursive(String s) { 31 | if (s.length() == 0) return; 32 | 33 | for (int i = 1; i <= s.length(); i++) { 34 | System.out.println(s.substring(0, i)); 35 | } 36 | printAllSubStrings(s.substring(1)); 37 | } 38 | 39 | public static void main(String[] args) { 40 | System.out.println("----Iterative----"); 41 | printAllSubStrings("ram"); 42 | System.out.println("--------"); 43 | printAllSubStrings(""); 44 | System.out.println("----Recursive----"); 45 | printAllSubStringsRecursive("ram"); 46 | System.out.println("--------"); 47 | printAllSubStringsRecursive(""); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/strings/WithoutString.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.strings; 2 | 3 | import com.sun.tools.javac.util.Assert; 4 | 5 | /** 6 | * Given two strings, base and remove, return a version of the base string where all instances 7 | * of the remove string have been removed (not case sensitive). You may assume that the remove 8 | * string is length 1 or more. Remove only non-overlapping instances, so with "xxx" removing 9 | * "xx" leaves "x". 10 | * 11 | * @author rampatra 12 | * @since 2019-01-23 13 | */ 14 | public class WithoutString { 15 | 16 | private static String withoutString(String base, String remove) { 17 | String original = base; 18 | base = base.toLowerCase(); 19 | remove = remove.toLowerCase(); 20 | int baseLen = base.length(); 21 | int removeLen = remove.length(); 22 | StringBuilder sb = new StringBuilder(); 23 | 24 | for (int i = 0; i < baseLen; ) { 25 | int j = 0; 26 | // when we see a match, advance the pointer 27 | while (j < removeLen && i + j < baseLen && base.charAt(i + j) == remove.charAt(j)) { 28 | j++; 29 | } 30 | if (j == removeLen) { // an entire match was found, move ahead and skip these chars 31 | i += removeLen; 32 | } else { 33 | sb.append(original.charAt(i)); // entire match was not found so append the char to StringBuilder 34 | i++; 35 | } 36 | } 37 | return sb.toString(); 38 | } 39 | 40 | public static void main(String[] args) { 41 | Assert.check(withoutString("Hello there", "llo").equals("He there")); 42 | Assert.check(withoutString("THIS is a FISH", "is").equals("TH a FH")); 43 | Assert.check(withoutString("xxx", "x").equals("")); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/threads/Basics.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.threads; 2 | 3 | /** 4 | * Created by IntelliJ IDEA. 5 | * User: rampatra 6 | * Date: 4/15/15 7 | * Time: 11:27 PM 8 | * To change this template go to Preferences | IDE Settings | File and Code Templates 9 | */ 10 | public class Basics { 11 | public static void main(String[] args) { 12 | Runnable r = new Runnable() { 13 | @Override 14 | public void run() { 15 | for (int i = 0; i < 10; i++) { 16 | System.out.println(Thread.currentThread().getName() + ": " + i); 17 | try { 18 | Thread.sleep(1000); 19 | } catch (InterruptedException e) { 20 | 21 | } 22 | System.out.println("====== " + Thread.currentThread().getName() + " woke up ======"); 23 | } 24 | } 25 | }; 26 | Thread t1 = new Thread(r); 27 | Thread t2 = new Thread(r); 28 | Thread t3 = new Thread(r); 29 | 30 | t1.setName("T1"); 31 | t2.setName("T2"); 32 | t3.setName("T3"); 33 | 34 | t1.start(); 35 | t2.start(); 36 | t3.start(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/trees/ConstructTreeFromInOrderAndPreOrder.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.trees; 2 | 3 | import com.rampatra.base.BinaryNode; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * Created by IntelliJ IDEA. 9 | * 10 | * @author rampatra 11 | * @since 6/26/15 12 | * @time: 5:34 PM 13 | */ 14 | public class ConstructTreeFromInOrderAndPreOrder { 15 | 16 | public > void constructTreeWithInOrderAndPreOrder(List> inOrder, 17 | List> preOrder) { 18 | for (int i = 0; i < preOrder.size(); i++) { 19 | 20 | } 21 | } 22 | 23 | public static void main(String[] args) { 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/trees/DoubleTree.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.trees; 2 | 3 | import com.rampatra.base.BinaryNode; 4 | import com.rampatra.base.BinaryTree; 5 | 6 | import static java.lang.System.out; 7 | 8 | /** 9 | * Created by IntelliJ IDEA. 10 | * 11 | * @author rampatra 12 | * @since 6/26/15 13 | * @time: 6:02 PM 14 | */ 15 | public class DoubleTree { 16 | 17 | /** 18 | * Converts a given tree to its Double tree. To create a Double tree 19 | * of the given tree, create a new duplicate for each node, and insert 20 | * the duplicate as the left child of the original node. 21 | * 22 | * @param node 23 | */ 24 | public static > void doubleTree(BinaryNode node) { 25 | if (node == null) return; 26 | 27 | BinaryNode newNode = new BinaryNode<>(node.value, node.left, null); 28 | 29 | node.left = newNode; 30 | 31 | doubleTree(newNode.left); 32 | doubleTree(node.right); 33 | } 34 | 35 | public static void main(String[] args) { 36 | BinaryTree bt = new BinaryTree<>(); 37 | bt.put(6); 38 | bt.put(3); 39 | bt.put(5); 40 | bt.put(7); 41 | bt.put(8); 42 | bt.put(9); 43 | bt.breadthFirstTraversal(); 44 | out.println(); 45 | doubleTree(bt.root); 46 | out.println("BFS after Double tree: "); 47 | bt.breadthFirstTraversal(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/trees/IdenticalTrees.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.trees; 2 | 3 | import com.rampatra.base.BinaryNode; 4 | import com.rampatra.base.BinarySearchTree; 5 | 6 | import static java.lang.System.out; 7 | 8 | /** 9 | * Created by IntelliJ IDEA. 10 | * 11 | * @author rampatra 12 | * @since 6/26/15 13 | * @time: 5:36 PM 14 | */ 15 | public class IdenticalTrees { 16 | 17 | /** 18 | * Checks whether two trees having their roots at node1 and node2 19 | * are identical or not. 20 | * 21 | * @param node1 22 | * @param node2 23 | * @param 24 | * @return 25 | */ 26 | public static > boolean isIdentical(BinaryNode node1, BinaryNode node2) { 27 | if (node1 == null && node2 == null) return true; 28 | if (node1 == null && node2 != null || (node1 != null && node2 == null)) return false; 29 | 30 | if (node1.value == node2.value) { 31 | return true && isIdentical(node1.left, node2.left) && isIdentical(node1.right, node2.right); 32 | } else { 33 | return false; 34 | } 35 | } 36 | 37 | public static void main(String[] args) { 38 | BinarySearchTree bst = new BinarySearchTree<>(); 39 | bst.put(6); 40 | bst.put(3); 41 | bst.put(5); 42 | bst.put(7); 43 | bst.put(8); 44 | bst.put(9); 45 | out.println(IdenticalTrees.isIdentical(bst.root.right, bst.root.right)); 46 | out.println(IdenticalTrees.isIdentical(bst.root.right, bst.root)); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/trees/InOrderUsingStack.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.trees; 2 | 3 | import com.rampatra.base.BinaryNode; 4 | import com.rampatra.base.BinarySearchTree; 5 | import com.rampatra.base.LinkedStack; 6 | import com.rampatra.base.Stack; 7 | 8 | import static java.lang.System.out; 9 | 10 | /** 11 | * Created by IntelliJ IDEA. 12 | * 13 | * @author rampatra 14 | * @since 6/26/15 15 | * @time: 7:31 PM 16 | */ 17 | public class InOrderUsingStack { 18 | 19 | /** 20 | * In-order traversal of tree using one stack and without recursion. 21 | * 22 | * @param node 23 | */ 24 | public static > void inOrderUsingStack(BinaryNode node) { 25 | if (node == null) return; 26 | 27 | Stack> stack = new LinkedStack<>(); 28 | 29 | BinaryNode curr = node; // set root node as current node 30 | stack.push(curr); // push current node 31 | 32 | while (!stack.isEmpty()) { 33 | 34 | while (curr != null) { 35 | curr = curr.left; 36 | if (curr != null) stack.push(curr); // push all left nodes of the current node 37 | } 38 | 39 | BinaryNode top = stack.pop(); 40 | out.print(top.value); // print top of stack 41 | curr = top.right; 42 | if (curr != null) stack.push(curr); // push right child of top node 43 | } 44 | } 45 | 46 | public static void main(String[] args) { 47 | BinarySearchTree bst = new BinarySearchTree<>(); 48 | bst.put(6); 49 | bst.put(3); 50 | bst.put(5); 51 | bst.put(7); 52 | bst.put(8); 53 | bst.put(9); 54 | inOrderUsingStack(bst.root); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/trees/LeafNodes.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.trees; 2 | 3 | import com.rampatra.base.BinaryNode; 4 | import com.rampatra.base.BinaryTree; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * 9 | * @author rampatra 10 | * @since 6/26/15 11 | * @time: 6:08 PM 12 | */ 13 | public class LeafNodes { 14 | 15 | /** 16 | * Returns the number of leaf nodes in a binary tree. 17 | * 18 | * @return 19 | */ 20 | public static > int countLeafNodes(BinaryNode node) { 21 | if (node == null) { 22 | return 0; 23 | } else if (node.left == null && node.right == null) { 24 | return 1; 25 | } else { 26 | return countLeafNodes(node.left) + countLeafNodes(node.right); 27 | } 28 | } 29 | 30 | public static void main(String[] args) { 31 | BinaryTree bt = new BinaryTree<>(); 32 | bt.put(6); 33 | bt.put(3); 34 | bt.put(5); 35 | bt.put(7); 36 | bt.put(8); 37 | bt.put(9); 38 | System.out.println(countLeafNodes(bt.root)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/rampatra/trees/MirrorTree.java: -------------------------------------------------------------------------------- 1 | package com.rampatra.trees; 2 | 3 | import com.rampatra.base.BinaryNode; 4 | import com.rampatra.base.BinaryTree; 5 | 6 | /** 7 | * Created by IntelliJ IDEA. 8 | * 9 | * @author rampatra 10 | * @since 6/26/15 11 | * @time: 7:03 PM 12 | */ 13 | public class MirrorTree { 14 | 15 | /** 16 | * Converts a Tree to its Mirror Tree. 17 | *

18 | * MIRROR OF A BINARY TREE T is another Binary Tree M(T) with 19 | * left and right children of all non-leaf nodes interchanged. 20 | *

21 | * TIP: In-order traversal of mirror tree is exactly the 22 | * reverse of the in-order traversal of the original tree. 23 | */ 24 | public static > void mirror(BinaryNode node) { 25 | if (node == null) return; 26 | 27 | // mirror sub-trees 28 | mirror(node.left); 29 | mirror(node.right); 30 | 31 | // swap nodes 32 | BinaryNode tempNode; 33 | tempNode = node.left; 34 | node.left = node.right; 35 | node.right = tempNode; 36 | } 37 | 38 | public static void main(String[] args) { 39 | BinaryTree bt = new BinaryTree<>(); 40 | bt.put(6); 41 | bt.put(3); 42 | bt.put(5); 43 | bt.put(7); 44 | bt.put(8); 45 | bt.put(9); 46 | System.out.println("Original Tree"); 47 | bt.breadthFirstTraversal(); 48 | System.out.println("\nMirror Tree"); 49 | mirror(bt.root); 50 | bt.breadthFirstTraversal(); 51 | } 52 | } 53 | --------------------------------------------------------------------------------