├── .gitignore ├── Code-Practice.iml ├── Leetcode-InterviewBit-DSA-Practice.iml ├── README.md ├── lib ├── kotlin-reflect-sources.jar ├── kotlin-reflect.jar ├── kotlin-stdlib-2.2.0-Beta1-javadoc.jar ├── kotlin-stdlib-2.2.0-Beta1-sources.jar ├── kotlin-stdlib-2.2.0-Beta1.jar ├── kotlin-stdlib-jdk7-2.2.0-Beta1-javadoc.jar ├── kotlin-stdlib-jdk7-2.2.0-Beta1-sources.jar ├── kotlin-stdlib-jdk7-2.2.0-Beta1.jar ├── kotlin-stdlib-jdk8-2.2.0-Beta1-javadoc.jar ├── kotlin-stdlib-jdk8-2.2.0-Beta1-sources.jar ├── kotlin-stdlib-jdk8-2.2.0-Beta1.jar ├── kotlin-stdlib.jar ├── kotlin-test-sources.jar ├── kotlin-test.jar ├── kotlinx-coroutines-android-1.5.1-native-mt-sources.jar ├── kotlinx-coroutines-android-1.5.1-native-mt.jar ├── kotlinx-coroutines-core-common-1.3.0-sources.jar ├── kotlinx-coroutines-core-common-1.3.0.jar ├── kotlinx-coroutines-core-jvm-1.4.1-sources.jar ├── kotlinx-coroutines-core-jvm-1.4.1.jar ├── reactive-streams-1.0.3-sources.jar ├── reactive-streams-1.0.3.jar ├── rxandroid-2.1.1-sources.jar ├── rxandroid-2.1.1.jar ├── rxjava-2.2.8-sources.jar └── rxjava-2.2.8.jar ├── res ├── Bipartite-graph.png ├── BucketSort.png ├── Count-of-Smaller-Numbers-After-Self.png ├── Delete-OR-Extract-Min-from-Heap.gif ├── Insert-Bubble-Up-Min-Heap.gif ├── SCCUndirected.png ├── SpellChecker.png ├── backtracking1.png ├── backtracking2.png ├── bfs.png ├── bfs_matrix.png ├── bfs_traversal.png ├── bubble_sort.gif ├── dfs.png ├── diagram1.png ├── diagram2.png ├── divide-two-integers.png ├── divide_and_conquer.png ├── find_median_stream.png ├── find_peak_element.png ├── graph_cycle.png ├── grid_ex1.jpeg ├── grid_ex2.jpeg ├── histogram.jpg ├── k_highest_rank_hotel_1.png ├── k_highest_rank_hotel_2.png ├── k_highest_rank_hotel_3.png ├── keypad.png ├── kthtree1.jpeg ├── leetcode-1267.jpeg ├── line1.jpeg ├── line2.jpeg ├── matrix-sum.png ├── maximal_rectangle.jpg ├── maximum-subarray-sum.jpeg ├── maximum_profit.png ├── merge_sort.png ├── mht.jpeg ├── minesweeper-1.jpeg ├── minesweeper-2.jpeg ├── most_water.jpeg ├── n_ary_tree.png ├── next-permutation-algorithm.svg ├── permutation_recursion.gif ├── permutation_tree.jpeg ├── permutation_tree_2.jpeg ├── platform.png ├── pq-with-heap.jpg ├── pre-tree.jpeg ├── queens.jpg ├── rainwatertrap.png ├── rec1.jpg ├── rec2.jpg ├── rectangle_coordinates.png ├── recursion_tree_frog_jump.jpeg ├── remove_node.jpeg ├── robot.png ├── rotting_orange.png ├── server_handle_requests.png ├── sqrt_root.png ├── sqrt_root1.png ├── sqrt_root2.png ├── sudoku_1.png ├── sudoku_2.png ├── toplogical_Sort.png ├── topo_sort_dictionary.png ├── trie_pic.png ├── unique_bst.jpeg ├── unique_paths.png ├── vertical_travarsal_tree.png ├── vertical_travarsal_tree_sol_1.png ├── vertical_travarsal_tree_sol_2.png ├── vertical_travarsal_tree_sol_3.png ├── vertical_travarsal_tree_sol_4.png └── word_search.jpeg ├── src └── main │ └── java │ ├── javaclasses │ ├── Algorithm │ │ ├── AVLTreeImplementation.java │ │ ├── BellmanFordAlgorithm.java │ │ ├── BfsGraph_AdjacencyList.java │ │ ├── BfsGraph_AdjacencyMatrix.java │ │ ├── BucketSort.java │ │ ├── DfsGraph_AdjacencyList.java │ │ ├── DijkstraAlgorithm.java │ │ ├── KMPAlgorithm.java │ │ ├── KadaneAlgorithm.java │ │ ├── RadixSort.java │ │ ├── SegmentTreeMinimumRangeQuery.java │ │ ├── SortingAlgorithm.java │ │ ├── SquareRootDecomposition.java │ │ ├── TopologicalSort.java │ │ └── Trie_InsertDeleteSearch.java │ ├── Array │ │ ├── ArrayNesting.java │ │ ├── ArrayProduct.java │ │ ├── FindDuplicate.java │ │ ├── FindIntersection.java │ │ ├── FindKclosestElements.java │ │ ├── FindMissingNumber.java │ │ ├── FindMissingPositive.java │ │ ├── FindPairWithGivenDifference.java │ │ ├── HighestProductOf3.java │ │ ├── IntersectionOfTwoArraysII.java │ │ ├── JumpGame.java │ │ ├── JumpGame_II.java │ │ ├── LargestNumber.java │ │ ├── LongestConsecutiveSequence.java │ │ ├── MajorityElement.java │ │ ├── MakeEqualElementArray.java │ │ ├── MaxAscendingSubarraySum.java │ │ ├── MaxDifference.java │ │ ├── MaxDistance.java │ │ ├── MaxLengthIncreasingSubarrayWithOneDeletion.java │ │ ├── MaximumAbsoluteDifference.java │ │ ├── MaximumContiguousSubarray.java │ │ ├── MaximumGap.java │ │ ├── MaximumSumSubarrayUsingPrefixSum.java │ │ ├── MergeKSortedArray.java │ │ ├── MinCost_MakeArrayElementEqual.java │ │ ├── MinimumLightsToActivate.java │ │ ├── NextPermutation.java │ │ ├── PairSum.java │ │ ├── PickFromBothSides.java │ │ ├── ReduceArraySizeTohalf.java │ │ ├── SecondSmallest.java │ │ ├── ShuffleArray.java │ │ ├── SnapshotArray.java │ │ ├── Sort012.java │ │ ├── SubArraySum.java │ │ ├── SuffixArray.java │ │ └── WaveArray.java │ ├── ArrayList │ │ ├── FlattenListIterator.java │ │ ├── GroupAnagrams.java │ │ ├── InsertInterval.java │ │ ├── MergeTwoSortedList_II.java │ │ ├── PascalTriangle.java │ │ ├── RangeModule.java │ │ ├── RearrangeList.java │ │ └── RemoveDuplicateFromSortedList_II.java │ ├── Backtracking │ │ ├── CombinationSum.java │ │ ├── GeneralApproachToBacktracking.java │ │ ├── GraphColoring.java │ │ ├── JewelMaze.java │ │ ├── NQueens.java │ │ ├── PalindromePartitioning.java │ │ ├── SudokuSolver.java │ │ └── WildCardMatching.java │ ├── BinarySearch │ │ ├── ArrayQueries.java │ │ ├── FindNthNumberInMergedList.java │ │ ├── FindPeakElement.java │ │ ├── MaximumRunningTimeNComputers.java │ │ ├── MedianTwoSortedArray.java │ │ ├── MinimumTimeToCompleteTrips.java │ │ ├── SearchInRotatedSortedArray.java │ │ ├── SearchRange.java │ │ └── SplitArrayToKSubArrayWithMinSum.java │ ├── BitManipulation │ │ ├── CountWaysUsingBitMask.java │ │ ├── DivideTwoIntegers.java │ │ ├── MinimumBitsToFlipToMakeArrayEqual.java │ │ ├── NextPowerOf2.java │ │ ├── ReverseBits.java │ │ ├── SingleNumber.java │ │ ├── SumOfTwoIntegers.java │ │ └── XorQueries.java │ ├── Codility │ │ ├── BinaryGap.java │ │ ├── CropMessage.java │ │ ├── MaxCounters.java │ │ ├── MinAvgTwoSlice.java │ │ ├── MinimumNumberOfCars.java │ │ ├── MinimumNumberOfFilters.java │ │ └── TapeEquilibrium.java │ ├── DataStructure │ │ ├── CustomHashMapImpl.java │ │ ├── DequeExample.java │ │ ├── DesignSearchAutocompleteSystem.java │ │ ├── DoublyLinkedList.java │ │ ├── InsertDeleteGetRandom.java │ │ ├── LinkedListInsertDeleteSearch.java │ │ ├── LruCache │ │ │ ├── LRUCache.java │ │ │ └── Node.java │ │ └── Trie │ │ │ ├── DesignAdd_SearchWords.java │ │ │ └── TrieDataStructure.java │ ├── DisjointSet │ │ ├── DetectCycleUsingUnionFind.java │ │ ├── LexicographicSmallestString.java │ │ ├── SimilarStringGroup.java │ │ └── SocialNetwork.java │ ├── Divide_and_Conquer │ │ └── LongestSubstringWith_K_RepeatedChars.java │ ├── DynamicProgramming │ │ ├── BestTimeToBuyStockII.java │ │ ├── BestTimeToBuyStockIII.java │ │ ├── Bitmask │ │ │ └── MinimumCostTaskAssign.java │ │ ├── CoinChange.java │ │ ├── CuttingRod.java │ │ ├── DistinctSubsequence.java │ │ ├── EditDistance.java │ │ ├── FrogJump.java │ │ ├── InterleavingString.java │ │ ├── KnapSackProblem.java │ │ ├── LongestCommonSubsequence.java │ │ ├── LongestIncreasingSubsequence.java │ │ ├── MaxSumWithoutAdjacentElement.java │ │ ├── MaximumBudget.java │ │ ├── MaximumLengthOfRepeatedSubarray.java │ │ ├── MaximumProfitJobScheduling.java │ │ ├── MaximumSumSquareSubmatrix.java │ │ ├── MinCostForTickets.java │ │ ├── MinSumPathMatrix.java │ │ ├── NthStairCase.java │ │ ├── RegularExpressionMatch.java │ │ ├── SolvingQuestionWithBrainPower.java │ │ ├── StoneGameIII.java │ │ ├── SubsetWithGivenSum.java │ │ └── UniquePaths.java │ ├── Graph │ │ ├── BFS │ │ │ ├── AsFarFromLand.java │ │ │ ├── BFS_Shortest_path.java │ │ │ ├── BusRoutes.java │ │ │ ├── JumpingNumbers.java │ │ │ ├── K_HighestRankHotelWithinPrice.java │ │ │ ├── RottingOrange.java │ │ │ ├── ShortestDistanceBetweenCells.java │ │ │ ├── ShortestDistanceMatrix.java │ │ │ ├── ShortestPathAlternatingColors.java │ │ │ ├── ShortestPathFromSourceToDestinationMatrix.java │ │ │ ├── ShortestPathVisitingAllNodes.java │ │ │ ├── SnakeAndLadder.java │ │ │ ├── WaterSupplyRoute.java │ │ │ └── WordLadder.java │ │ ├── DFS │ │ │ ├── AllPathsFromSourceToTarget_DAG.java │ │ │ ├── CombinationPhoneNumber.java │ │ │ ├── CountServerThatCommunicate.java │ │ │ ├── CourseSchedule.java │ │ │ ├── CourseScheduleII.java │ │ │ ├── DetectCycleInDirectedGraph.java │ │ │ ├── DetectCycleInUndirectedGraph.java │ │ │ ├── FindIfPathExists.java │ │ │ ├── FindPath.java │ │ │ ├── KeysAndRooms.java │ │ │ ├── LongestPathFromNode.java │ │ │ ├── MinFuelCostToCapital.java │ │ │ ├── NeighbourNodesWithinDistance.java │ │ │ ├── NodesInSubTreeWithSameLabel.java │ │ │ ├── NumberOfConnectedComponents.java │ │ │ ├── NumberOfIslands.java │ │ │ ├── PossibleBipartition.java │ │ │ ├── RobotRoomCleaner.java │ │ │ ├── UniquePaths_II.java │ │ │ ├── WordSearchII.java │ │ │ └── WordSearch_DFS.java │ │ ├── MinesWeeper.java │ │ ├── TimeNeededTo_InformAll.java │ │ └── Trie │ │ │ └── WordBreakII.java │ ├── GreedyAlgorithm │ │ ├── ContainerWithMostWater.java │ │ ├── DistributeCandy.java │ │ ├── FractionalKnapsack.java │ │ ├── LongestPalindrome.java │ │ ├── MaximumMatrixSum.java │ │ ├── MaximumMeetings.java │ │ ├── MergeIntervals.java │ │ ├── MinMaxPairSum.java │ │ ├── MinimumCostHomeComingRobot.java │ │ ├── MinimumNumberOfArrows.java │ │ ├── MinimumNumberOfOperationToFormArray.java │ │ ├── MinimumNumberOfPlatformRequired.java │ │ ├── NonOverlappingIntervals.java │ │ ├── SmallestSubsequenceOfDistinctCharacters.java │ │ └── TwoCityScheduling.java │ ├── HashTable │ │ ├── ContinuousSubarraySum.java │ │ ├── CountSubarrayWithEqualOccurences.java │ │ ├── DegreeOfAnArray.java │ │ ├── DesignHashMap.java │ │ ├── DistinctNumbersInWindow.java │ │ ├── MinAreaRectangle.java │ │ ├── PairWithGivenXor.java │ │ └── SlowestKey.java │ ├── HeapPriorityQueue │ │ ├── CheckIfMaxMinHeap.java │ │ ├── ContinuousSubarray.java │ │ ├── FindMedianFromStream.java │ │ ├── IPO.java │ │ ├── KLargest_Smallest_Elements.java │ │ ├── KthLargestElementInStream.java │ │ ├── KthSmallElementInSortedMatrix.java │ │ ├── MaxMinHeapImplementation.java │ │ ├── MaximumSumTwoInterval.java │ │ ├── MeetingRoomsII.java │ │ ├── MergeKSortedArray.java │ │ ├── MergeKSortedLists.java │ │ ├── MinimumNumberOfRefuelingStops.java │ │ ├── PriorityQueueImpl.java │ │ ├── PriorityQueueWithCustomComparator.java │ │ ├── ReArrangeArray.java │ │ ├── ReorganizeString.java │ │ ├── ServerHandleMostRequests.java │ │ ├── SingleThreadedCPU.java │ │ ├── SmallestRangeCoveringKLists.java │ │ └── TopKFrequentElements.java │ ├── LinkedList │ │ ├── AddTwoNumbersAsLinkedList_II.java │ │ ├── ArrayToLinkedList.java │ │ ├── LinkedListIntersection.java │ │ ├── ListNode.java │ │ ├── MergeTwoLinkedList.java │ │ ├── OddEvenLinkList.java │ │ ├── PalindromeList.java │ │ ├── RemoveDuplicateFromSortedList.java │ │ ├── RemoveNthNodeFromEndOfList.java │ │ ├── ReverseLinkList.java │ │ ├── ReverseNodesInKGroups.java │ │ ├── RotateList.java │ │ ├── SortLinkedList.java │ │ └── SwapPairNodes.java │ ├── Matrix │ │ ├── LuckyNumbersInMatrix.java │ │ ├── RotateImage.java │ │ ├── Search2dMatrix.java │ │ ├── SetMatrixZeroes.java │ │ ├── Shift2D_Grid.java │ │ ├── SpiralMatrixII.java │ │ └── ValidSodoku.java │ ├── NumberTheory │ │ └── Math │ │ │ ├── CheckIfStraightLine.java │ │ │ ├── CountDiv.java │ │ │ ├── FindNthFibonacci.java │ │ │ ├── FourSum.java │ │ │ ├── HappyNumber.java │ │ │ ├── IncreasingTripletSubsequence.java │ │ │ ├── IntegerToRoman.java │ │ │ ├── KclosestPoints.java │ │ │ ├── MaxTripletSum.java │ │ │ ├── NextSmallestPalindrome.java │ │ │ ├── Permutation_Prime.java │ │ │ ├── Pow_x_n.java │ │ │ ├── PowerOfNumber.java │ │ │ ├── ProductOfArrayExceptSelf.java │ │ │ ├── ReachNumber.java │ │ │ ├── ReverseInteger.java │ │ │ ├── StatisticsFromLargeSample.java │ │ │ └── TwoSum.java │ ├── OOPDesign │ │ └── UnixFileApi │ │ │ ├── File.java │ │ │ ├── FileSystem.java │ │ │ ├── Filter │ │ │ ├── ExtensionFilter.java │ │ │ ├── Filter.java │ │ │ ├── NameFilter.java │ │ │ └── SizeFilter.java │ │ │ ├── Main.java │ │ │ └── SearchFile.java │ ├── OutputQuiz │ │ ├── AbstractClassQuiz.java │ │ ├── CollectionInsertionOrder.java │ │ ├── HashMap_Equals_HashCode.java │ │ ├── InheritanceQuiz.java │ │ ├── OutputQuiz.java │ │ ├── PassByValueReferenceOutput.java │ │ ├── ReduceExampleOutput.java │ │ ├── StackQueueOutput.java │ │ ├── StaticBlock.java │ │ └── ThreadOutput.java │ ├── Recursion │ │ ├── AllStringPermutation.java │ │ ├── EmployeeReporting.java │ │ ├── GenerateParenthesis.kt │ │ ├── Permutations.java │ │ ├── ReverseString.java │ │ └── SubsetSum.java │ ├── StackQueue │ │ ├── InfixToPostfix.java │ │ ├── LargestRectangleHistogram.java │ │ ├── LongestValidParenthesis.java │ │ ├── MaximalRectangle.java │ │ ├── MaximumWidthRamp.java │ │ ├── MinRemoveToMakeValidParenthesis.java │ │ ├── MinStack.java │ │ ├── NextGreaterElement.java │ │ ├── NextPermutation.java │ │ ├── NumberOfCustomer_iceCream.java │ │ ├── PostfixEvaluation.java │ │ ├── StackOperation.java │ │ ├── StackUsingQueues.java │ │ ├── ValidParenthesis.java │ │ └── ValidParenthesis_II.java │ ├── Strings │ │ ├── AllStringPermutation.java │ │ ├── BackspaceStringCompare.java │ │ ├── BalancedParenthesis.java │ │ ├── DetectCapital.java │ │ ├── DuplicateCharacter.java │ │ ├── FindFirstNonRepeatedCharacter.java │ │ ├── GroupAnagramTogether.java │ │ ├── ImplementStrStr.java │ │ ├── IsomorphicString.java │ │ ├── LetterCombinationNumber.java │ │ ├── LongestCommonPrefix.java │ │ ├── LongestPalindromicSubstring.java │ │ ├── LongestSubstringWithoutRepeatingCharacters.java │ │ ├── MakePalindromeByAddingCharacter.java │ │ ├── NonRepeatingStream.java │ │ ├── OrderlyQueue.java │ │ ├── PartitionLabels.java │ │ ├── PerformStringShift.java │ │ ├── PermutationString.java │ │ ├── RansomNote.java │ │ ├── RemoveAdjacentDuplicate.java │ │ ├── ReverseEachWords.java │ │ ├── ReverseString.java │ │ ├── ReverseWordsWithoutSpecialCharacters.java │ │ ├── RomanToInteger.java │ │ ├── SortCharactersByFrequency.java │ │ ├── Subsequence.java │ │ ├── SubstringWithConcatOfWords.java │ │ ├── UniqueCharacter.java │ │ ├── ValidAnagram.java │ │ └── Word_split_Coderbyte.java │ ├── Tree │ │ ├── BinaryTreeRightView.java │ │ ├── BottomViewTree.java │ │ ├── BstIdentical.java │ │ ├── Check_If_TreeBalanced.java │ │ ├── Construct_BST_From_Preorder.java │ │ ├── ConvertSortedArrayToBST.java │ │ ├── ConvertToBalancedBST.java │ │ ├── CountNodesEqualToAverageSubtree.java │ │ ├── CountSmallerNumberAfterSelf.java │ │ ├── DeleteNodeInBST.java │ │ ├── DiameterBinaryTree.java │ │ ├── InvertTree.java │ │ ├── IsTreeBST.java │ │ ├── KthSmallestElementInBst.java │ │ ├── LeafSimilarTrees.java │ │ ├── LevelOrderTraversal.java │ │ ├── LongestConsecutiveSequenceInBT.java │ │ ├── LowestCommonAncestorBST.java │ │ ├── LowestCommonAncestorBT.java │ │ ├── MaxDiffBetweenNodeAncestor.java │ │ ├── MaxHeightOfTree.java │ │ ├── MaxMin_DepthOfTree.java │ │ ├── MaxWidthBinaryTree.java │ │ ├── MaximumAverageSubTree.java │ │ ├── MinAbsoluteDifferenceInBST.java │ │ ├── MinimumHeightTrees.java │ │ ├── N_ary_TreeTraversal.java │ │ ├── PathSum.java │ │ ├── SecondMinimumNodeInBinaryTree.java │ │ ├── SerializeDeserializeBinaryTree.java │ │ ├── SymmetricTree.java │ │ ├── TreeNode.java │ │ ├── TreeTraversal.java │ │ ├── UniqueBinarySearchTree.java │ │ ├── VerifyPreOrderSerialization.java │ │ └── VerticalSumBinaryTree.java │ ├── TwoPointer │ │ ├── CommonLongestSubstringPattern.java │ │ ├── FindAnagrams.java │ │ ├── FruitsIntoBaskets.java │ │ ├── GasStation.java │ │ ├── LongestSubstringWithKDistinctCharacters.java │ │ ├── LongestSubstringWithoutRepeating.java │ │ ├── MaxContiguousSubarrayK.java │ │ ├── MinimumWindowSubstring.java │ │ ├── MoveZeroesAtEnd.java │ │ ├── PairWithGivenDifference.java │ │ ├── PerfectPeakArray.java │ │ ├── RemoveElementFromArray.java │ │ ├── SortArrayOfSquares.java │ │ ├── SortColors.java │ │ ├── SubarrayGivenSum.java │ │ ├── SubarraySizeKthreshold.java │ │ ├── ThreeSum.java │ │ ├── ThreeSumClosest.java │ │ └── TrappingRainWater.java │ └── Utility │ │ ├── BSTInsertDuplicate.java │ │ ├── BestTimeToBuyStock.java │ │ ├── BigIntegerExample.java │ │ ├── CalculateVacationWeeks.java │ │ ├── CreditDebitCardNumberValidator.java │ │ ├── FlatToHierarchicalTree.java │ │ ├── GridDistance.java │ │ ├── HashMapCustomObjectKey.java │ │ ├── JavaStdInOut.java │ │ ├── MobileBill.java │ │ ├── MobileKeyboard.java │ │ ├── MultiCustomComparator.java │ │ ├── NumberPasswordValidation.java │ │ ├── Sort2DArray.java │ │ ├── SortHashMap.java │ │ ├── SpellCheckerUsingTrie.java │ │ ├── TestClass.java │ │ ├── ThreadSafeSingleton.java │ │ ├── TreeMapCustomComparatorByValue.java │ │ ├── TreeSet_FloorCeiling.java │ │ ├── URLConnectionReadData.java │ │ └── VariableArguments.java │ └── kotlinclasses │ ├── Algorithm │ ├── LineSweep.kt │ └── MooreVotingAlgorithm.kt │ ├── Array │ ├── MergeSortedArray.kt │ ├── RemoveDuplicateFromSortedArrayII.kt │ └── RotateArray.kt │ ├── BinarySearch │ ├── BinarySearchExample.kt │ └── FindPeakElement.kt │ ├── Collections │ ├── ConvertListToMap.kt │ ├── KotlinCollectionFunctions.kt │ ├── KotlinSequenceVsCollection.kt │ ├── ListDifference.kt │ └── MergeInterval.kt │ ├── Concepts │ ├── Coroutine │ │ ├── CoroutineExample.kt │ │ ├── KotlinCoroutineScopeFlow.kt │ │ └── SupervisorScope.kt │ ├── Flow │ │ └── KotlinFlowOperators.kt │ ├── InlineClass_Functions.kt │ ├── InterfaceDelegation.kt │ ├── KotlinGenerics.kt │ ├── Lambda_Closure_Example.kt │ ├── Oop │ │ ├── Constructors.kt │ │ ├── MultipleInheritance.kt │ │ └── VisibilityModifiers.kt │ ├── OperatorFunction.kt │ ├── RxJavaObservables.kt │ ├── ScopeFunction.kt │ ├── SealedClassEx.kt │ └── Thread │ │ ├── DeadlockPreventation.kt │ │ ├── ThreadCreation.kt │ │ └── ThreadSafeCounter.kt │ ├── DataStructure │ └── LRUCache.kt │ ├── DynamicProgramming │ └── BestTimeToBuySellStockII.kt │ ├── Graph │ ├── AlienDictionary.kt │ ├── BFS_Shortest_path.kt │ └── EvaluateDivision.kt │ ├── HashTable │ ├── CountSpecialSubsequence.kt │ ├── CustomHashMap.kt │ ├── IsomorphicStrings.kt │ ├── LargestOutlierInArray.kt │ ├── MapVsFlatMap.kt │ └── SortHashMap.kt │ ├── HeapPriorityQueue │ └── TaskScheduler.kt │ ├── LinkedList │ ├── AddTwoNumbers.kt │ ├── CopyListWithRandomPointer.kt │ ├── LinkedListCycle.kt │ ├── ListNode.kt │ └── ReverseLinkedList_II.kt │ ├── Math │ ├── PalindromeNumber.kt │ ├── PlusOne.kt │ └── RandomPickWithWeight.kt │ ├── OutputQuiz │ └── OutputKotlin.kt │ ├── Practice │ ├── KotlinPractice.kt │ └── TestClass.kt │ ├── Problems │ ├── LogDump.kt │ └── TopURLAccessed.kt │ ├── Strings │ ├── GroupAnagrams.kt │ ├── LongestSelfContainedSubstring.kt │ └── UniquePalindromicSubsequence.kt │ ├── Tree │ ├── BinaryTreeMaximumPathSum.kt │ ├── MaxMinProductInBinaryTree.kt │ └── VerticalTraversalBinaryTree.kt │ ├── TwoPointer │ ├── MinimumSizeSubarraySum.kt │ └── ValidPalindrome.kt │ └── Utility │ ├── BinaryAddition.kt │ ├── NumberToWord.kt │ └── RightLengthEncoding.kt ├── step_1.png ├── step_2.png ├── step_3.png └── step_4.png /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/* 2 | out/* -------------------------------------------------------------------------------- /Code-Practice.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /Leetcode-InterviewBit-DSA-Practice.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Leetcode-InterviewBit-Practice-Problems 2 | A project containing my solution for Leetcode, InterviewBit problems along with DSA Practice problems. 3 | 4 | ## Build and run 5 | 6 | To run the project and source files: 7 | 8 | Clone the repo -> Open Android Studio -> Select File -> Open the Repository folder. 9 | 10 | The project is configured to run single `Java` & `Kotlin` files from Android Studio. 11 | 12 | After Importing the project to Android Studio: 13 | 14 | 1. Click Add Configuration 15 | 16 | ![](step_1.png) 17 | 18 | 2. Select plus icon at top left and create an Application. 19 | 20 | ![](step_2.png) 21 | 22 | 3. Leave it as unnamed and click apply and ok. 23 | 24 | ![](step_3.png) 25 | 26 | 4. Now you can go to `src\main\javaclasses` or `src\main\kotlinclasses` folder and run/debug single Java/Kotlin class from Android studio. 27 | 28 | ![](step_4.png) 29 | 30 | ## Add Custom Library 31 | 32 | You can add custom library and sources into the `lib` folder and use it in your class. -------------------------------------------------------------------------------- /lib/kotlin-reflect-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlin-reflect-sources.jar -------------------------------------------------------------------------------- /lib/kotlin-reflect.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlin-reflect.jar -------------------------------------------------------------------------------- /lib/kotlin-stdlib-2.2.0-Beta1-javadoc.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlin-stdlib-2.2.0-Beta1-javadoc.jar -------------------------------------------------------------------------------- /lib/kotlin-stdlib-2.2.0-Beta1-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlin-stdlib-2.2.0-Beta1-sources.jar -------------------------------------------------------------------------------- /lib/kotlin-stdlib-2.2.0-Beta1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlin-stdlib-2.2.0-Beta1.jar -------------------------------------------------------------------------------- /lib/kotlin-stdlib-jdk7-2.2.0-Beta1-javadoc.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlin-stdlib-jdk7-2.2.0-Beta1-javadoc.jar -------------------------------------------------------------------------------- /lib/kotlin-stdlib-jdk7-2.2.0-Beta1-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlin-stdlib-jdk7-2.2.0-Beta1-sources.jar -------------------------------------------------------------------------------- /lib/kotlin-stdlib-jdk7-2.2.0-Beta1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlin-stdlib-jdk7-2.2.0-Beta1.jar -------------------------------------------------------------------------------- /lib/kotlin-stdlib-jdk8-2.2.0-Beta1-javadoc.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlin-stdlib-jdk8-2.2.0-Beta1-javadoc.jar -------------------------------------------------------------------------------- /lib/kotlin-stdlib-jdk8-2.2.0-Beta1-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlin-stdlib-jdk8-2.2.0-Beta1-sources.jar -------------------------------------------------------------------------------- /lib/kotlin-stdlib-jdk8-2.2.0-Beta1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlin-stdlib-jdk8-2.2.0-Beta1.jar -------------------------------------------------------------------------------- /lib/kotlin-stdlib.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlin-stdlib.jar -------------------------------------------------------------------------------- /lib/kotlin-test-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlin-test-sources.jar -------------------------------------------------------------------------------- /lib/kotlin-test.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlin-test.jar -------------------------------------------------------------------------------- /lib/kotlinx-coroutines-android-1.5.1-native-mt-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlinx-coroutines-android-1.5.1-native-mt-sources.jar -------------------------------------------------------------------------------- /lib/kotlinx-coroutines-android-1.5.1-native-mt.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlinx-coroutines-android-1.5.1-native-mt.jar -------------------------------------------------------------------------------- /lib/kotlinx-coroutines-core-common-1.3.0-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlinx-coroutines-core-common-1.3.0-sources.jar -------------------------------------------------------------------------------- /lib/kotlinx-coroutines-core-common-1.3.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlinx-coroutines-core-common-1.3.0.jar -------------------------------------------------------------------------------- /lib/kotlinx-coroutines-core-jvm-1.4.1-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlinx-coroutines-core-jvm-1.4.1-sources.jar -------------------------------------------------------------------------------- /lib/kotlinx-coroutines-core-jvm-1.4.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/kotlinx-coroutines-core-jvm-1.4.1.jar -------------------------------------------------------------------------------- /lib/reactive-streams-1.0.3-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/reactive-streams-1.0.3-sources.jar -------------------------------------------------------------------------------- /lib/reactive-streams-1.0.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/reactive-streams-1.0.3.jar -------------------------------------------------------------------------------- /lib/rxandroid-2.1.1-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/rxandroid-2.1.1-sources.jar -------------------------------------------------------------------------------- /lib/rxandroid-2.1.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/rxandroid-2.1.1.jar -------------------------------------------------------------------------------- /lib/rxjava-2.2.8-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/rxjava-2.2.8-sources.jar -------------------------------------------------------------------------------- /lib/rxjava-2.2.8.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/lib/rxjava-2.2.8.jar -------------------------------------------------------------------------------- /res/Bipartite-graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/Bipartite-graph.png -------------------------------------------------------------------------------- /res/BucketSort.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/BucketSort.png -------------------------------------------------------------------------------- /res/Count-of-Smaller-Numbers-After-Self.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/Count-of-Smaller-Numbers-After-Self.png -------------------------------------------------------------------------------- /res/Delete-OR-Extract-Min-from-Heap.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/Delete-OR-Extract-Min-from-Heap.gif -------------------------------------------------------------------------------- /res/Insert-Bubble-Up-Min-Heap.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/Insert-Bubble-Up-Min-Heap.gif -------------------------------------------------------------------------------- /res/SCCUndirected.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/SCCUndirected.png -------------------------------------------------------------------------------- /res/SpellChecker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/SpellChecker.png -------------------------------------------------------------------------------- /res/backtracking1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/backtracking1.png -------------------------------------------------------------------------------- /res/backtracking2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/backtracking2.png -------------------------------------------------------------------------------- /res/bfs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/bfs.png -------------------------------------------------------------------------------- /res/bfs_matrix.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/bfs_matrix.png -------------------------------------------------------------------------------- /res/bfs_traversal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/bfs_traversal.png -------------------------------------------------------------------------------- /res/bubble_sort.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/bubble_sort.gif -------------------------------------------------------------------------------- /res/dfs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/dfs.png -------------------------------------------------------------------------------- /res/diagram1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/diagram1.png -------------------------------------------------------------------------------- /res/diagram2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/diagram2.png -------------------------------------------------------------------------------- /res/divide-two-integers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/divide-two-integers.png -------------------------------------------------------------------------------- /res/divide_and_conquer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/divide_and_conquer.png -------------------------------------------------------------------------------- /res/find_median_stream.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/find_median_stream.png -------------------------------------------------------------------------------- /res/find_peak_element.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/find_peak_element.png -------------------------------------------------------------------------------- /res/graph_cycle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/graph_cycle.png -------------------------------------------------------------------------------- /res/grid_ex1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/grid_ex1.jpeg -------------------------------------------------------------------------------- /res/grid_ex2.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/grid_ex2.jpeg -------------------------------------------------------------------------------- /res/histogram.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/histogram.jpg -------------------------------------------------------------------------------- /res/k_highest_rank_hotel_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/k_highest_rank_hotel_1.png -------------------------------------------------------------------------------- /res/k_highest_rank_hotel_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/k_highest_rank_hotel_2.png -------------------------------------------------------------------------------- /res/k_highest_rank_hotel_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/k_highest_rank_hotel_3.png -------------------------------------------------------------------------------- /res/keypad.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/keypad.png -------------------------------------------------------------------------------- /res/kthtree1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/kthtree1.jpeg -------------------------------------------------------------------------------- /res/leetcode-1267.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/leetcode-1267.jpeg -------------------------------------------------------------------------------- /res/line1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/line1.jpeg -------------------------------------------------------------------------------- /res/line2.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/line2.jpeg -------------------------------------------------------------------------------- /res/matrix-sum.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/matrix-sum.png -------------------------------------------------------------------------------- /res/maximal_rectangle.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/maximal_rectangle.jpg -------------------------------------------------------------------------------- /res/maximum-subarray-sum.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/maximum-subarray-sum.jpeg -------------------------------------------------------------------------------- /res/maximum_profit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/maximum_profit.png -------------------------------------------------------------------------------- /res/merge_sort.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/merge_sort.png -------------------------------------------------------------------------------- /res/mht.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/mht.jpeg -------------------------------------------------------------------------------- /res/minesweeper-1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/minesweeper-1.jpeg -------------------------------------------------------------------------------- /res/minesweeper-2.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/minesweeper-2.jpeg -------------------------------------------------------------------------------- /res/most_water.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/most_water.jpeg -------------------------------------------------------------------------------- /res/n_ary_tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/n_ary_tree.png -------------------------------------------------------------------------------- /res/permutation_recursion.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/permutation_recursion.gif -------------------------------------------------------------------------------- /res/permutation_tree.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/permutation_tree.jpeg -------------------------------------------------------------------------------- /res/permutation_tree_2.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/permutation_tree_2.jpeg -------------------------------------------------------------------------------- /res/platform.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/platform.png -------------------------------------------------------------------------------- /res/pq-with-heap.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/pq-with-heap.jpg -------------------------------------------------------------------------------- /res/pre-tree.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/pre-tree.jpeg -------------------------------------------------------------------------------- /res/queens.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/queens.jpg -------------------------------------------------------------------------------- /res/rainwatertrap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/rainwatertrap.png -------------------------------------------------------------------------------- /res/rec1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/rec1.jpg -------------------------------------------------------------------------------- /res/rec2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/rec2.jpg -------------------------------------------------------------------------------- /res/rectangle_coordinates.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/rectangle_coordinates.png -------------------------------------------------------------------------------- /res/recursion_tree_frog_jump.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/recursion_tree_frog_jump.jpeg -------------------------------------------------------------------------------- /res/remove_node.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/remove_node.jpeg -------------------------------------------------------------------------------- /res/robot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/robot.png -------------------------------------------------------------------------------- /res/rotting_orange.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/rotting_orange.png -------------------------------------------------------------------------------- /res/server_handle_requests.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/server_handle_requests.png -------------------------------------------------------------------------------- /res/sqrt_root.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/sqrt_root.png -------------------------------------------------------------------------------- /res/sqrt_root1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/sqrt_root1.png -------------------------------------------------------------------------------- /res/sqrt_root2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/sqrt_root2.png -------------------------------------------------------------------------------- /res/sudoku_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/sudoku_1.png -------------------------------------------------------------------------------- /res/sudoku_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/sudoku_2.png -------------------------------------------------------------------------------- /res/toplogical_Sort.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/toplogical_Sort.png -------------------------------------------------------------------------------- /res/topo_sort_dictionary.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/topo_sort_dictionary.png -------------------------------------------------------------------------------- /res/trie_pic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/trie_pic.png -------------------------------------------------------------------------------- /res/unique_bst.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/unique_bst.jpeg -------------------------------------------------------------------------------- /res/unique_paths.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/unique_paths.png -------------------------------------------------------------------------------- /res/vertical_travarsal_tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/vertical_travarsal_tree.png -------------------------------------------------------------------------------- /res/vertical_travarsal_tree_sol_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/vertical_travarsal_tree_sol_1.png -------------------------------------------------------------------------------- /res/vertical_travarsal_tree_sol_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/vertical_travarsal_tree_sol_2.png -------------------------------------------------------------------------------- /res/vertical_travarsal_tree_sol_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/vertical_travarsal_tree_sol_3.png -------------------------------------------------------------------------------- /res/vertical_travarsal_tree_sol_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/vertical_travarsal_tree_sol_4.png -------------------------------------------------------------------------------- /res/word_search.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/res/word_search.jpeg -------------------------------------------------------------------------------- /src/main/java/javaclasses/Array/ArrayNesting.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Array Nesting.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Array; 9 | 10 | import java.util.Arrays; 11 | 12 | public class ArrayNesting { 13 | //Leetcode 565 14 | /*You are given an integer array nums of length n where nums is a permutation of the numbers in the range 15 | [0, n - 1]. 16 | 17 | You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following 18 | rule: 19 | 20 | The first element in s[k] starts with the selection of the element nums[k] of index = k. 21 | The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on. 22 | We stop adding right before a duplicate element occurs in s[k]. 23 | Return the longest length of a set s[k]. 24 | 25 | Example 1: 26 | Input: nums = [5,4,0,3,1,6,2] 27 | Output: 4 28 | Explanation: 29 | nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2. 30 | One of the longest sets s[k]: 31 | s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0} 32 | 33 | Example 2: 34 | Input: nums = [0,1,2] 35 | Output: 1*/ 36 | 37 | //Using DFS 38 | public int arrayNesting(int[] nums) { 39 | if (nums.length == 0) { 40 | return 0; 41 | } 42 | int result = 0; 43 | int[] visited = new int[nums.length]; 44 | Arrays.fill(visited, 0); 45 | for (int i = 0; i < nums.length; i++) { 46 | if (visited[i] == 0) { 47 | int current = i; 48 | int count = 0; 49 | while (visited[current] == 0) { 50 | visited[current] = 1; 51 | count++; 52 | current = nums[current]; 53 | } 54 | result = Math.max(result, count); 55 | } 56 | } 57 | return result; 58 | } 59 | 60 | public static void main(String[] args) { 61 | ArrayNesting nesting = new ArrayNesting(); 62 | int[] nums = {5, 4, 0, 3, 1, 6, 2}; 63 | System.out.println(nesting.arrayNesting(nums)); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Array/FindDuplicate.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Find Duplicate.java 4 | * * Created by Rafsan Ahmad on 1/14/22, 12:03 AM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.Array; 10 | 11 | import java.util.Arrays; 12 | import java.util.HashSet; 13 | import java.util.Set; 14 | 15 | public class FindDuplicate { 16 | //Leetcode 287 17 | /*Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] 18 | inclusive. 19 | 20 | There is only one repeated number in nums, return this repeated number. 21 | 22 | You must solve the problem without modifying the array nums and uses only constant extra space. 23 | 24 | Example 1: 25 | Input: nums = [1,3,4,2,2] 26 | Output: 2 27 | 28 | Example 2: 29 | Input: nums = [3,1,3,4,2] 30 | Output: 3 31 | */ 32 | //Using Sort - O(nlogn) 33 | public int findDuplicate(int[] nums) { 34 | Arrays.sort(nums); 35 | int len = nums.length; 36 | for (int i = 0; i < len - 1; i++) { 37 | if (nums[i] == nums[i + 1]) { 38 | return nums[i]; 39 | } 40 | } 41 | return -1; 42 | } 43 | 44 | //Using Set - O(n) 45 | public int findDuplicateOptimized(int[] nums) { 46 | Set seen = new HashSet<>(); 47 | for (int num : nums) { 48 | if (seen.contains(num)) 49 | return num; 50 | seen.add(num); 51 | } 52 | return -1; 53 | } 54 | 55 | public static void main(String[] args) { 56 | FindDuplicate duplicate = new FindDuplicate(); 57 | int[] nums = {7, 9, 7, 4, 2, 8, 7, 7, 1, 5}; 58 | System.out.println(duplicate.findDuplicate(nums)); 59 | System.out.println(duplicate.findDuplicateOptimized(nums)); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Array/FindMissingNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Find Missing Number.java 4 | * * Created by Rafsan Ahmad on 1/22/22, 9:31 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.Array; 10 | 11 | import java.util.HashSet; 12 | import java.util.Set; 13 | 14 | public class FindMissingNumber { 15 | /*An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], 16 | which means that exactly one element is missing. 17 | 18 | Your goal is to find that missing element. 19 | 20 | Write a function: 21 | 22 | class Solution { public int solution(int[] A); } 23 | 24 | that, given an array A, returns the value of the missing element. 25 | 26 | For example, given array A such that: 27 | 28 | A[0] = 2 29 | A[1] = 3 30 | A[2] = 1 31 | A[3] = 5 32 | the function should return 4, as it is the missing element. 33 | 34 | Write an efficient algorithm for the following assumptions: 35 | 36 | N is an integer within the range [0..100,000]; 37 | the elements of A are all distinct; 38 | each element of array A is an integer within the range [1..(N + 1)].*/ 39 | 40 | public int solution(int[] A) { 41 | int max = A.length + 1; 42 | 43 | Set incompleteSet = new HashSet<>(); 44 | for (int i = 0; i < A.length; i++) { 45 | incompleteSet.add(A[i]); 46 | } 47 | 48 | for (int i = 1; i < max + 1; i++) { 49 | if (!incompleteSet.contains(i)) { 50 | return (i); 51 | } 52 | } 53 | return -1; 54 | } 55 | 56 | public static void main(String[] args) { 57 | FindMissingNumber number = new FindMissingNumber(); 58 | int[] nums = {2, 3, 1, 5}; 59 | System.out.println(number.solution(nums)); 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Array/JumpGame_II.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * JumpGame II.java 4 | * * Created by Rafsan Ahmad on 5/20/22, 11:19 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.Array; 10 | 11 | public class JumpGame_II { 12 | //Leetcode 45 13 | /*Given an array of non-negative integers nums, you are initially positioned at the first index of the array. 14 | 15 | Each element in the array represents your maximum jump length at that position. 16 | 17 | Your goal is to reach the last index in the minimum number of jumps. 18 | 19 | You can assume that you can always reach the last index. 20 | 21 | 22 | 23 | Example 1: 24 | Input: nums = [2,3,1,1,4] 25 | Output: 2 26 | Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the 27 | last index. 28 | 29 | Example 2: 30 | Input: nums = [2,3,0,1,4] 31 | Output: 2 32 | */ 33 | 34 | public int jump(int[] nums) { 35 | int current = 0; 36 | int next = 0; 37 | int result = 0; 38 | 39 | for (int i = 0; i < nums.length; i++) { 40 | if (i > current) { 41 | current = next; 42 | result++; 43 | } 44 | next = Math.max(next, i + nums[i]); 45 | } 46 | 47 | return result; 48 | } 49 | 50 | public static void main(String[] args) { 51 | JumpGame_II game_ii = new JumpGame_II(); 52 | int[] ar = {2, 3, 0, 1, 4}; 53 | int[] ar2 = {2, 3, 1, 3, 1, 1}; 54 | System.out.println(game_ii.jump(ar)); 55 | System.out.println(game_ii.jump(ar2)); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Array/LargestNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Largest Number.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Array; 9 | 10 | import java.util.Arrays; 11 | import java.util.Comparator; 12 | 13 | //Leetcode = 179 14 | /* 15 | Given a list of non-negative integers nums, arrange them such that they form the largest number. 16 | 17 | Note: The result may be very large, so you need to return a string instead of an integer. 18 | 19 | Example 1: 20 | Input: nums = [10,2] 21 | Output: "210" 22 | 23 | Example 2: 24 | Input: nums = [3,30,34,5,9] 25 | Output: "9534330" 26 | 27 | Example 3: 28 | Input: nums = [1] 29 | Output: "1" 30 | 31 | Example 4: 32 | Input: nums = [10] 33 | Output: "10" 34 | * */ 35 | public class LargestNumber { 36 | 37 | public String largestNumber(int[] nums) { 38 | if (nums == null || nums.length == 0) { 39 | return ""; 40 | } 41 | 42 | int len = nums.length; 43 | String[] str = new String[len]; 44 | StringBuilder builder = new StringBuilder(); 45 | 46 | for (int i = 0; i < len; i++) { 47 | str[i] = String.valueOf(nums[i]); 48 | } 49 | 50 | Comparator comparator = (o1, o2) -> { 51 | String s1 = o1 + o2; 52 | String s2 = o2 + o1; 53 | return s2.compareTo(s1); 54 | }; 55 | 56 | Arrays.sort(str, comparator); 57 | if (str[0].charAt(0) == '0') 58 | return "0"; 59 | 60 | for (int i = 0; i < len; i++) { 61 | builder.append(str[i]); 62 | } 63 | 64 | return builder.toString(); 65 | } 66 | 67 | public static void main(String[] args) { 68 | int[] arr = {3, 30, 34, 5, 9}; 69 | LargestNumber ln = new LargestNumber(); 70 | String res = ln.largestNumber(arr); 71 | System.out.println(res); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Array/MaxDifference.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Max Difference.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Array; 9 | 10 | /*Given an array of integers, find Maximum difference between two elements such that larger number appears after 11 | the smaller number. 12 | In this tutorial, I am going to discuss multiple approaches and their java code to find maximum difference between 13 | two elements. 14 | 15 | For example : 16 | 17 | Example 1: 18 | 19 | arr = {2, 5, 15, 6, 4} 20 | Output: 13 21 | 22 | The difference between 15 and 2 is 13. Element 15 is greater than 2 and it satisfies our condition that larger number 23 | appears after the smaller number. 24 | 25 | Example 2: 26 | 27 | arr = {7, 9, 5, 6, 13, 2}; 28 | Output : 8 29 | 30 | The difference between 13 and 5 is 8 (13-5).*/ 31 | 32 | /*In this approach, instead of taking difference of the picked element with every other element, we can take the 33 | difference with the minimum element found so far. 34 | So we need to keep track of two things: 35 | 36 | 1) Maximum difference found so far. 37 | 2) Minimum number visited so far.*/ 38 | 39 | /* 40 | Find Maximum Difference between Two Elements of an Array in 41 | O(n) Time Complexity. 42 | */ 43 | public class MaxDifference { 44 | 45 | public static int findMaxDiff(int[] arr) { 46 | 47 | int maxDiff = arr[1] - arr[0]; 48 | int minEle = arr[0]; 49 | 50 | for (int i = 1; i < arr.length; i++) { 51 | if ((arr[i] - minEle) > maxDiff) { 52 | maxDiff = arr[i] - minEle; 53 | } 54 | 55 | if (arr[i] < minEle) { 56 | minEle = arr[i]; 57 | } 58 | } 59 | 60 | return maxDiff; 61 | } 62 | 63 | public static void main(String[] args) { 64 | 65 | int arr[] = {7, 9, 5, 6, 13, 2, 15}; 66 | int result = findMaxDiff(arr); 67 | 68 | System.out.println(result); 69 | } 70 | } 71 | 72 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Array/MaximumContiguousSubarray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Maximum Contiguous Subarray.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Array; 9 | 10 | public class MaximumContiguousSubarray { 11 | //Leetcode 53 12 | /* 13 | Given an integer array nums, find the contiguous subarray (containing at least one number) 14 | which has the largest sum and return its sum. 15 | 16 | Example 1: 17 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 18 | Output: 6 19 | Explanation: [4,-1,2,1] has the largest sum = 6. 20 | 21 | Example 2: 22 | Input: nums = [1] 23 | Output: 1 24 | 25 | Example 3: 26 | Input: nums = [5,4,-1,7,8] 27 | Output: 23 28 | * */ 29 | 30 | public int maxSubArray(int[] nums) { 31 | int sum = nums[0]; 32 | int result = 0; 33 | 34 | for (int i = 1; i < nums.length; i++) { 35 | sum = Math.max(nums[i], sum + nums[i]); 36 | result = Math.max(sum, result); 37 | } 38 | return result; 39 | } 40 | 41 | public static void main(String[] args) { 42 | MaximumContiguousSubarray array = new MaximumContiguousSubarray(); 43 | int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; 44 | System.out.println(array.maxSubArray(arr)); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Array/MergeKSortedArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Merge K Sorted Array.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Array; 9 | 10 | import java.util.Arrays; 11 | import java.util.PriorityQueue; 12 | 13 | public class MergeKSortedArray { 14 | //Same as Leetcode 23 15 | //This problem can be solved by using a Heap 16 | //Time complexity 0(nklog(k)) 17 | //k=Number of arrays 18 | 19 | static class ArrayContainer implements Comparable { 20 | 21 | int[] arr; 22 | int index; 23 | 24 | public ArrayContainer(int[] arr, int index) { 25 | this.arr = arr; 26 | this.index = index; 27 | } 28 | 29 | @Override 30 | public int compareTo(ArrayContainer container) { 31 | return this.arr[this.index] - container.arr[container.index]; 32 | } 33 | } 34 | 35 | public static int[] mergeKSortedArray(int[][] arr) { 36 | //PriorityQueue is heap in Java 37 | PriorityQueue queue = new PriorityQueue<>(); 38 | int total = 0; 39 | 40 | //Add arrays to Heap 41 | for (int i = 0; i < arr.length; i++) { 42 | queue.add(new ArrayContainer(arr[i], 0)); 43 | total = total + arr[i].length; 44 | } 45 | int m = 0; 46 | int[] result = new int[total]; 47 | 48 | //while heap is not empty 49 | while (!queue.isEmpty()) { 50 | ArrayContainer ac = queue.poll(); 51 | result[m++] = ac.arr[ac.index]; 52 | if (ac.index < ac.arr.length - 1) { 53 | queue.add(new ArrayContainer(ac.arr, ac.index + 1)); 54 | } 55 | } 56 | return result; 57 | } 58 | 59 | public static void main(String[] args) { 60 | int[] arr1 = {1, 3, 5, 7}; 61 | int[] arr2 = {2, 4, 6, 8}; 62 | int[] arr3 = {0, 9, 10, 11}; 63 | 64 | int[] result = mergeKSortedArray(new int[][]{arr1, arr2, arr3}); 65 | System.out.println(Arrays.toString(result)); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Array/SecondSmallest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Second Smallest.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Array; 9 | 10 | /*Given an input array of unsorted integers. Write a code to find second smallest number in an array. 11 | 12 | For example : 13 | 14 | arr = {-1, 7, 1, 34, 18} 15 | 16 | The second smallest number in this array is 1.*/ 17 | 18 | /*Let’s discuss how we can solve this problem in a single traversal using two variables 19 | (smallest and secondSmallest). 20 | 21 | Here are the following steps – 22 | 23 | i) Declare two variables smallest and secondSmallest. Initialize them with Integer.MAX_VALUE. 24 | 25 | ii) Traverse an array and do the following checks – 26 | 27 | a) If current element is smaller than the smallest. Then, update the value of smallest variable. 28 | 29 | b) If current element is greater than smallest and less than secondSmallest than update the value of secondSmallest. 30 | 31 | The time complexity of this approach is O(n). 32 | 33 | */ 34 | 35 | //Find second lowest number in an array 36 | public class SecondSmallest { 37 | 38 | public static int getSecondSmallest(int arr[]) { 39 | 40 | //Integer.MAX_VALUE is 2147483647 41 | int smallest = Integer.MAX_VALUE; 42 | int secondSmallest = Integer.MAX_VALUE; 43 | 44 | //Traverse an array 45 | for (int i = 0; i < arr.length; i++) { 46 | 47 | if (arr[i] < smallest) { 48 | secondSmallest = smallest; 49 | smallest = arr[i]; 50 | } 51 | 52 | if (arr[i] > smallest && arr[i] < secondSmallest) { 53 | secondSmallest = arr[i]; 54 | } 55 | } 56 | 57 | return secondSmallest; 58 | } 59 | 60 | public static void main(String[] args) { 61 | 62 | int[] arr = {-1, 70, 10, 34, 18, 78}; 63 | 64 | //Method Call 65 | int result = getSecondSmallest(arr); 66 | 67 | System.out.println(" Second smallest number " + result); 68 | } 69 | 70 | } 71 | 72 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Array/SubArraySum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Sub Array Sum.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Array; 9 | 10 | import java.util.HashMap; 11 | 12 | public class SubArraySum { 13 | //Leetcode 560 14 | /*Given an array of integers nums and an integer k, return the total number 15 | of continuous subarrays whose sum equals to k. 16 | 17 | Example 1: 18 | Input: nums = [1,1,1], k = 2 19 | Output: 2 20 | 21 | Example 2: 22 | Input: nums = [1,2,3], k = 3 23 | Output: 2*/ 24 | 25 | public int subarraySum(int[] nums, int k) { 26 | int count = 0; 27 | int sum = 0; 28 | //Key - Sum, Value - Number of occurances of sum 29 | HashMap map = new HashMap<>(); 30 | map.put(0, 1); 31 | 32 | for (int i = 0; i < nums.length; i++) { 33 | sum += nums[i]; 34 | if (map.containsKey(sum - k)) 35 | count += map.get(sum - k); 36 | int occurances = map.getOrDefault(sum, 0) + 1; 37 | map.put(sum, occurances); 38 | } 39 | return count; 40 | } 41 | 42 | public static void main(String[] args) { 43 | int[] arr = {1, 2, 3}; 44 | SubArraySum sum = new SubArraySum(); 45 | System.out.println(sum.subarraySum(arr, 3)); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Array/WaveArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Wave Array.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Array; 9 | 10 | import java.util.Arrays; 11 | 12 | public class WaveArray { 13 | //https://www.interviewbit.com/problems/wave-array/ 14 | /*Problem Description 15 | Given an array of integers A, sort the array into a wave like array and return it, In other words, 16 | arrange the elements into a sequence such that 17 | a1 >= a2 <= a3 >= a4 <= a5..... 18 | NOTE : If there are multiple answers possible, return the one that's lexicographically smallest. 19 | 20 | Input Format 21 | First argument is an integer array A. 22 | 23 | Output Format 24 | Return an array arranged in the sequence as described. 25 | 26 | Example Input 27 | Input 1: 28 | A = [1, 2, 3, 4] 29 | 30 | Input 2: 31 | A = [1, 2] 32 | 33 | Example Output 34 | Output 1: 35 | [2, 1, 4, 3] 36 | 37 | Output 2: 38 | [2, 1] 39 | 40 | Example Explanation 41 | Explanation 1: 42 | One possible answer : [2, 1, 4, 3] 43 | Another possible answer : [4, 1, 3, 2] 44 | First answer is lexicographically smallest. So, return [2, 1, 4, 3]. 45 | 46 | Explanation 2: 47 | Only possible answer is [2, 1].*/ 48 | 49 | public int[] wave(int[] A) { 50 | int[] result = new int[A.length]; 51 | int len = A.length; 52 | Arrays.sort(A); 53 | for (int i = 0; i < len - 1; i = i + 2) { 54 | int temp = A[i + 1]; 55 | result[i + 1] = A[i]; 56 | result[i] = temp; 57 | } 58 | if (len % 2 != 0) result[len - 1] = A[len - 1]; 59 | return result; 60 | } 61 | 62 | public static void main(String[] args) { 63 | int[] ar = {1, 2, 3, 4, 5}; 64 | System.out.println(Arrays.toString(new WaveArray().wave(ar))); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/ArrayList/MergeTwoSortedList_II.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Merge Two Sorted List_II.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.ArrayList; 9 | 10 | import java.util.ArrayList; 11 | 12 | public class MergeTwoSortedList_II { 13 | //https://www.interviewbit.com/problems/merge-two-sorted-lists-ii/ 14 | /*Given two sorted integer arrays A and B, merge B into A as one sorted array. 15 | 16 | Note: You have to modify the array A to contain the merge of A and B. Do not output anything in your code. 17 | 18 | TIP: C users, please malloc the result into a new array and return the result. 19 | 20 | If the number of elements initialized in A and B are m and n respectively, 21 | the resulting size of array A after your code is executed should be m + n 22 | 23 | Example : 24 | 25 | Input : 26 | A : [1 5 8] 27 | B : [6 9] 28 | 29 | Modified A : [1 5 6 8 9]*/ 30 | 31 | //Approach - Using Two Pointer 32 | //Time complexity = O(m+n) 33 | //Space complexity = O(1) 34 | public void merge(ArrayList A, ArrayList B) { 35 | int i = 0, j = 0; 36 | while (i < A.size() && j < B.size()) { 37 | if (A.get(i) > B.get(j)) { 38 | A.add(i, B.get(j)); 39 | j++; 40 | } 41 | i++; 42 | } 43 | while (j < B.size()) { 44 | A.add(B.get(j)); 45 | j++; 46 | } 47 | } 48 | 49 | public static void main(String[] args) { 50 | MergeTwoSortedList_II list = new MergeTwoSortedList_II(); 51 | ArrayList A = new ArrayList<>(); 52 | ArrayList B = new ArrayList<>(); 53 | A.add(-4); 54 | A.add(3); 55 | A.add(90); 56 | B.add(0); 57 | B.add(-2); 58 | B.add(-2); 59 | B.add(9); 60 | //A = [-4,3,90] 61 | //B = [0,-2,-2,9] 62 | //Merged = [-4, 0, -2, -2, 3, 9, 90] 63 | list.merge(A, B); 64 | System.out.println("Merged List: " + A); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Backtracking/PalindromePartitioning.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Palindrome Partitioning.java 4 | * * Created by Rafsan Ahmad on 1/28/23, 6:02 PM 5 | * * Copyright (c) 2023 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.Backtracking; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | public class PalindromePartitioning { 15 | /*Given a string s, partition s such that every 16 | substring 17 | of the partition is a 18 | palindrome 19 | . Return all possible palindrome partitioning of s. 20 | 21 | Example 1: 22 | 23 | Input: s = "aab" 24 | Output: [["a","a","b"],["aa","b"]] 25 | Example 2: 26 | 27 | Input: s = "a" 28 | Output: [["a"]]*/ 29 | 30 | public List> partition(String s) { 31 | List> result = new ArrayList<>(); 32 | 33 | helper(result, new ArrayList<>(), s, 0); 34 | 35 | return result; 36 | } 37 | 38 | 39 | public void helper(List> list, List tempList, String s, int start) { 40 | 41 | if (start == s.length()) { 42 | list.add(new ArrayList<>(tempList)); 43 | } 44 | 45 | for (int i = start; i < s.length(); i++) { 46 | if (isPalindrome(s, start, i)) { 47 | tempList.add(s.substring(start, i + 1)); 48 | helper(list, tempList, s, i + 1); 49 | tempList.remove(tempList.size() - 1); 50 | } 51 | } 52 | } 53 | 54 | public boolean isPalindrome(String s, int left, int right) { 55 | 56 | while (left < right) { 57 | if (s.charAt(left) != s.charAt(right)) return false; 58 | left++; 59 | right--; 60 | } 61 | 62 | return true; 63 | } 64 | 65 | public static void main(String[] args) { 66 | PalindromePartitioning partitioning = new PalindromePartitioning(); 67 | System.out.println(partitioning.partition("aab")); 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/BinarySearch/FindPeakElement.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Find Peak Element.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:50 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.BinarySearch; 9 | 10 | public class FindPeakElement { 11 | //Leetcode 162 12 | /*A peak element is an element that is strictly greater than its neighbors. 13 | 14 | Given an integer array nums, find a peak element, and return its index. 15 | If the array contains multiple peaks, return the index to any of the peaks. 16 | You may imagine that nums[-1] = nums[n] = -∞. 17 | You must write an algorithm that runs in O(log n) time. 18 | 19 | Example 1: 20 | Input: nums = [1,2,3,1] 21 | Output: 2 22 | Explanation: 3 is a peak element and your function should return the index number 2. 23 | 24 | Example 2: 25 | Input: nums = [1,2,1,3,5,6,4] 26 | Output: 5 27 | Explanation: Your function can return either index number 1 where the peak element is 2, or index number 28 | 5 where the peak element is 6.*/ 29 | 30 | public int findPeakElement(int[] nums) { 31 | int l = 0; 32 | int r = nums.length - 1; 33 | while (l < r) { 34 | int mid = (l + r) / 2; 35 | if (nums[mid] > nums[mid + 1]) { 36 | r = mid; 37 | } else { 38 | l = mid + 1; 39 | } 40 | } 41 | return l; 42 | } 43 | 44 | public static void main(String[] args) { 45 | int[] ar = {1, 2, 1, 3, 5, 6, 4}; 46 | System.out.println(new FindPeakElement().findPeakElement(ar)); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/BitManipulation/NextPowerOf2.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Next Power Of 2.java 4 | * * Created by Rafsan Ahmad on 10/25/23, 2:06 AM 5 | * * Copyright (c) 2023 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package javaclasses.BitManipulation; 11 | 12 | public class NextPowerOf2 { 13 | 14 | public int nextPowerOf2(int num) { 15 | if (num == 0) { 16 | return 1; 17 | } 18 | if (num > 0 && (num & (num - 1)) == 0) { 19 | return num; 20 | } 21 | while ((num & (num - 1)) > 0) { 22 | num = num & (num - 1); 23 | } 24 | return num << 1; 25 | } 26 | 27 | public static void main(String args[]) { 28 | NextPowerOf2 np = new NextPowerOf2(); 29 | System.out.println(np.nextPowerOf2(4)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/BitManipulation/SingleNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Single Number.java 4 | * * Created by Rafsan Ahmad on 1/4/22, 2:51 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.BitManipulation; 10 | 11 | public class SingleNumber { 12 | //Leetcode 136 13 | /*Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. 14 | 15 | You must implement a solution with a linear runtime complexity and use only constant extra space. 16 | 17 | Example 1: 18 | Input: nums = [2,2,1] 19 | Output: 1 20 | 21 | Example 2: 22 | Input: nums = [4,1,2,1,2] 23 | Output: 4 24 | 25 | Example 3: 26 | Input: nums = [1] 27 | Output: 1 28 | */ 29 | 30 | /*Here we are finding the XOR (Exclusive OR) of all the elements present in the given array. 31 | Since we have only 1 variable 'ans', space complexity will be O(1) and time complexity is also linear, 32 | since we are only iterating over the array and not applying any extra algorithm. 33 | Why XOR ? 34 | Since all elements are occurring twice except one element, the XOR of these element will be 0 and as we know 0 35 | xor N = N, we get our desired output.*/ 36 | public int singleNumber(int[] nums) { 37 | int ans = nums[0]; 38 | for (int i = 1; i < nums.length; i++) { 39 | ans ^= nums[i]; 40 | } 41 | return ans; 42 | } 43 | 44 | public static void main(String[] args) { 45 | SingleNumber number = new SingleNumber(); 46 | int[] nums = {4, 1, 2, 1, 2}; 47 | System.out.println(number.singleNumber(nums)); 48 | 49 | System.out.println(3 ^ 3); //0 50 | System.out.println(3 ^ 3 ^ 4); //4 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/BitManipulation/SumOfTwoIntegers.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Sum Of Two Integers.java 4 | * * Created by Rafsan Ahmad on 1/3/22, 12:24 AM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.BitManipulation; 10 | 11 | public class SumOfTwoIntegers { 12 | //Leetcode 371 13 | /*Given two integers a and b, return the sum of the two integers without using the operators + and -. 14 | 15 | Example 1: 16 | Input: a = 1, b = 2 17 | Output: 3 18 | 19 | Example 2: 20 | Input: a = 2, b = 3 21 | Output: 5 22 | 23 | Constraints: 24 | -1000 <= a, b <= 1000*/ 25 | public int getSum(int a, int b) { 26 | // Iterate till there is no carry 27 | while (b != 0) { 28 | // carry now contains common 29 | // set bits of a and b 30 | int carry = a & b; 31 | 32 | // Sum of bits of a and 33 | // b where at least one 34 | // of the bits is not set 35 | a = a ^ b; 36 | 37 | // Carry is shifted by 38 | // one so that adding it 39 | // to a gives the required sum 40 | b = carry << 1; 41 | } 42 | return a; 43 | } 44 | 45 | public static void main(String[] args) { 46 | SumOfTwoIntegers integers = new SumOfTwoIntegers(); 47 | System.out.println(integers.getSum(100, 10)); 48 | System.out.println(integers.getSum(-100, 10)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/BitManipulation/XorQueries.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Xor Queries.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:50 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.BitManipulation; 9 | 10 | import java.util.Arrays; 11 | 12 | public class XorQueries { 13 | //Leetcode 1310 14 | /*Given the array arr of positive integers and the array queries where queries[i] = [Li, Ri], 15 | for each query i compute the XOR of elements from Li to Ri (that is, arr[Li] xor arr[Li+1] xor ... xor arr[Ri] ). 16 | Return an array containing the result for the given queries. 17 | 18 | Example 1: 19 | Input: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]] 20 | Output: [2,7,14,8] 21 | Explanation: 22 | The binary representation of the elements in the array are: 23 | 1 = 0001 24 | 3 = 0011 25 | 4 = 0100 26 | 8 = 1000 27 | The XOR values for queries are: 28 | [0,1] = 1 xor 3 = 2 29 | [1,2] = 3 xor 4 = 7 30 | [0,3] = 1 xor 3 xor 4 xor 8 = 14 31 | [3,3] = 8 32 | 33 | Example 2: 34 | Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]] 35 | Output: [8,0,4,4]*/ 36 | 37 | public int[] xorQueries(int[] arr, int[][] queries) { 38 | int[] result = new int[queries.length]; 39 | int count = 0; 40 | for (int i = 0; i < queries.length; i++) { 41 | int num1 = queries[i][0]; 42 | int num2 = queries[i][1]; 43 | int xor = 0; 44 | for (int j = num1; j <= num2; j++) { 45 | xor = xor ^ arr[j]; 46 | } 47 | result[count] = xor; 48 | ++count; 49 | } 50 | return result; 51 | } 52 | 53 | public static void main(String[] args) { 54 | XorQueries xorQueries = new XorQueries(); 55 | int[] arr = {1, 3, 4, 8}; 56 | int[][] queries = {{0, 1}, {1, 2}, {0, 3}, {3, 3}}; 57 | System.out.println(Arrays.toString(xorQueries.xorQueries(arr, queries))); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Codility/CropMessage.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * CropMessage.java 4 | * * Created by Rafsan Ahmad on 1/24/22, 1:51 AM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.Codility; 10 | 11 | public class CropMessage { 12 | 13 | //K Characters limit on a Forum Message 14 | public String cropMessage(String message, int K) { 15 | StringBuilder builder = new StringBuilder(""); 16 | int currentLength = 0; 17 | String[] splitted = message.split("\\s+"); 18 | for (String str : splitted) { 19 | currentLength += str.length() + 1; //for space 20 | if (currentLength <= K || currentLength - 1 == K) { 21 | builder.append(str).append(" "); 22 | } 23 | } 24 | String result = builder.toString(); 25 | result = result.replaceAll("\\s+$", ""); //remove ending space 26 | return result; 27 | } 28 | 29 | public static void main(String[] args) { 30 | CropMessage c = new CropMessage(); 31 | String message = "Codility we test coders"; 32 | System.out.println(c.cropMessage(message, 14)); 33 | String message2 = "The quick brown fox jumps over the lazy dog"; 34 | System.out.println(c.cropMessage(message2, 39)); 35 | String message3 = "APP B CD E"; 36 | System.out.println(c.cropMessage(message3, 6)); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Codility/MinimumNumberOfFilters.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Minimum Number Of Filters.java 4 | * * Created by Rafsan Ahmad on 1/24/22, 1:53 AM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.Codility; 10 | 11 | import java.util.Arrays; 12 | 13 | public class MinimumNumberOfFilters { 14 | 15 | //Minimum filters required to reduce polution by half which is produced in Array A 16 | public int minimumNumberOfFilters(int[] A) { 17 | int len = A.length; 18 | int minFilters = 0; 19 | int totalPollution = 0; 20 | for (int i = 0; i < len; i++) { 21 | totalPollution += A[i]; 22 | } 23 | double reducedPollution = totalPollution; 24 | 25 | double[] polutions = Arrays.stream(A).asDoubleStream().toArray(); 26 | while (reducedPollution > totalPollution / 2.0) { 27 | int maxIndex = maxIndex(polutions); 28 | double p = polutions[maxIndex] / 2; 29 | polutions[maxIndex] = p; 30 | reducedPollution = getSum(polutions); 31 | minFilters++; 32 | } 33 | 34 | return minFilters; 35 | } 36 | 37 | public int maxIndex(double[] array) { 38 | int maxAt = 0; 39 | for (int i = 0; i < array.length; i++) { 40 | maxAt = array[i] > array[maxAt] ? i : maxAt; 41 | } 42 | return maxAt; 43 | } 44 | 45 | public double getSum(double[] arr) { 46 | double total = 0; 47 | for (int i = 0; i < arr.length; i++) { 48 | total += arr[i]; 49 | } 50 | return total; 51 | } 52 | 53 | public static void main(String[] args) { 54 | MinimumNumberOfFilters filters = new MinimumNumberOfFilters(); 55 | int[] nums = {5, 19, 8, 1}; 56 | int[] nums2 = {1, 0, 2}; 57 | int[] nums3 = {1, 1}; 58 | System.out.println(filters.minimumNumberOfFilters(nums)); 59 | System.out.println(filters.minimumNumberOfFilters(nums2)); 60 | System.out.println(filters.minimumNumberOfFilters(nums3)); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/DataStructure/DequeExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * DequeExample.java 4 | * * Created by Rafsan Ahmad on 2/2/22, 12:32 AM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.DataStructure; 10 | 11 | import java.util.ArrayDeque; 12 | import java.util.Deque; 13 | 14 | public class DequeExample { 15 | 16 | public static void main(String[] args) { 17 | Deque dequeue = new ArrayDeque<>(); 18 | dequeue.offerFirst(20); // -> 20 19 | dequeue.offerFirst(21); // -> 21 20 20 | dequeue.offerFirst(22); // -> 22 21 20 21 | dequeue.offerLast(23); // -> 22 21 20 23 22 | dequeue.offerLast(24); // -> 22 21 20 23 24 23 | dequeue.offerLast(25); // -> 22 21 20 23 24 25 24 | dequeue.offerFirst(26); // -> 26 22 21 20 23 24 25 25 | dequeue.offerFirst(27); // -> 27 26 22 21 20 23 24 25 26 | System.out.println("dequeue = " + dequeue); 27 | 28 | System.out.println(); 29 | System.out.println("dequeue.offerLast(28) = " + dequeue.offerLast(28)); 30 | System.out.println("dequeue.offerFirst(29) = " + dequeue.offerFirst(29)); 31 | System.out.println("dequeue = " + dequeue); 32 | 33 | while (!dequeue.isEmpty()) { 34 | System.out.println(); 35 | System.out.println("dequeue.pollFirst() = " + dequeue.pollFirst()); 36 | System.out.println("dequeue.pollLast() = " + dequeue.pollLast()); 37 | System.out.println("dequeue = " + dequeue); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/DataStructure/LruCache/Node.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.DataStructure.LruCache; 9 | 10 | public class Node { 11 | int key; 12 | int value; 13 | public Node prev; 14 | public Node next; 15 | 16 | public Node(int key, int value) { 17 | this.key = key; 18 | this.value = value; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/DynamicProgramming/MaximumBudget.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Maximum Budget.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:50 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.DynamicProgramming; 9 | 10 | public class MaximumBudget { 11 | /*Given 'budget' and prices for each category of ads (mxn int array), pick one price from each 12 | category and maximize the budget utilization 13 | 14 | budget = 30 15 | adPrices= 16 | [3,1,5,7,10] 17 | [7,9,2,20,10] 18 | [3,1,9,45,51] 19 | 20 | ans = 30 (take 7 from first, 20 from second and 3 from third category)*/ 21 | 22 | public int closest(int[][] array, int target) { 23 | int m = array.length; 24 | int n = array[0].length; 25 | boolean[][] dp = new boolean[m][target + 1]; 26 | for (int num : array[0]) { 27 | if (num <= target) { 28 | dp[0][num] = true; 29 | } 30 | } 31 | for (int i = 1; i < m; i++) { 32 | for (int num : array[i]) { 33 | for (int j = 0; j <= target; j++) { 34 | if (dp[i - 1][j] && num + j <= target) { 35 | dp[i][j + num] = true; 36 | } 37 | } 38 | } 39 | } 40 | for (int i = target; i >= 0; i--) { 41 | if (dp[m - 1][i]) { 42 | return i; 43 | } 44 | } 45 | return 0; 46 | } 47 | 48 | public static void main(String[] args) { 49 | MaximumBudget budget = new MaximumBudget(); 50 | int[][] arr = { 51 | {3, 1, 5, 7, 10}, 52 | {7, 9, 2, 20, 10}, 53 | {3, 1, 9, 45, 51} 54 | }; 55 | System.out.println(budget.closest(arr, 30)); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/DynamicProgramming/MaximumLengthOfRepeatedSubarray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Maximum Length Of Repeated Subarray.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:50 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.DynamicProgramming; 9 | 10 | public class MaximumLengthOfRepeatedSubarray { 11 | //Leetcode 718 12 | /*Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays. 13 | 14 | Example 1: 15 | Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7] 16 | Output: 3 17 | Explanation: The repeated subarray with maximum length is [3,2,1]. 18 | 19 | Example 2: 20 | Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0] 21 | Output: 5*/ 22 | 23 | public int findLength(int[] nums1, int[] nums2) { 24 | int max = 0; 25 | int[][] dp = new int[nums1.length + 1][nums2.length + 1]; 26 | for (int i = 1; i <= nums1.length; i++) { 27 | for (int j = 1; j <= nums2.length; j++) { 28 | if (nums1[i - 1] == nums2[j - 1]) { 29 | dp[i][j] = dp[i - 1][j - 1] + 1; 30 | max = Math.max(dp[i][j], max); 31 | } 32 | } 33 | } 34 | return max; 35 | } 36 | 37 | public static void main(String[] args) { 38 | MaximumLengthOfRepeatedSubarray subarray = new MaximumLengthOfRepeatedSubarray(); 39 | int[] ar1 = {1, 2, 3, 2, 1}; 40 | int[] ar2 = {3, 2, 1, 4, 7}; 41 | System.out.println(subarray.findLength(ar1, ar2)); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/GreedyAlgorithm/ContainerWithMostWater.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Container With Most Water.java 4 | * * Created by Rafsan Ahmad on 12/10/21, 3:47 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.GreedyAlgorithm; 10 | 11 | public class ContainerWithMostWater { 12 | //Leetcode 11 13 | //res/most_water.jpeg 14 | /*Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). 15 | n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). 16 | Find two lines, which, together with the x-axis forms a container, 17 | such that the container contains the most water. 18 | Notice that you may not slant the container. 19 | 20 | Example 1: 21 | Input: height = [1,8,6,2,5,4,8,3,7] 22 | Output: 49 23 | Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, 24 | the max area of water (blue section) the container can contain is 49. 25 | 26 | Example 2: 27 | Input: height = [1,1] 28 | Output: 1 29 | 30 | Example 3: 31 | Input: height = [4,3,2,1,4] 32 | Output: 16 33 | 34 | Example 4: 35 | Input: height = [1,2,1] 36 | Output: 2 37 | */ 38 | 39 | public int maxArea(int[] height) { 40 | int result = Integer.MIN_VALUE; 41 | if (height == null || height.length < 2) { 42 | return 0; 43 | } 44 | int left = 0; 45 | int right = height.length - 1; 46 | while (left < right) { 47 | int w = right - left; 48 | int h = Math.min(height[left], height[right]); 49 | result = Math.max(result, w * h); 50 | if (height[left] < height[right]) { 51 | left++; 52 | } else { 53 | right--; 54 | } 55 | } 56 | return result; 57 | } 58 | 59 | public static void main(String[] args) { 60 | ContainerWithMostWater water = new ContainerWithMostWater(); 61 | int[] arr = {1, 8, 6, 2, 5, 4, 8, 3, 7}; 62 | System.out.println(water.maxArea(arr)); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/GreedyAlgorithm/MaximumMatrixSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Maximum Matrix Sum.java 4 | * * Created by Rafsan Ahmad on 2/18/22, 12:27 AM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.GreedyAlgorithm; 10 | 11 | public class MaximumMatrixSum { 12 | //Leetcode 1975 13 | /*You are given an n x n integer matrix. You can do the following operation any number of times: 14 | 15 | Choose any two adjacent elements of matrix and multiply each of them by -1. 16 | Two elements are considered adjacent if and only if they share a border. 17 | 18 | Your goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using 19 | the operation mentioned above. 20 | 21 | 22 | 23 | Example 1: 24 | //res/matrix-sum.png 25 | Input: matrix = [[1,-1],[-1,1]] 26 | Output: 4 27 | Explanation: We can follow the following steps to reach sum equals 4: 28 | - Multiply the 2 elements in the first row by -1. 29 | - Multiply the 2 elements in the first column by -1. 30 | 31 | 32 | Example 2: 33 | Input: matrix = [[1,2,3],[-1,-2,-3],[1,2,3]] 34 | Output: 16 35 | Explanation: We can follow the following step to reach sum equals 16: 36 | - Multiply the 2 last elements in the second row by -1.*/ 37 | 38 | public long maxMatrixSum(int[][] matrix) { 39 | int negativeCount = 0; 40 | long result = 0; 41 | int min = Integer.MAX_VALUE; 42 | 43 | for (int i = 0; i < matrix.length; i++) { 44 | for (int j = 0; j < matrix[0].length; j++) { 45 | if (matrix[i][j] < 0) 46 | negativeCount++; 47 | 48 | min = Math.min(min, Math.abs(matrix[i][j])); 49 | result = result + Math.abs(matrix[i][j]); 50 | } 51 | } 52 | 53 | if (negativeCount % 2 != 0) { 54 | result = result - (2 * min); 55 | } 56 | 57 | return result; 58 | } 59 | 60 | public static void main(String[] args) { 61 | MaximumMatrixSum sum = new MaximumMatrixSum(); 62 | int[][] matrix = {{1, 2, 3}, {-1, -2, -3}, {1, 2, 3}}; 63 | System.out.println(sum.maxMatrixSum(matrix)); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/HeapPriorityQueue/MergeKSortedArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Merge K Sorted Array.java 3 | * * Created by Rafsan Ahmad on 11/24/21, 4:41 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.HeapPriorityQueue; 9 | 10 | import java.util.Arrays; 11 | import java.util.PriorityQueue; 12 | 13 | public class MergeKSortedArray { 14 | //Same as Leetcode 23 15 | //This problem can be solved by using a Heap 16 | //Time complexity 0(nlog(k)) 17 | 18 | public static class ArrayContainer implements Comparable { 19 | 20 | int[] arr; 21 | int index; 22 | 23 | public ArrayContainer(int[] arr, int index) { 24 | this.arr = arr; 25 | this.index = index; 26 | } 27 | 28 | @Override 29 | public int compareTo(ArrayContainer container) { 30 | return this.arr[this.index] - container.arr[container.index]; 31 | } 32 | } 33 | 34 | public static int[] mergeKSortedArray(int[][] arr) { 35 | //PriorityQueue is heap in Java 36 | PriorityQueue queue = new PriorityQueue<>(); 37 | int total = 0; 38 | 39 | //Add arrays to Heap 40 | for (int i = 0; i < arr.length; i++) { 41 | queue.add(new ArrayContainer(arr[i], 0)); 42 | total = total + arr[i].length; 43 | } 44 | int m = 0; 45 | int[] result = new int[total]; 46 | 47 | //while heap is not empty 48 | while (!queue.isEmpty()) { 49 | ArrayContainer ac = queue.poll(); 50 | result[m++] = ac.arr[ac.index]; 51 | if (ac.index < ac.arr.length - 1) { 52 | queue.add(new ArrayContainer(ac.arr, ac.index + 1)); 53 | } 54 | } 55 | return result; 56 | } 57 | 58 | public static void main(String[] args) { 59 | int[] arr1 = {1, 3, 5, 7}; 60 | int[] arr2 = {2, 4, 6, 8}; 61 | int[] arr3 = {0, 9, 10, 11}; 62 | 63 | int[] result = mergeKSortedArray(new int[][]{arr1, arr2, arr3}); 64 | System.out.println(Arrays.toString(result)); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/LinkedList/ArrayToLinkedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Array To Linked List.java 3 | * * Created by Rafsan Ahmad on 10/28/21, 4:19 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.LinkedList; 9 | 10 | public class ArrayToLinkedList { 11 | /*Given an array arr[] of size N. The task is to create linked list from the given array. 12 | Examples: 13 | 14 | 15 | Input : arr[]={1, 2, 3, 4, 5} 16 | Output : 1->2->3->4->5 17 | 18 | Input :arr[]={10, 11, 12, 13, 14} 19 | Output : 10->11->12->13->14*/ 20 | 21 | public ListNode insertNode(ListNode root, int data) { 22 | ListNode tempNode = new ListNode(data); 23 | tempNode.next = root; 24 | root = tempNode; 25 | return root; 26 | } 27 | 28 | public ListNode array2List(int[] arr) { 29 | ListNode root = null; 30 | for (int i = arr.length - 1; i >= 0; i--) { 31 | root = insertNode(root, arr[i]); 32 | } 33 | return root; 34 | } 35 | 36 | public void printList(ListNode node) { 37 | while (node != null) { 38 | System.out.print(node.val + " "); 39 | node = node.next; 40 | } 41 | } 42 | 43 | public static void main(String[] args) { 44 | ArrayToLinkedList list = new ArrayToLinkedList(); 45 | int[] arr = {1, 2, 3, 4, 5}; 46 | ListNode node = list.array2List(arr); 47 | list.printList(node); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/LinkedList/ListNode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * ListNode.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.LinkedList; 9 | 10 | public class ListNode { 11 | public int val; 12 | public ListNode next; 13 | 14 | public ListNode() { 15 | } 16 | 17 | public ListNode(int val) { 18 | this.val = val; 19 | } 20 | 21 | ListNode(int val, ListNode next) { 22 | this.val = val; 23 | this.next = next; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/LinkedList/OddEvenLinkList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Odd Even Linked List.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.LinkedList; 9 | 10 | public class OddEvenLinkList { 11 | //Leetcode 328 12 | /* 13 | Given the head of a singly linked list, group all the nodes with odd indices together 14 | followed by the nodes with even indices, and return the reordered list. 15 | The first node is considered odd, and the second node is even, and so on. 16 | Note that the relative order inside both the even and odd groups should remain as it was in the input 17 | Input: head = [1,2,3,4,5] 18 | Output: [1,3,5,2,4] 19 | */ 20 | 21 | public ListNode oddEvenList(ListNode head) { 22 | if (head == null) return null; 23 | 24 | ListNode odd = head; 25 | ListNode even = head.next; 26 | ListNode evenHead = even; 27 | 28 | while (even != null && even.next != null) { 29 | odd.next = even.next; 30 | odd = odd.next; 31 | even.next = odd.next; 32 | even = even.next; 33 | } 34 | odd.next = evenHead; 35 | return head; 36 | } 37 | 38 | public void printList(ListNode node) { 39 | while (node != null) { 40 | System.out.print(node.val + " "); 41 | node = node.next; 42 | } 43 | } 44 | 45 | public static void main(String[] args) { 46 | ListNode root = new ListNode(1); 47 | root.next = new ListNode(2); 48 | root.next.next = new ListNode(3); 49 | root.next.next.next = new ListNode(4); 50 | root.next.next.next.next = new ListNode(5); 51 | 52 | OddEvenLinkList list = new OddEvenLinkList(); 53 | ListNode result = list.oddEvenList(root); 54 | list.printList(result); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/LinkedList/PalindromeList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Palindrome List.java 4 | * * Created by Rafsan Ahmad on 11/28/22, 6:33 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.LinkedList; 10 | 11 | public class PalindromeList { 12 | //https://www.interviewbit.com/problems/palindrome-list/ 13 | /*Given a singly linked list, determine if its a palindrome. Return 1 or 0 denoting if its a palindrome or not, 14 | respectively. 15 | 16 | Notes: 17 | 18 | Expected solution is linear in time and constant in space. 19 | For example, 20 | 21 | List 1-->2-->1 is a palindrome. 22 | List 1-->2-->3 is not a palindrome.*/ 23 | 24 | public int palindromeList(ListNode A) { 25 | if (A == null) return 0; 26 | ListNode head = A; 27 | ListNode tail = null; 28 | 29 | while (A != null) { 30 | ListNode temp = tail; 31 | tail = new ListNode(A.val); 32 | tail.next = temp; 33 | A = A.next; 34 | } 35 | 36 | while (head != null && tail != null) { 37 | if (head.val != tail.val) return 0; 38 | head = head.next; 39 | tail = tail.next; 40 | } 41 | 42 | return 1; 43 | } 44 | 45 | public static void main(String[] args) { 46 | PalindromeList list = new PalindromeList(); 47 | ListNode node = new ListNode(10); 48 | node.next = new ListNode(7); 49 | node.next.next = new ListNode(10); 50 | System.out.println(list.palindromeList(node)); 51 | 52 | ListNode node2 = new ListNode(1); 53 | node2.next = new ListNode(2); 54 | node2.next.next = new ListNode(1); 55 | node2.next.next.next = new ListNode(2); 56 | System.out.println(list.palindromeList(node2)); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/LinkedList/RotateList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Rotate List.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.LinkedList; 9 | 10 | public class RotateList { 11 | //Leetcode 61 12 | /*Given the head of a linked list, rotate the list to the right by k places. 13 | * Input: head = [1,2,3,4,5], k = 2 14 | Output: [4,5,1,2,3]*/ 15 | 16 | public ListNode rotateRight(ListNode head, int k) { 17 | if (head == null) return null; 18 | ListNode copyHead = head; 19 | int len = 1; 20 | while (copyHead.next != null) { 21 | copyHead = copyHead.next; 22 | len++; 23 | } 24 | copyHead.next = head; 25 | for (int i = len - k % len; i > 1; i--) { 26 | head = head.next; 27 | } 28 | copyHead = head.next; 29 | head.next = null; 30 | return copyHead; 31 | } 32 | 33 | public void printList(ListNode node) { 34 | while (node != null) { 35 | System.out.print(node.val + " "); 36 | node = node.next; 37 | } 38 | } 39 | 40 | public static void main(String[] args) { 41 | ListNode node = new ListNode(1); 42 | node.next = new ListNode(2); 43 | node.next.next = new ListNode(3); 44 | node.next.next.next = new ListNode(4); 45 | node.next.next.next.next = new ListNode(5); 46 | RotateList rt = new RotateList(); 47 | ListNode result = rt.rotateRight(node, 2); 48 | rt.printList(result); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Matrix/Search2dMatrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Search a 2d Matrix.java 4 | * * Created by Rafsan Ahmad on 1/17/22, 3:21 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.Matrix; 10 | 11 | public class Search2dMatrix { 12 | //Leetcode 74 13 | /*Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following 14 | properties: 15 | 16 | Integers in each row are sorted from left to right. 17 | The first integer of each row is greater than the last integer of the previous row. 18 | 19 | 20 | Example 1: 21 | 1 | 3 | 5 |7 22 | 10 | 11 | 16 | 20 23 | 23 | 30 | 34 | 60 24 | 25 | Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 26 | Output: true 27 | 28 | Example 2: 29 | 30 | Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 31 | Output: false 32 | */ 33 | public boolean searchMatrix(int[][] matrix, int target) { 34 | int len = matrix[0].length; 35 | for (int i = 0; i < matrix.length; i++) { 36 | int first = matrix[i][0]; 37 | int last = matrix[i][len - 1]; 38 | if (target >= first && target <= last) { 39 | //In range 40 | int left = 0; 41 | int right = len - 1; 42 | while (left <= right) { 43 | int mid = (left + right) / 2; 44 | if (matrix[i][mid] == target) { 45 | return true; 46 | } else if (matrix[i][mid] <= target) { 47 | left = mid + 1; 48 | } else { 49 | right = mid - 1; 50 | } 51 | } 52 | } 53 | } 54 | return false; 55 | } 56 | 57 | public static void main(String[] args) { 58 | Search2dMatrix matrix = new Search2dMatrix(); 59 | int[][] arr = {{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}}; 60 | System.out.println(matrix.searchMatrix(arr, 3)); 61 | System.out.println(matrix.searchMatrix(arr, 13)); 62 | 63 | int[][] arr2 = {{1, 3}}; 64 | System.out.println(matrix.searchMatrix(arr2, 3)); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Matrix/SetMatrixZeroes.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Set Matrix Zeroes.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Matrix; 9 | 10 | import java.util.HashSet; 11 | 12 | public class SetMatrixZeroes { 13 | //Leetcode 73 14 | /* 15 | * Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, 16 | and return the matrix. 17 | 18 | You must do it in place. 19 | Example 1: 20 | Input: matrix = [[1,1,1],[1,0,1],[1,1,1]] 21 | Output: [[1,0,1],[0,0,0],[1,0,1]]*/ 22 | 23 | /* 1 1 1 1 0 1 24 | 1 0 1 -----> 0 0 0 25 | 1 1 1 1 0 1 26 | * */ 27 | 28 | public void setZeroes(int[][] matrix) { 29 | HashSet rows = new HashSet<>(); 30 | HashSet columns = new HashSet<>(); 31 | for (int i = 0; i < matrix.length; i++) { 32 | for (int j = 0; j < matrix[i].length; j++) { 33 | if (matrix[i][j] == 0) { 34 | rows.add(i); 35 | columns.add(j); 36 | } 37 | } 38 | } 39 | 40 | for (int i = 0; i < matrix.length; i++) { 41 | for (int j = 0; j < matrix[i].length; j++) { 42 | if (rows.contains(i) || columns.contains(j)) { 43 | matrix[i][j] = 0; 44 | } 45 | } 46 | } 47 | } 48 | 49 | public static void main(String[] args) { 50 | SetMatrixZeroes matrix = new SetMatrixZeroes(); 51 | int[][] arr = { 52 | {1, 1, 1}, 53 | {1, 0, 1}, 54 | {1, 1, 1}}; 55 | matrix.setZeroes(arr); 56 | for (int i = 0; i < arr.length; i++) { 57 | for (int j = 0; j < arr[i].length; j++) { 58 | System.out.print(arr[i][j] + " "); 59 | } 60 | System.out.println(); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/NumberTheory/Math/CheckIfStraightLine.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Check If Straight Line.java 4 | * * Created by Rafsan Ahmad on 12/11/21, 4:25 AM 5 | * * Copyright (c) 2021 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.NumberTheory.Math; 10 | 11 | public class CheckIfStraightLine { 12 | //Leetcode 1232 13 | //res/line1.jpeg 14 | //res/line2.jpeg 15 | /*You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. 16 | Check if these points make a straight line in the XY plane. 17 | 18 | Example 1: 19 | Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] 20 | Output: true 21 | 22 | 23 | Example 2: 24 | Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] 25 | Output: false 26 | */ 27 | 28 | public boolean checkStraightLine(int[][] coordinates) { 29 | int x0 = coordinates[0][0]; 30 | int y0 = coordinates[0][1]; 31 | int x1 = coordinates[1][0]; 32 | int y1 = coordinates[1][1]; 33 | int dx = x1 - x0; 34 | int dy = y1 - y0; 35 | 36 | for (int i = 2; i < coordinates.length; ++i) { 37 | int x = coordinates[i][0]; 38 | int y = coordinates[i][1]; 39 | if ((x - x0) * dy != (y - y0) * dx) 40 | return false; 41 | } 42 | 43 | return true; 44 | } 45 | 46 | public static void main(String[] args) { 47 | CheckIfStraightLine line = new CheckIfStraightLine(); 48 | int[][] coordinates = {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}}; 49 | System.out.println(line.checkStraightLine(coordinates)); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/NumberTheory/Math/CountDiv.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Count Div.java 4 | * * Created by Rafsan Ahmad on 1/23/22, 8:25 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.NumberTheory.Math; 10 | 11 | public class CountDiv { 12 | /*Write a function: 13 | 14 | class Solution { public int solution(int A, int B, int K); } 15 | 16 | that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible 17 | by K, i.e.: 18 | 19 | { i : A ≤ i ≤ B, i mod K = 0 } 20 | 21 | For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible 22 | by 2 within the range [6..11], namely 6, 8 and 10. 23 | 24 | Write an efficient algorithm for the following assumptions: 25 | 26 | A and B are integers within the range [0..2,000,000,000]; 27 | K is an integer within the range [1..2,000,000,000]; 28 | A ≤ B.*/ 29 | 30 | public int solution(int A, int B, int K) { 31 | int count = 0; 32 | if (A % K == 0) count++; 33 | if (A != B) { 34 | int firstDivided = A / K; 35 | int secondDivided = B / K; 36 | count += secondDivided - firstDivided; 37 | } 38 | return count; 39 | } 40 | 41 | public static void main(String[] args) { 42 | CountDiv div = new CountDiv(); 43 | System.out.println(div.solution(0, 0, 1)); 44 | System.out.println(div.solution(6, 11, 1)); 45 | System.out.println(div.solution(6, 11, 2)); 46 | System.out.println(div.solution(6, 11, 3)); 47 | System.out.println(div.solution(6, 11, 4)); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/NumberTheory/Math/HappyNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Happy Number.java 4 | * * Created by Rafsan Ahmad on 12/21/21, 12:21 AM 5 | * * Copyright (c) 2021 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.NumberTheory.Math; 10 | 11 | import java.util.HashSet; 12 | 13 | public class HappyNumber { 14 | /*Write an algorithm to determine if a number n is happy. 15 | 16 | A happy number is a number defined by the following process: 17 | 18 | Starting with any positive integer, replace the number by the sum of the squares of its digits. 19 | Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not 20 | include 1. 21 | Those numbers for which this process ends in 1 are happy. 22 | Return true if n is a happy number, and false if not. 23 | 24 | Example 1: 25 | Input: n = 19 26 | Output: true 27 | Explanation: 28 | 12 + 92 = 82 29 | 82 + 22 = 68 30 | 62 + 82 = 100 31 | 12 + 02 + 02 = 1 32 | 33 | Example 2: 34 | Input: n = 2 35 | Output: false 36 | 37 | Constraints: 38 | 39 | 1 <= n <= 231 - 1 40 | */ 41 | public boolean isHappy(int n) { 42 | HashSet set = new HashSet<>(); 43 | int nextNum = getNextNumber(n); 44 | while (nextNum != 1 && !set.contains(nextNum)) { 45 | set.add(nextNum); 46 | nextNum = getNextNumber(nextNum); 47 | } 48 | if (nextNum == 1) return true; 49 | return false; 50 | } 51 | 52 | public int getNextNumber(int num) { 53 | int sum = 0; 54 | while (num > 0) { 55 | int digit = num % 10; 56 | sum += digit * digit; 57 | num = num / 10; 58 | } 59 | return sum; 60 | } 61 | 62 | public static void main(String[] args) { 63 | HappyNumber number = new HappyNumber(); 64 | System.out.println(number.isHappy(19)); 65 | System.out.println(number.isHappy(17)); 66 | System.out.println(number.isHappy(2)); 67 | System.out.println(number.isHappy(231)); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/NumberTheory/Math/NextSmallestPalindrome.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Next Smallest Palindrome.java 3 | * * Created by Rafsan Ahmad on 11/30/21, 4:34 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.NumberTheory.Math; 9 | 10 | import java.math.BigInteger; 11 | 12 | public class NextSmallestPalindrome { 13 | //https://www.interviewbit.com/problems/next-smallest-palindrome/ 14 | /*Problem Description 15 | Given a numeric string A representing a large number you need to find the next smallest palindrome greater 16 | than this number. 17 | 18 | Problem Constraints 19 | 1 <= |A| <= 100 20 | 21 | A doesn't start with zeroes and always contain digits from 0-9. 22 | 23 | Input Format 24 | First and only argument is an string A. 25 | 26 | Output Format 27 | Return a numeric string denoting the next smallest palindrome greater than A. 28 | 29 | Example Input 30 | Input 1: 31 | A = "23545" 32 | 33 | Input 2: 34 | A = "999" 35 | 36 | Example Output 37 | Output 1: 38 | "23632" 39 | 40 | Output 2: 41 | "1001" 42 | */ 43 | public String nextSmallestPalindrome(String num) { 44 | int len = num.length(); 45 | String left = num.substring(0, len / 2); 46 | String middle = num.substring(len / 2, len - len / 2); 47 | String right = num.substring(len - len / 2); 48 | 49 | if (right.compareTo(reverse(left)) < 0) 50 | return left + middle + reverse(left); 51 | 52 | String next = new BigInteger(left + middle).add(BigInteger.ONE).toString(); 53 | String firstPart = next.substring(0, left.length() + middle.length()); 54 | String lastPart = reverse(next).substring(middle.length()); 55 | return firstPart + lastPart; 56 | } 57 | 58 | private static String reverse(String s) { 59 | return new StringBuilder(s).reverse().toString(); 60 | } 61 | 62 | public static void main(String[] args) { 63 | NextSmallestPalindrome palindrome = new NextSmallestPalindrome(); 64 | System.out.println(palindrome.nextSmallestPalindrome("23545")); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/NumberTheory/Math/Pow_x_n.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * pow(x, n).java 4 | * * Created by Rafsan Ahmad on 6/10/24, 12:57 AM 5 | * * Copyright (c) 2024 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package javaclasses.NumberTheory.Math; 11 | 12 | public class Pow_x_n { 13 | /*Implement pow(x, n), which calculates x raised to the power n (i.e., xn). 14 | 15 | Example 1: 16 | 17 | Input: x = 2.00000, n = 10 18 | Output: 1024.00000 19 | Example 2: 20 | 21 | Input: x = 2.10000, n = 3 22 | Output: 9.26100 23 | Example 3: 24 | 25 | Input: x = 2.00000, n = -2 26 | Output: 0.25000 27 | Explanation: 2-2 = 1/22 = 1/4 = 0.25 28 | 29 | 30 | Constraints: 31 | 32 | -100.0 < x < 100.0 33 | -2^31 <= n <= 2^31-1 34 | n is an integer. 35 | Either x is not zero or n > 0. 36 | -10^4 <= x^n <= 10^4 37 | */ 38 | 39 | /* 40 | * Time complexity: O(logn) 41 | * Solution: 42 | * 2^10 can be written as: 43 | * n=10 is even: n = n/2 44 | * (2*2)^5 = 4^5 45 | * n=5 is odd: n = n-1 46 | * 4*4^4 47 | * 4^4 can be written as: 48 | * n=4 is even: n = n/2 49 | * (4*4)^2 = 16^2 50 | * 16*16 = 256 51 | * 4*256 = 1024 52 | * */ 53 | 54 | public double myPow(double x, int n) { 55 | long power = (long) n; 56 | power = Math.abs(power); 57 | double result = 1.0; 58 | while (power > 0) { 59 | if (power % 2 == 1) { 60 | //Odd 61 | result = result * x; 62 | power--; 63 | } else { 64 | //Even 65 | x = x * x; 66 | power /= 2; 67 | } 68 | } 69 | 70 | if (n < 0) return 1 / result; 71 | return result; 72 | } 73 | 74 | public static void main(String[] args) { 75 | Pow_x_n powXN = new Pow_x_n(); 76 | System.out.println(powXN.myPow(2, 10)); 77 | System.out.println(powXN.myPow(2.00000, -2)); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/NumberTheory/Math/PowerOfNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Power Of Number.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:50 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.NumberTheory.Math; 9 | 10 | 11 | public class PowerOfNumber { 12 | static private final String LOG_TAG = PowerOfNumber.class.getSimpleName(); 13 | static double x = 3; 14 | static double n = -1; 15 | 16 | public static void main(String arg[]) { 17 | System.out.println("power equals " + pow(x, n)); 18 | } 19 | 20 | public static double pow(double x, double n) { 21 | double y; 22 | 23 | if (n == 0) { 24 | return 1; 25 | } else if (n > 0 && n % 2 == 0) { 26 | y = Math.pow(x, (n / 2)); 27 | return y * y; 28 | } else if (n > 0 && n % 2 == 1) { 29 | y = Math.pow(x, (n - 1)); 30 | return y * x; 31 | } else { 32 | return 1 / (Math.pow(x, -1 * n)); 33 | } 34 | } 35 | } 36 | 37 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/NumberTheory/Math/ReachNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Reach a Number.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:50 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.NumberTheory.Math; 9 | 10 | public class ReachNumber { 11 | //Leetcode 754 12 | /*You are standing at position 0 on an infinite number line. There is a destination at position 13 | target. 14 | 15 | You can make some number of moves numMoves so that: 16 | 17 | On each move, you can either go left or right. 18 | During the ith move (starting from i == 1 to i == numMoves), you take i steps in the chosen direction. 19 | Given the integer target, return the minimum number of moves required (i.e., the minimum numMoves) to 20 | reach the destination. 21 | 22 | Example 1: 23 | Input: target = 2 24 | Output: 3 25 | Explanation: 26 | On the 1st move, we step from 0 to 1 (1 step). 27 | On the 2nd move, we step from 1 to -1 (2 steps). 28 | On the 3rd move, we step from -1 to 2 (3 steps). 29 | 30 | Example 2: 31 | Input: target = 3 32 | Output: 2 33 | Explanation: 34 | On the 1st move, we step from 0 to 1 (1 step). 35 | On the 2nd move, we step from 1 to 3 (2 steps).*/ 36 | 37 | int reachNumber(int target) { 38 | int sum = 0; 39 | int k = 0; 40 | target = Math.abs(target); 41 | while (sum < target) { 42 | k++; 43 | sum += k; 44 | } 45 | 46 | if ((sum - target) % 2 == 0) { 47 | return k; 48 | } else { 49 | if ((k % 2) == 0) { 50 | //Even 51 | return k + 1; 52 | } else { 53 | //odd 54 | return k + 2; 55 | } 56 | } 57 | } 58 | 59 | public static void main(String[] args) { 60 | ReachNumber number = new ReachNumber(); 61 | System.out.println(number.reachNumber(2)); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/NumberTheory/Math/TwoSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Two Sum.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:50 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.NumberTheory.Math; 9 | 10 | import java.util.Arrays; 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | 14 | public class TwoSum { 15 | //Leetcode 1 16 | /*Given an array of integers nums and an integer target, return indices of the two numbers such that 17 | they add up to target. 18 | 19 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 20 | 21 | You can return the answer in any order. 22 | 23 | Example 1: 24 | Input: nums = [2,7,11,15], target = 9 25 | Output: [0,1] 26 | Output: Because nums[0] + nums[1] == 9, we return [0, 1]. 27 | 28 | Example 2: 29 | Input: nums = [3,2,4], target = 6 30 | Output: [1,2] 31 | 32 | Example 3: 33 | Input: nums = [3,3], target = 6 34 | Output: [0,1] 35 | */ 36 | public int[] twoSum(int[] nums, int target) { 37 | Map map = new HashMap<>(); 38 | for (int i = 0; i < nums.length; i++) { 39 | if (map.containsKey(target - nums[i])) { 40 | return new int[]{map.get(target - nums[i]), i}; 41 | } else { 42 | map.put(nums[i], i); 43 | } 44 | } 45 | return new int[]{-1, -1}; 46 | } 47 | 48 | public static void main(String[] args) { 49 | int[] arr = {2, 7, 11, 15}; 50 | TwoSum sum = new TwoSum(); 51 | System.out.println(Arrays.toString(sum.twoSum(arr, 9))); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/OOPDesign/UnixFileApi/File.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * File.java 4 | * * Created by Rafsan Ahmad on 11/21/24, 1:12 PM 5 | * * Copyright (c) 2024 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package javaclasses.OOPDesign.UnixFileApi; 11 | 12 | public class File { 13 | private String name; 14 | private String extension; 15 | private int size; 16 | 17 | public File(String name, String extension, int size) { 18 | this.name = name; 19 | this.extension = extension; 20 | this.size = size; 21 | } 22 | 23 | public String getName() { 24 | return name; 25 | } 26 | 27 | public String getExtension() { 28 | return extension; 29 | } 30 | 31 | public int getSize() { 32 | return size; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/OOPDesign/UnixFileApi/FileSystem.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * FileSystem.java 4 | * * Created by Rafsan Ahmad on 11/21/24, 1:15 PM 5 | * * Copyright (c) 2024 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package javaclasses.OOPDesign.UnixFileApi; 11 | 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | 15 | public class FileSystem { 16 | private String name; 17 | private boolean isDirectory; 18 | private List subDirectories; 19 | private List files; 20 | 21 | public FileSystem(String name, boolean isDirectory) { 22 | this.name = name; 23 | this.isDirectory = isDirectory; 24 | this.subDirectories = new ArrayList<>(); 25 | this.files = new ArrayList<>(); 26 | } 27 | 28 | public void addFile(File file) { 29 | this.files.add(file); 30 | } 31 | 32 | public void addSubDirectory(FileSystem subDirectory) { 33 | this.subDirectories.add(subDirectory); 34 | } 35 | 36 | public List getSubDirectories() { 37 | return subDirectories; 38 | } 39 | 40 | public List getFiles() { 41 | return files; 42 | } 43 | 44 | public String getName() { 45 | return name; 46 | } 47 | 48 | public boolean isDirectory() { 49 | return isDirectory; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/OOPDesign/UnixFileApi/Filter/ExtensionFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * ExtensionFilter.java 4 | * * Created by Rafsan Ahmad on 11/21/24, 1:14 PM 5 | * * Copyright (c) 2024 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package javaclasses.OOPDesign.UnixFileApi.Filter; 11 | 12 | import javaclasses.OOPDesign.UnixFileApi.File; 13 | 14 | public class ExtensionFilter extends Filter { 15 | private String extension; 16 | 17 | public ExtensionFilter(String extension) { 18 | this.extension = extension; 19 | } 20 | 21 | @Override 22 | public boolean match(File file) { 23 | return file.getExtension().equals(extension); 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/OOPDesign/UnixFileApi/Filter/Filter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Filter.java 4 | * * Created by Rafsan Ahmad on 11/21/24, 1:14 PM 5 | * * Copyright (c) 2024 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package javaclasses.OOPDesign.UnixFileApi.Filter; 11 | 12 | import javaclasses.OOPDesign.UnixFileApi.File; 13 | 14 | public abstract class Filter { 15 | public abstract boolean match(File file); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/OOPDesign/UnixFileApi/Filter/NameFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * NameFilter.java 4 | * * Created by Rafsan Ahmad on 11/21/24, 1:14 PM 5 | * * Copyright (c) 2024 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package javaclasses.OOPDesign.UnixFileApi.Filter; 11 | 12 | import javaclasses.OOPDesign.UnixFileApi.File; 13 | 14 | public class NameFilter extends Filter { 15 | private String name; 16 | 17 | public NameFilter(String name) { 18 | this.name = name; 19 | } 20 | 21 | @Override 22 | public boolean match(File file) { 23 | return file.getName().equals(name); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/OOPDesign/UnixFileApi/Filter/SizeFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * SizeFilter.java 4 | * * Created by Rafsan Ahmad on 11/21/24, 1:14 PM 5 | * * Copyright (c) 2024 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package javaclasses.OOPDesign.UnixFileApi.Filter; 11 | 12 | import javaclasses.OOPDesign.UnixFileApi.File; 13 | 14 | public class SizeFilter extends Filter { 15 | private int size; 16 | private String operator; 17 | 18 | public SizeFilter(int size, String operator) { 19 | this.size = size; 20 | this.operator = operator; 21 | } 22 | 23 | @Override 24 | public boolean match(File file) { 25 | switch (operator) { 26 | case ">": 27 | return file.getSize() > size; 28 | case ">=": 29 | return file.getSize() >= size; 30 | case "<": 31 | return file.getSize() < size; 32 | case "<=": 33 | return file.getSize() <= size; 34 | case "==": 35 | return file.getSize() == size; 36 | default: 37 | return false; 38 | } 39 | } 40 | } 41 | 42 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/OOPDesign/UnixFileApi/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Main.java 4 | * * Created by Rafsan Ahmad on 11/21/24, 1:17 PM 5 | * * Copyright (c) 2024 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package javaclasses.OOPDesign.UnixFileApi; 11 | 12 | import java.util.HashMap; 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | public class Main { 17 | /* 18 | # API - Search the File System 19 | 20 | # Searching Files based on Name, Extension and Size 21 | 22 | # input for the search (directory) 23 | */ 24 | public static void main(String[] args) { 25 | File f1 = new File("abc", "txt", 10); 26 | File f2 = new File("cde", "txt", 20); 27 | File f3 = new File("def", "pdf", 30); 28 | File f4 = new File("ghi", "py", 5); 29 | File f5 = new File("uvw", "java", 10); 30 | 31 | FileSystem root = new FileSystem("/", true); 32 | root.addFile(f1); 33 | root.addFile(f2); 34 | root.addFile(f3); 35 | root.addFile(f4); 36 | root.addFile(f5); 37 | 38 | Map filters = new HashMap<>(); 39 | filters.put("ExtensionFilter", "java"); 40 | filters.put("SizeFilter", new Object[]{10, ">="}); 41 | 42 | SearchFile search = new SearchFile(root, filters, "OR"); 43 | List result = search.findFiles(); 44 | 45 | for (String fileName : result) { 46 | System.out.println(fileName); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/OutputQuiz/AbstractClassQuiz.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Abstract Class Quiz.java 4 | * * Created by Rafsan Ahmad on 1/12/22, 9:24 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.OutputQuiz; 10 | 11 | abstract class Animal { 12 | public abstract void makeNoise(); 13 | 14 | public abstract void move(); 15 | } 16 | 17 | abstract class Demo { 18 | public int a; 19 | 20 | void demo() { 21 | a = 10; 22 | } 23 | 24 | abstract public void get(); 25 | } 26 | 27 | abstract class Canine extends Animal { 28 | public void wagTail() { 29 | System.out.println("Wagging"); 30 | } 31 | 32 | @Override 33 | public void move() { 34 | System.out.println("Run"); 35 | } 36 | } 37 | 38 | class Dog extends Canine { 39 | 40 | public void fetch() { 41 | System.out.println("Fetch"); 42 | } 43 | 44 | @Override 45 | public void makeNoise() { 46 | System.out.println("Bark"); 47 | } 48 | } 49 | 50 | class DemoTest extends Demo { 51 | public void get() { 52 | System.out.println("a = " + a); 53 | } 54 | } 55 | 56 | public class AbstractClassQuiz { 57 | public static void main(String[] args) { 58 | //Quiz 1 59 | Dog d = new Dog(); 60 | d.makeNoise(); 61 | d.move(); 62 | d.wagTail(); 63 | d.fetch(); 64 | 65 | Canine c = new Dog(); 66 | c.makeNoise(); 67 | c.move(); 68 | c.wagTail(); 69 | //c.fetch(); 70 | 71 | Animal a = new Dog(); 72 | a.makeNoise(); 73 | a.move(); 74 | //a.wagTail(); 75 | //a.fetch(); 76 | 77 | //Quiz 2 78 | DemoTest obj = new DemoTest(); 79 | obj.get(); // a = 0 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/OutputQuiz/PassByValueReferenceOutput.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Pass By Value Reference Output.java 4 | * * Created by Rafsan Ahmad on 1/13/22, 3:43 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.OutputQuiz; 10 | 11 | public class PassByValueReferenceOutput { 12 | 13 | public static void changeTheString(String weather) { 14 | weather = "sunny"; 15 | } 16 | 17 | public static void changeTheArray(String[] rainyDays) { 18 | rainyDays[1] = "Sunday"; 19 | } 20 | 21 | public static void changeTheObject(Forecast forecast) { 22 | forecast.temperature = 35; 23 | } 24 | 25 | public static void main(String[] args) { 26 | String weather = "rainy"; 27 | changeTheString(weather); 28 | System.out.println("The Weather is " + weather); 29 | 30 | String[] rainyDays = new String[]{"Monday", "Friday"}; 31 | changeTheArray(rainyDays); 32 | System.out.println("The rainy days were on " + rainyDays[0] + " and " + rainyDays[1]); 33 | 34 | Forecast forecast = new Forecast(); 35 | forecast.pressure = 700; 36 | forecast.temperature = 20; 37 | changeTheObject(forecast); 38 | System.out.println("The temperature is " + forecast.temperature + "C"); 39 | } 40 | } 41 | 42 | class Forecast extends PassByValueReferenceOutput { 43 | public int temperature; 44 | public int pressure; 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/OutputQuiz/StackQueueOutput.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Stack Queue Output.java 4 | * * Created by Rafsan Ahmad on 1/15/22, 4:49 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.OutputQuiz; 10 | 11 | import java.util.LinkedList; 12 | import java.util.Queue; 13 | import java.util.Stack; 14 | 15 | public class StackQueueOutput { 16 | 17 | public void stackQueueTest() { 18 | Stack stack = new Stack<>(); 19 | Queue queue = new LinkedList<>(); 20 | stack.push("Apple"); 21 | stack.push("Banana"); 22 | stack.push("Cherry"); 23 | 24 | ((LinkedList) queue).add(stack.pop()); 25 | stack.push("Dingleberrry"); 26 | stack.push("Eggplant"); 27 | ((LinkedList) queue).add("Fig"); 28 | 29 | stack.push(queue.remove()); 30 | ((LinkedList) queue).add(stack.pop()); 31 | ((LinkedList) queue).add(stack.pop()); 32 | 33 | System.out.println(stack); //Apple, Banana, Dingleberry 34 | System.out.println(queue); //Fig, Cherry, Eggplant 35 | } 36 | 37 | public static void main(String[] args) { 38 | StackQueueOutput output = new StackQueueOutput(); 39 | output.stackQueueTest(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/OutputQuiz/StaticBlock.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Created by Rafsan Ahmad on 12/5/21, 10:33 AM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.OutputQuiz; 9 | 10 | class Scaler { 11 | static int i; 12 | 13 | static { 14 | System.out.println("a"); 15 | 16 | i = 100; 17 | } 18 | } 19 | 20 | public class StaticBlock { 21 | static { 22 | System.out.println("b"); 23 | } 24 | 25 | public static void main(String[] args) { 26 | System.out.println("c"); 27 | 28 | System.out.println(Scaler.i); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/OutputQuiz/ThreadOutput.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Thread Output.java 4 | * * Created by Rafsan Ahmad on 1/13/22, 3:02 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.OutputQuiz; 10 | 11 | class newThread extends Thread { 12 | 13 | newThread() { 14 | super("My Thread"); 15 | start(); 16 | } 17 | 18 | public void run() { 19 | // prints: Thread[My Thread,5,main] 20 | // 5 = Thread Priority 21 | // My Thread = Thread name 22 | System.out.println(this); 23 | } 24 | } 25 | 26 | class Test implements Runnable { 27 | 28 | @Override 29 | public void run() { 30 | System.out.println("TURING"); 31 | } 32 | } 33 | 34 | public class ThreadOutput { 35 | 36 | public static void main(String[] args) throws InterruptedException { 37 | new newThread(); 38 | 39 | Thread thread1 = new Thread(new Test()); 40 | thread1.start(); 41 | thread1.start(); // Throws illegal thread state exception 42 | System.out.println(thread1.getState()); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Recursion/EmployeeReporting.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Employee Reporting.java 4 | * * Created by Rafsan Ahmad on 2/20/22, 1:56 AM 5 | * * Copyright (c) 2023 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.Recursion; 10 | 11 | import java.util.ArrayList; 12 | import java.util.Arrays; 13 | import java.util.HashMap; 14 | import java.util.List; 15 | import java.util.Map; 16 | 17 | 18 | public class EmployeeReporting { 19 | /* 20 | A company's organizational structure is represented as 21 | 1: 2, 3, 4 22 | In the above employees with id 2, 3 and 4 report to 1 23 | Assume the following hierarchy. 24 | 1: 2, 3, 4 25 | 3: 5, 6, 7 26 | 5: 8, 9, 10 27 | Given an employee Id, return all the employees reporting to him directly or indirectly 28 | */ 29 | 30 | public List getReportees(Map> empMap, int manager) { 31 | List result = new ArrayList<>(); 32 | getReporteesHelper(result, empMap, manager); 33 | return result; 34 | } 35 | 36 | private void getReporteesHelper(List result, Map> empMap, Integer manager) { 37 | List reportees = empMap.get(manager); 38 | if (reportees == null) 39 | return; 40 | for (Integer i : reportees) { 41 | result.add(i); 42 | getReporteesHelper(result, empMap, i); 43 | } 44 | } 45 | 46 | public static void main(String[] args) { 47 | Map> empMap = new HashMap<>(); 48 | empMap.put(1, Arrays.asList(2, 3, 4)); 49 | empMap.put(3, Arrays.asList(5, 6, 7)); 50 | empMap.put(5, Arrays.asList(8, 9, 10)); 51 | empMap.put(9, Arrays.asList(11, 12, 13)); 52 | EmployeeReporting reporting = new EmployeeReporting(); 53 | System.out.println(reporting.getReportees(empMap, 3)); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Recursion/GenerateParenthesis.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * Generate Parenthesis.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Recursion 9 | 10 | class GenerateParenthesis { 11 | //Leetcode 22 12 | /*Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 13 | 14 | Example 1: 15 | 16 | Input: n = 3 17 | Output: ["((()))","(()())","(())()","()(())","()()()"] 18 | Example 2: 19 | 20 | Input: n = 1 21 | Output: ["()"] 22 | */ 23 | fun generateParenthesis(n: Int): Array { 24 | val result = ArrayList() 25 | dfs(result, "", n, n) 26 | return result.toTypedArray() 27 | } 28 | 29 | fun dfs(result: ArrayList, str: String, left: Int, right: Int) { 30 | if (left > right) return 31 | if (left == 0 && right == 0) { 32 | result.add(str) 33 | return 34 | } 35 | if (left > 0) { 36 | dfs(result, "$str(", left - 1, right) 37 | } 38 | if (right > 0) { 39 | dfs(result, "$str)", left, right - 1) 40 | } 41 | } 42 | } 43 | 44 | fun main(args: Array) { 45 | val parenthesis = GenerateParenthesis() 46 | println(parenthesis.generateParenthesis(3).contentToString()); 47 | } -------------------------------------------------------------------------------- /src/main/java/javaclasses/Recursion/ReverseString.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Reverse String.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Recursion; 9 | 10 | /*Write a java program to reverse a string using recursion. In this tutorial, 11 | I am going to explain how to write a java code which reverse an input string using recursion. 12 | I have also added the video at the end of this tutorial. 13 | 14 | For example : 15 | 16 | Input String: Object 17 | Output String: tcejbO*/ 18 | 19 | /*In this code example, we write a function reverse which takes a string as an argument and reverses it 20 | recursively. The time complexity of this approach is O(n).*/ 21 | 22 | /** 23 | * Reverse a String using Recursion 24 | */ 25 | public class ReverseString { 26 | 27 | //Method which reverse a string 28 | private static String reverse(String str) { 29 | 30 | //Terminating condition 31 | if (str == null || str.length() <= 1) { 32 | return str; 33 | } 34 | 35 | //Recursive function call 36 | return reverse(str.substring(1)) + str.charAt(0); 37 | } 38 | 39 | public static void main(String[] args) { 40 | 41 | String str = "Object"; 42 | String revStr = reverse(str); 43 | 44 | System.out.println(revStr); 45 | 46 | } 47 | } 48 | 49 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/StackQueue/LongestValidParenthesis.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Longest Valid Parenthesis.java 4 | * * Created by Rafsan Ahmad on 12/16/24, 2:14PM 5 | * * Copyright (c) 2024 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package javaclasses.StackQueue; 11 | 12 | import java.util.Stack; 13 | 14 | public class LongestValidParenthesis { 15 | //https://leetcode.com/problems/longest-valid-parentheses/description/ 16 | /*Given a string containing just the characters '(' and ')', return the length of the longest 17 | valid (well-formed) parentheses substring. 18 | 19 | Example 1: 20 | Input: s = "(()" 21 | Output: 2 22 | Explanation: The longest valid parentheses substring is "()". 23 | 24 | Example 2: 25 | Input: s = ")()())" 26 | Output: 4 27 | Explanation: The longest valid parentheses substring is "()()". 28 | 29 | Example 3: 30 | Input: s = "" 31 | Output: 0 32 | 33 | Constraints: 34 | 0 <= s.length <= 3 * 10^4 35 | s[i] is '(', or ')'.*/ 36 | 37 | public int longestValidParentheses(String s) { 38 | if (s.length() <= 1) return 0; 39 | 40 | int result = 0; 41 | int left = -1; 42 | Stack stack = new Stack<>(); 43 | 44 | for (int i = 0; i < s.length(); i++) { 45 | if (s.charAt(i) == '(') 46 | stack.push(i); 47 | 48 | else { 49 | if (stack.isEmpty()) { 50 | left = i; 51 | } else { 52 | stack.pop(); 53 | if (stack.isEmpty()) { 54 | result = Math.max(result, i - left); 55 | } else { 56 | result = Math.max(result, i - stack.peek()); 57 | } 58 | } 59 | } 60 | } 61 | 62 | return result; 63 | } 64 | 65 | public static void main(String[] args) { 66 | LongestValidParenthesis parenthesis = new LongestValidParenthesis(); 67 | System.out.println(parenthesis.longestValidParentheses(")()())")); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/StackQueue/NextGreaterElement.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Next Greater Element.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:50 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.StackQueue; 9 | 10 | import java.util.Arrays; 11 | import java.util.Stack; 12 | 13 | public class NextGreaterElement { 14 | //Leetcode 503 15 | /*Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), 16 | return the next greater number for every element in nums. 17 | 18 | The next greater number of a number x is the first greater number to its traversing-order next in the array, 19 | which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number. 20 | 21 | 22 | Example 1: 23 | Input: nums = [1,2,1] 24 | Output: [2,-1,2] 25 | Explanation: The first 1's next greater number is 2; 26 | The number 2 can't find next greater number. 27 | The second 1's next greater number needs to search circularly, which is also 2. 28 | 29 | Example 2: 30 | Input: nums = [1,2,3,4,3] 31 | Output: [2,3,4,-1,4]*/ 32 | 33 | public int[] nextGreaterElementsCircular(int[] nums) { 34 | int n = nums.length; 35 | int[] res = new int[n]; 36 | Stack st = new Stack<>(); 37 | for (int i = 2 * n - 1; i >= 0; i--) { 38 | while (!st.isEmpty() && st.peek() <= nums[i % n]) { 39 | st.pop(); 40 | } 41 | 42 | if (i < n) { 43 | if (!st.isEmpty()) res[i] = st.peek(); 44 | else res[i] = -1; 45 | } 46 | 47 | st.push(nums[i % n]); 48 | } 49 | return res; 50 | } 51 | 52 | public static void main(String[] args) { 53 | int[] ar = {1, 2, 3, 4, 3}; 54 | NextGreaterElement element = new NextGreaterElement(); 55 | System.out.println(Arrays.toString(element.nextGreaterElementsCircular(ar))); 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/StackQueue/ValidParenthesis.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Valid Parenthesis.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:50 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.StackQueue; 9 | 10 | //Leetcode 20 11 | /* 12 | * Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', 13 | determine if the input string is valid. 14 | 15 | An input string is valid if: 16 | 17 | Open brackets must be closed by the same type of brackets. 18 | Open brackets must be closed in the correct order. 19 | 20 | 21 | Example 1: 22 | 23 | Input: s = "()" 24 | Output: true 25 | Example 2: 26 | 27 | Input: s = "()[]{}" 28 | Output: true 29 | Example 3: 30 | 31 | Input: s = "(]" 32 | Output: false*/ 33 | 34 | import java.util.Stack; 35 | 36 | public class ValidParenthesis { 37 | //Using Stack 38 | public boolean isValid(String s) { 39 | Stack st = new Stack<>(); 40 | 41 | if (s.isEmpty()) { 42 | return true; 43 | } 44 | for (int i = 0; i < s.length(); i++) { 45 | if (s.charAt(i) == ')' && !st.isEmpty() && st.peek() == '(') { 46 | st.pop(); 47 | } else if (s.charAt(i) == '}' && !st.isEmpty() && st.peek() == '{') { 48 | st.pop(); 49 | } else if (s.charAt(i) == ']' && !st.isEmpty() && st.peek() == '[') { 50 | st.pop(); 51 | } else { 52 | st.push(s.charAt(i)); 53 | } 54 | } 55 | if (st.isEmpty()) { 56 | return true; 57 | } 58 | return false; 59 | } 60 | 61 | public static void main(String[] args) { 62 | ValidParenthesis vp = new ValidParenthesis(); 63 | System.out.println(vp.isValid("()[]{}")); 64 | 65 | int res = 10&7; 66 | int d =10; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Strings/AllStringPermutation.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * All String Permutation.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Strings; 9 | 10 | public class AllStringPermutation { 11 | /*Below are the permutations of string ABC. 12 | ABC ACB BAC BCA CBA CAB*/ 13 | 14 | 15 | /** 16 | * permutation function 17 | * 18 | * @param str string to calculate permutation for 19 | * @param l starting index 20 | * @param r end index 21 | */ 22 | private void permute(String str, int l, int r) { 23 | if (l == r) 24 | System.out.print(str + " "); 25 | else { 26 | for (int i = l; i <= r; i++) { 27 | str = swap(str, l, i); 28 | permute(str, l + 1, r); 29 | str = swap(str, l, i); 30 | } 31 | } 32 | } 33 | 34 | /** 35 | * Swap Characters at position 36 | * 37 | * @param a string value 38 | * @param i position 1 39 | * @param j position 2 40 | * @return swapped string 41 | */ 42 | public String swap(String a, int i, int j) { 43 | char temp; 44 | char[] charArray = a.toCharArray(); 45 | temp = charArray[i]; 46 | charArray[i] = charArray[j]; 47 | charArray[j] = temp; 48 | return String.valueOf(charArray); 49 | } 50 | 51 | public static void main(String[] args) { 52 | String str = "ABC"; 53 | int n = str.length(); 54 | AllStringPermutation permutation = new AllStringPermutation(); 55 | permutation.permute(str, 0, n - 1); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Strings/DetectCapital.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Detect Capital.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Strings; 9 | /*Given a word, you need to judge whether the usage of capitals in it is right or not. 10 | 11 | We define the usage of capitals in a word to be right when one of the following cases holds: 12 | 13 | All letters in this word are capitals, like "USA". 14 | All letters in this word are not capitals, like "leetcode". 15 | Only the first letter in this word is capital, like "Google". 16 | Otherwise, we define that this word doesnt use capitals in a right way 17 | 18 | Example 1: 19 | Input: "USA" 20 | Output: True 21 | 22 | Example 2: 23 | Input: "FlaG" 24 | Output: False 25 | 26 | 27 | Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.*/ 28 | 29 | /*LeetCode 520*/ 30 | 31 | public class DetectCapital { 32 | public boolean detectCapitalUse(String word) { 33 | int small = 0; 34 | int capital = 0; 35 | 36 | for (int i = 0; i < word.length(); i++) { 37 | char ch = word.charAt(i); 38 | if (ch >= 'A' && ch <= 'Z') { 39 | //Ascii A-Z 40 | capital++; 41 | } else { 42 | small++; 43 | } 44 | } 45 | return capital == word.length() || small == word.length() 46 | || (capital == 1 && word.charAt(0) >= 'A' && word.charAt(0) <= 'Z'); 47 | } 48 | 49 | public static void main(String[] args) { 50 | DetectCapital dc = new DetectCapital(); 51 | System.out.println(dc.detectCapitalUse("FLAG")); 52 | } 53 | } -------------------------------------------------------------------------------- /src/main/java/javaclasses/Strings/DuplicateCharacter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Duplicate Character.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Strings; 9 | 10 | 11 | import java.util.HashSet; 12 | import java.util.Set; 13 | 14 | /*Given an input string, Write a java code to find duplicate characters in a String. In this tutorial, 15 | I am going to explain multiple approaches to find duplicate characters in a string. 16 | 17 | For example : 18 | 19 | Input string: “Java” 20 | Duplicate character : a 21 | 22 | Input string: “programming” 23 | Duplicate character : m,g,r*/ 24 | 25 | 26 | /*In this example, we are going to use set data structure. A set doesn’t contain duplicate element. 27 | Using this property we can easily find duplicate characters.*/ 28 | 29 | //print duplicate characters of a string using set 30 | public class DuplicateCharacter { 31 | 32 | public static void printDuplicateUsingSet(String str) { 33 | 34 | //Declare set 35 | Set set = new HashSet<>(); 36 | 37 | //Traverse a string 38 | for (int i = 0; i < str.length(); i++) { 39 | Character ch = str.charAt(i); 40 | 41 | //If character is already present in a set 42 | if (set.contains(ch)) { 43 | System.out.println(ch); 44 | } else { 45 | set.add(ch); 46 | } 47 | } 48 | } 49 | 50 | public static void main(String[] args) { 51 | 52 | String str = "java"; 53 | //Method call 54 | printDuplicateUsingSet(str); 55 | } 56 | } -------------------------------------------------------------------------------- /src/main/java/javaclasses/Strings/ImplementStrStr.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Implement Str Str.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Strings; 9 | 10 | public class ImplementStrStr { 11 | //Leetcode 28 12 | /*Implement strStr(). 13 | 14 | Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 15 | 16 | Clarification: 17 | 18 | What should we return when needle is an empty string? This is a great question to ask during an interview. 19 | 20 | For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to 21 | C's strstr() and Java's indexOf(). 22 | 23 | 24 | Example 1: 25 | 26 | Input: haystack = "hello", needle = "ll" 27 | Output: 2 28 | Example 2: 29 | 30 | Input: haystack = "aaaaa", needle = "bba" 31 | Output: -1 32 | Example 3: 33 | 34 | Input: haystack = "", needle = "" 35 | Output: 0*/ 36 | 37 | public int strStr(final String hayStack, final String needle) { 38 | if (needle.isEmpty() || hayStack.isEmpty()) { 39 | return -1; 40 | } 41 | int lenA = hayStack.length(); 42 | int lenB = needle.length(); 43 | if (lenB > lenA) return -1; 44 | int index = 0; 45 | int count = 0; 46 | 47 | for (int i = 0; i < lenA; i++) { 48 | int current = i; 49 | count = 0; 50 | for (int j = 0; j < lenB; j++) { 51 | if (current < lenA && hayStack.charAt(current) == needle.charAt(j)) { 52 | ++current; 53 | ++count; 54 | if (j == 0) index = i; 55 | } 56 | if (count == lenB) { 57 | return index; 58 | } 59 | } 60 | } 61 | 62 | return -1; 63 | } 64 | 65 | public static void main(String[] args) { 66 | ImplementStrStr strStr = new ImplementStrStr(); 67 | System.out.println(strStr.strStr("bbaabbbbbaabbaabbbbbbabbbabaabbbabbabbbbababbbabbabaaababbbaabaaaba", 68 | "babaaa")); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Strings/IsomorphicString.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Isomorphic String.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Strings; 9 | 10 | import java.util.HashMap; 11 | 12 | public class IsomorphicString { 13 | //Leetcode 205 14 | /*Given two strings s and t, determine if they are isomorphic. 15 | 16 | Two strings s and t are isomorphic if the characters in s can be replaced to get t. 17 | 18 | All occurrences of a character must be replaced with another character while preserving the order of characters. 19 | No two characters may map to the same character, but a character may map to itself. 20 | 21 | Example 1: 22 | Input: s = "egg", t = "add" 23 | Output: true 24 | 25 | Example 2: 26 | Input: s = "foo", t = "bar" 27 | Output: false 28 | 29 | Example 3: 30 | Input: s = "paper", t = "title" 31 | Output: true 32 | */ 33 | public boolean isIsomorphic(String s, String t) { 34 | HashMap map = new HashMap<>(); 35 | if (s.length() != t.length()) { 36 | return false; 37 | } 38 | StringBuilder builder = new StringBuilder(); 39 | for (int i = 0; i < s.length(); i++) { 40 | if (map.containsKey(s.charAt(i))) { 41 | char ch = map.get(s.charAt(i)); 42 | builder.append(ch); 43 | } else if (map.containsValue(t.charAt(i))) { 44 | return false; 45 | } else { 46 | map.put(s.charAt(i), t.charAt(i)); 47 | builder.append(t.charAt(i)); 48 | } 49 | } 50 | if (builder.toString().equals(t)) { 51 | return true; 52 | } 53 | return false; 54 | } 55 | 56 | public static void main(String[] args) { 57 | IsomorphicString string = new IsomorphicString(); 58 | System.out.println(string.isIsomorphic("paper", "title")); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Strings/PartitionLabels.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Partition Labels.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Strings; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | public class PartitionLabels { 14 | //Leetcode 763 15 | /*You are given a string s. We want to partition the string into as many parts as possible so that each 16 | letter appears in at most one part. 17 | 18 | Return a list of integers representing the size of these parts. 19 | 20 | Example 1: 21 | Input: s = "ababcbacadefegdehijhklij" 22 | Output: [9,7,8] 23 | Explanation: 24 | The partition is "ababcbaca", "defegde", "hijhklij". 25 | This is a partition so that each letter appears in at most one part. 26 | A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts. 27 | 28 | Example 2: 29 | Input: s = "eccbbbbdec" 30 | Output: [10]*/ 31 | 32 | public List partitionLabels(String s) { 33 | List result = new ArrayList<>(); 34 | int[] last = new int[26]; 35 | for (int i = 0; i < s.length(); i++) { 36 | last[s.charAt(i) - 'a'] = i; 37 | } 38 | int j = 0; 39 | int anchor = 0; 40 | for (int i = 0; i < s.length(); i++) { 41 | j = Math.max(j, last[s.charAt(i) - 'a']); 42 | if (i == j) { 43 | result.add(i - anchor + 1); 44 | anchor = i + 1; 45 | } 46 | } 47 | return result; 48 | } 49 | 50 | public static void main(String[] args) { 51 | PartitionLabels labels = new PartitionLabels(); 52 | System.out.println(labels.partitionLabels("eccbbbbdec")); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Strings/RansomNote.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Ransom Note.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Strings; 9 | 10 | /*Given an arbitrary ransom note string and another string containing letters from all the magazines, 11 | write a function that will return true if the ransom note can be constructed from the magazines ; 12 | otherwise, it will return false. 13 | 14 | Each letter in the magazine string can only be used once in your ransom note. 15 | 16 | Example 1: 17 | Input: ransomNote = "a", magazine = "b" 18 | Output: false 19 | 20 | Example 2: 21 | Input: ransomNote = "aa", magazine = "ab" 22 | Output: false 23 | 24 | Example 3: 25 | Input: ransomNote = "aa", magazine = "aab" 26 | Output: true 27 | 28 | 29 | Constraints: 30 | 31 | You may assume that both strings contain only lowercase letters. 32 | */ 33 | 34 | /*LeetCode 383*/ 35 | 36 | public class RansomNote { 37 | public static boolean canConstruct(String ransomNote, String magazine) { 38 | int[] arr = new int[26]; 39 | int mgLne = magazine.length(); 40 | int ranLen = ransomNote.length(); 41 | 42 | for (int i = 0; i < mgLne; i++) { 43 | arr[magazine.charAt(i) - 97]++; //a ascii code is 97 44 | } 45 | 46 | //if value is less than zero, it means 47 | //character is not available for ransom note 48 | for (int i = 0; i < ranLen; i++) { 49 | if (--arr[ransomNote.charAt(i) - 97] < 0) 50 | return false; 51 | } 52 | return true; 53 | } 54 | 55 | public static void main(String[] args) { 56 | System.out.println(canConstruct("aa", "aab")); 57 | System.out.println(canConstruct("aa", "ab")); 58 | System.out.println(canConstruct("rafsan", "ahmadrafsen")); 59 | System.out.println(canConstruct("bbcd", "aabbbbc")); 60 | } 61 | } -------------------------------------------------------------------------------- /src/main/java/javaclasses/Strings/RemoveAdjacentDuplicate.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Remove Adjacent Duplicate.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Strings; 9 | 10 | import java.util.Stack; 11 | 12 | /*LeetCode - 1047*/ 13 | /*Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, 14 | and removing them. 15 | 16 | We repeatedly make duplicate removals on S until we no longer can. 17 | 18 | Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique. 19 | 20 | Example 1: 21 | 22 | Input: "abbaca" 23 | Output: "ca" 24 | Explanation: 25 | For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only 26 | possible move. 27 | The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".*/ 28 | 29 | public class RemoveAdjacentDuplicate { 30 | 31 | public static String removeAdjacentDuplicate(String str) { 32 | Stack st = new Stack<>(); 33 | StringBuilder sb = new StringBuilder(); 34 | 35 | for (int i = 0; i < str.length(); i++) { 36 | if (!st.isEmpty() && st.peek() == str.charAt(i)) { 37 | st.pop(); 38 | } else { 39 | st.push(str.charAt(i)); 40 | } 41 | } 42 | 43 | for (Character ch : st) { 44 | sb.append(ch); 45 | } 46 | 47 | return sb.toString(); 48 | } 49 | 50 | public static void main(String[] args) { 51 | String str = "caaabbc"; 52 | String result = removeAdjacentDuplicate(str); 53 | System.out.println(result); 54 | } 55 | } 56 | 57 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Strings/ReverseEachWords.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Reverse Each Words.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Strings; 9 | 10 | /*Write a java program to reverse each words of a string. 11 | Suppose, If an input string is Java Programming then the output string should be avaJ gnimmargorP.*/ 12 | 13 | /*We split the input string into words using split() method. 14 | Then we reverse each individual word and append to a final string. Finally, we print the output. 15 | */ 16 | 17 | 18 | public class ReverseEachWords { 19 | 20 | public static void main(String[] args) { 21 | 22 | String str = "Java Programming"; 23 | 24 | //Create an array of words 25 | //[Java,Programming] 26 | String[] words = str.split("\\s+"); 27 | StringBuilder revString = new StringBuilder(); 28 | 29 | for (int i = 0; i < words.length; i++) { 30 | String word = words[i]; 31 | StringBuilder revWord = new StringBuilder(); 32 | 33 | for (int j = word.length() - 1; j >= 0; j--) { 34 | revWord.append(word.charAt(j)); 35 | } 36 | 37 | revString.append(revWord).append(" "); 38 | } 39 | 40 | System.out.println(revString); 41 | } 42 | } -------------------------------------------------------------------------------- /src/main/java/javaclasses/Strings/ReverseString.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Reverse String.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Strings; 9 | 10 | /*Write a java program to reverse a string. In this tutorial, I am going to explain how to 11 | write a java code which reverse an input string using recursion & stack. 12 | 13 | For example : 14 | 15 | Input String: Object 16 | Output String: tcejbO*/ 17 | 18 | 19 | import java.util.Stack; 20 | 21 | public class ReverseString { 22 | 23 | //Reverse a String using Recursion 24 | private static String reverseUsingRecursion(String str) { 25 | 26 | //Terminating condition 27 | if (str == null || str.length() <= 1) { 28 | return str; 29 | } 30 | 31 | //Recursive function call 32 | String res = str.substring(1); 33 | return reverseUsingRecursion(res) + str.charAt(0); 34 | } 35 | 36 | //Reverse a String using Stack 37 | private static String reverseUsingStack(String str) { 38 | //Declare a stack 39 | Stack stack = new Stack<>(); 40 | 41 | /** 42 | * Traverse a string and push each character 43 | * of a string in a stack. 44 | */ 45 | for (int i = 0; i < str.length(); i++) { 46 | stack.push(str.charAt(i)); 47 | } 48 | 49 | StringBuilder result = new StringBuilder(); 50 | //When stack is not empty, pop each character 51 | while (!stack.empty()) { 52 | result.append(stack.pop()); 53 | } 54 | return result.toString(); 55 | } 56 | 57 | public static void main(String[] args) { 58 | 59 | String str = "Object"; 60 | System.out.println(reverseUsingRecursion(str)); 61 | System.out.println(reverseUsingStack(str)); 62 | 63 | } 64 | } 65 | 66 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Strings/ReverseWordsWithoutSpecialCharacters.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Reverse Words Without Special Characters.java 4 | * * Created by Rafsan Ahmad on 1/6/22, 9:45 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.Strings; 10 | 11 | public class ReverseWordsWithoutSpecialCharacters { 12 | 13 | /*Given a string, that contains a special character together with alphabets (‘a’ to ‘z’ and ‘A’ to ‘Z’), 14 | reverse the string in a way that special characters are not affected. 15 | 16 | Examples: 17 | Input: str = "a,b$c" 18 | Output: str = "c,b$a" 19 | Note that $ and , are not moved anywhere. 20 | Only subsequence "abc" is reversed 21 | 22 | Input: str = "Ab,c,de!$" 23 | Output: str = "ed,c,bA!$"*/ 24 | 25 | public static String reverse(String str) { 26 | char[] chArray = str.toCharArray(); 27 | // Initialize left and right pointers 28 | int r = chArray.length - 1, l = 0; 29 | 30 | // Traverse string from both ends until 31 | // 'l' and 'r' 32 | while (l < r) { 33 | // Ignore special characters 34 | if (!Character.isAlphabetic(chArray[l])) 35 | l++; 36 | else if (!Character.isAlphabetic(chArray[r])) 37 | r--; 38 | 39 | // Both str[l] and str[r] are not spacial 40 | else { 41 | char tmp = chArray[l]; 42 | chArray[l] = chArray[r]; 43 | chArray[r] = tmp; 44 | l++; 45 | r--; 46 | } 47 | } 48 | return String.valueOf(chArray); 49 | } 50 | 51 | public static void main(String[] args) { 52 | /*Input string: a!!!b.c.d,e'f,ghi 53 | Output string: i!!!h.g.f,e'd,cba*/ 54 | String str = "a!!!b.c.d,e'f,ghi"; 55 | String res = reverse(str); 56 | System.out.println("Output string: " + res); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Strings/UniqueCharacter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Unique Character.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Strings; 9 | 10 | /*Given a string, find the first non-repeating character in it and return its index. 11 | If it doesn't exist, return -1. 12 | 13 | Examples: 14 | 15 | s = "leetcode" 16 | return 0. 17 | Explanation: First Non repeating character is l 18 | 19 | s = "loveleetcode" 20 | return 2. 21 | Explanation: First Non repeating character is v 22 | 23 | Note: You may assume the string contains only lowercase English letters.*/ 24 | 25 | import java.util.HashMap; 26 | 27 | public class UniqueCharacter { 28 | 29 | public static int findUniqueCharacter(String str) { 30 | 31 | HashMap charCountMap = new HashMap<>(); 32 | /*Traverse a string and create a map of 33 | character and its count*/ 34 | for (int i = 0; i < str.length(); i++) { 35 | char ch = str.charAt(i); 36 | charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1); 37 | } 38 | 39 | /*Now we know each character and its count present in a string 40 | Next step is to simply traverse a string & check the character whose count is 1*/ 41 | 42 | for (int j = 0; j < str.length(); j++) { 43 | char ch = str.charAt(j); 44 | int count = charCountMap.get(ch); 45 | if (count == 1) { 46 | return j; 47 | } 48 | } 49 | return -1; 50 | } 51 | 52 | public static void main(String[] args) { 53 | System.out.println(findUniqueCharacter("character")); 54 | System.out.println(findUniqueCharacter("loveleetcode")); 55 | } 56 | 57 | } -------------------------------------------------------------------------------- /src/main/java/javaclasses/Tree/Check_If_TreeBalanced.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Check If A Binary Tree Is Balanced.java 4 | * * Created by Rafsan Ahmad on 12/3/22, 10:57 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.Tree; 10 | 11 | public class Check_If_TreeBalanced { 12 | /*A height balanced binary tree is a binary tree in which the height of the left subtree and right subtree of any node 13 | does not differ by more than 1 and both the left and right subtree are also height balanced. 14 | 15 | Steps: 16 | For each node make two recursion calls – one for left subtree and the other for the right subtree. 17 | Based on the heights returned from the recursion calls, decide if the subtree whose root is the current node is 18 | height-balanced or not. 19 | If it is balanced then return the height of that subtree. Otherwise, return -1 to denote that the subtree is not 20 | height-balanced. 21 | */ 22 | 23 | /*Time Complexity: O(n) 24 | Because we are only one dfs call and utilizing the height returned from that to determine the height balance, 25 | it is performing the task in linear time. 26 | Auxiliary Space: O(n) 27 | */ 28 | public static int isBalanced(Node root) { 29 | if (root == null) 30 | return 0; 31 | int lh = isBalanced(root.left); 32 | if (lh == -1) 33 | return -1; 34 | int rh = isBalanced(root.right); 35 | if (rh == -1) 36 | return -1; 37 | 38 | if (Math.abs(lh - rh) > 1) 39 | return -1; 40 | else 41 | return Math.max(lh, rh) + 1; 42 | } 43 | 44 | public static void main(String[] args) { 45 | Node root = new Node(10); 46 | root.left = new Node(5); 47 | root.right = new Node(30); 48 | root.right.left = new Node(15); 49 | root.right.right = new Node(20); 50 | 51 | if (isBalanced(root) > 0) 52 | System.out.print("Balanced"); 53 | else 54 | System.out.print("Not Balanced"); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Tree/IsTreeBST.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Is Tree Binary Search Tree.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Tree; 9 | 10 | public class IsTreeBST { 11 | /*A binary search tree (BST) is a node based binary tree data structure which has the following properties. 12 | • The left subtree of a node contains only nodes with keys less than the node’s key. 13 | • The right subtree of a node contains only nodes with keys greater than the node’s key. 14 | • Both the left and right subtrees must also be binary search trees. 15 | From the above properties it naturally follows that: 16 | • Each node (item in the tree) has a distinct key.*/ 17 | 18 | 19 | // Returns true if given tree is BST. 20 | static boolean isBST(Node root, Node l, Node r) { 21 | // Base condition 22 | if (root == null) 23 | return true; 24 | 25 | // if left node exist then check it has 26 | // correct data or not i.e. left node's data 27 | // should be less than root's data 28 | if (l != null && root.data <= l.data) 29 | return false; 30 | 31 | // if right node exist then check it has 32 | // correct data or not i.e. right node's data 33 | // should be greater than root's data 34 | if (r != null && root.data >= r.data) 35 | return false; 36 | 37 | // check recursively for every node. 38 | return isBST(root.left, l, root) && 39 | isBST(root.right, root, r); 40 | } 41 | 42 | // Driver code 43 | public static void main(String args[]) { 44 | Node root = new Node(4); 45 | root.left = new Node(2); 46 | root.right = new Node(5); 47 | root.left.left = new Node(1); 48 | root.left.right = new Node(3); 49 | 50 | if (isBST(root, null, null)) 51 | System.out.print("Tree Is BST"); 52 | else 53 | System.out.print("Tree is Not a BST"); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Tree/KthSmallestElementInBst.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Kth Smallest Element In Binary Search Tree.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Tree; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | public class KthSmallestElementInBst { 14 | //Leetcode 230 15 | //res/kthtree1.jpeg 16 | /*Given the root of a binary search tree, and an integer k, return the kth (1-indexed) smallest 17 | element in the tree. 18 | 19 | 20 | Example 1: 21 | 3 22 | / \ 23 | 1 4 24 | \ 25 | 2 26 | Input: root = [3,1,4,null,2], k = 1 27 | Output: 1 28 | 29 | Example 2: 30 | Input: root = [5,3,6,2,4,null,null,1], k = 3 31 | Output: 3*/ 32 | 33 | public int kthSmallest(TreeNode root, int k) { 34 | if (root == null || k < 1) { 35 | return 0; 36 | } 37 | List nodes = new ArrayList<>(); 38 | InOrderTraversal(root, nodes); 39 | return nodes.get(k - 1); 40 | } 41 | 42 | //Recursive In-order traversal - gives Ascending order list 43 | public void InOrderTraversal(TreeNode node, List list) { 44 | if (node == null) { 45 | return; 46 | } 47 | InOrderTraversal(node.left, list); 48 | list.add(node.val); 49 | InOrderTraversal(node.right, list); 50 | } 51 | 52 | public static void main(String[] args) { 53 | KthSmallestElementInBst bst = new KthSmallestElementInBst(); 54 | TreeNode root = new TreeNode(3); 55 | root.left = new TreeNode(1); 56 | root.right = new TreeNode(4); 57 | root.left.right = new TreeNode(2); 58 | 59 | System.out.println(bst.kthSmallest(root, 1)); 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Tree/MaxHeightOfTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Max Height Of Tree.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Tree; 9 | 10 | // A binary tree node 11 | class Node { 12 | int data; 13 | Node left, right; 14 | 15 | Node(int item) { 16 | data = item; 17 | left = right = null; 18 | } 19 | } 20 | 21 | public class MaxHeightOfTree { 22 | 23 | // Java program to find height of tree 24 | Node root; 25 | 26 | /* Compute the "maxDepth" of a tree -- the number of 27 | nodes along the longest path from the root node 28 | down to the farthest leaf node.*/ 29 | int maxDepth(Node node) { 30 | if (node == null) 31 | return 0; 32 | else { 33 | /* compute the depth of each subtree */ 34 | int lDepth = maxDepth(node.left); 35 | int rDepth = maxDepth(node.right); 36 | 37 | /* use the larger one */ 38 | return Math.max(lDepth, rDepth) + 1; 39 | } 40 | } 41 | 42 | /* Driver program to test above functions */ 43 | public static void main(String[] args) { 44 | MaxHeightOfTree tree = new MaxHeightOfTree(); 45 | 46 | tree.root = new Node(1); 47 | tree.root.left = new Node(2); 48 | tree.root.right = new Node(3); 49 | tree.root.left.left = new Node(4); 50 | tree.root.left.right = new Node(5); 51 | 52 | System.out.println("Height of tree is : " + 53 | tree.maxDepth(tree.root)); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Tree/PathSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Binary tree Path Sum.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Tree; 9 | 10 | public class PathSum { 11 | //Leetcode 112 12 | /* 13 | * Given the root of a binary tree and an integer targetSum, return true 14 | * if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. 15 | A leaf is a node with no children. 16 | 17 | Example 1: 18 | Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 19 | Output: true 20 | 21 | Example 2: 22 | Input: root = [1,2,3], targetSum = 5 23 | Output: false 24 | 25 | Example 3: 26 | Input: root = [1,2], targetSum = 0 27 | Output: false 28 | */ 29 | public boolean hasPathSum(TreeNode root, int targetSum) { 30 | if (root == null) { 31 | return false; 32 | } 33 | if (root.left == null && root.right == null && targetSum - root.val == 0) { 34 | return true; 35 | } else { 36 | return hasPathSum(root.left, targetSum - root.val) || 37 | hasPathSum(root.right, targetSum - root.val); 38 | } 39 | } 40 | 41 | public static void main(String[] args) { 42 | PathSum sum = new PathSum(); 43 | TreeNode root = new TreeNode(1); 44 | root.left = new TreeNode(2); 45 | root.right = new TreeNode(3); 46 | System.out.println(sum.hasPathSum(root, 5)); 47 | System.out.println(sum.hasPathSum(root, 4)); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Tree/TreeNode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Tree; 9 | 10 | public class TreeNode { 11 | public int val; 12 | public TreeNode left; 13 | public TreeNode right; 14 | 15 | TreeNode() { 16 | } 17 | 18 | public TreeNode(int val) { 19 | this.val = val; 20 | } 21 | 22 | TreeNode(int val, TreeNode left, TreeNode right) { 23 | this.val = val; 24 | this.left = left; 25 | this.right = right; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Tree/VerifyPreOrderSerialization.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Verify Pre Order Serialization.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Tree; 9 | 10 | public class VerifyPreOrderSerialization { 11 | //Leetcode 331 12 | //res/pre-tree.jpeg 13 | /*One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, 14 | we record the node's value. If it is a null node, we record using a sentinel value such as '#'. 15 | 16 | For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", 17 | where '#' represents a null node. 18 | 19 | Given a string of comma-separated values preorder, return true if it is a correct preorder traversal 20 | serialization of a binary tree. 21 | 22 | It is guaranteed that each comma-separated value in the string must be either an integer or a character 23 | '#' representing null pointer. 24 | 25 | You may assume that the input format is always valid. 26 | 27 | For example, it could never contain two consecutive commas, such as "1,,3". 28 | Note: You are not allowed to reconstruct the tree. 29 | 30 | Example 1: 31 | Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" 32 | Output: true 33 | 34 | Example 2: 35 | Input: preorder = "1,#" 36 | Output: false 37 | 38 | Example 3: 39 | Input: preorder = "9,#,#,1" 40 | Output: false*/ 41 | 42 | public boolean isValidSerialization(String preorder) { 43 | String[] nodes = preorder.split(","); 44 | int nodeCount = 1; 45 | for (String node : nodes) { 46 | nodeCount--; 47 | if (nodeCount < 0) { 48 | return false; 49 | } 50 | if (!node.equals("#")) { 51 | nodeCount += 2; 52 | } 53 | } 54 | return nodeCount == 0; 55 | } 56 | 57 | public static void main(String[] args) { 58 | VerifyPreOrderSerialization verify = new VerifyPreOrderSerialization(); 59 | System.out.println(verify.isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#")); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/TwoPointer/PairWithGivenDifference.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Pair With Given Difference.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:50 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.TwoPointer; 9 | 10 | import java.util.Arrays; 11 | 12 | public class PairWithGivenDifference { 13 | //https://www.interviewbit.com/problems/pair-with-given-difference/ 14 | /*Given an one-dimensional unsorted array A containing N integers. 15 | 16 | You are also given an integer B, find if there exists a pair of elements in the array whose difference is B. 17 | Return 1 if any such pair exists else return 0. 18 | 19 | Input Format 20 | First argument is an integer array A of size N. 21 | Second argument is an integer B. 22 | 23 | Output Format 24 | Return 1 if any such pair exists else return 0. 25 | 26 | Example Input 27 | Input 1: 28 | A = [5, 10, 3, 2, 50, 80] 29 | B = 78 30 | 31 | Input 2: 32 | A = [-10, 20] 33 | B = 30 34 | 35 | Example Output 36 | Output 1: 37 | 1 38 | 39 | Output 2: 40 | 1 41 | 42 | Example Explanation 43 | Explanation 1: 44 | 45 | Pair (80, 2) gives a difference of 78. 46 | Explanation 2: 47 | 48 | Pair (20, -10) gives a difference of 30 i.e 20 - (-10) => 20 + 10 => 30*/ 49 | 50 | public int solve(int[] A, int B) { 51 | int len = A.length - 1; 52 | int left = 0; 53 | int right = 1; 54 | Arrays.sort(A); 55 | 56 | while (left <= len && right <= len) { 57 | int diff = A[right] - A[left]; 58 | if (left != right && diff == B) { 59 | return 1; 60 | } else if (diff < B) right++; 61 | else left++; 62 | } 63 | 64 | return 0; 65 | } 66 | 67 | public static void main(String[] args) { 68 | PairWithGivenDifference difference = new PairWithGivenDifference(); 69 | int[] arr = {5, 10, 3, 2, 50, 80}; 70 | System.out.println(difference.solve(arr, 40)); 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/TwoPointer/SortArrayOfSquares.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Sort Array Of Squares.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:50 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.TwoPointer; 9 | 10 | import java.util.Arrays; 11 | 12 | public class SortArrayOfSquares { 13 | //https://www.interviewbit.com/problems/sort-array-with-squares/ 14 | //Leetcode 977 15 | /*Problem Description 16 | Given a sorted array A containing N integers both positive and negative. 17 | 18 | You need to create another array containing the squares of all the elements in A and return it in non-decreasing 19 | order. 20 | 21 | Try to this in O(N) time. 22 | 23 | Input Format 24 | First and only argument is an integer array A. 25 | 26 | Output Format 27 | Return a integer array as described in the problem above. 28 | 29 | Example Input 30 | Input 1: 31 | A = [-6, -3, -1, 2, 4, 5] 32 | 33 | Input 2: 34 | A = [-5, -4, -2, 0, 1] 35 | 36 | Example Output 37 | Output 1: 38 | [1, 4, 9, 16, 25, 36] 39 | 40 | Output 2: 41 | [0, 1, 4, 16, 25]*/ 42 | //Two - pointer 43 | public int[] sortArraySquare(int[] A) { 44 | int[] answer = new int[A.length]; 45 | int i = 0; 46 | int j = A.length - 1; 47 | int k = A.length - 1; 48 | while (i <= j) { 49 | if (Math.abs(A[i]) > Math.abs(A[j])) { 50 | answer[k--] = A[i] * A[i]; 51 | i++; 52 | } else { 53 | answer[k--] = A[j] * A[j]; 54 | j--; 55 | } 56 | } 57 | return answer; 58 | } 59 | 60 | public static void main(String[] args) { 61 | int[] arr = {-6, -3, -1, 2, 4, 5}; 62 | System.out.println(Arrays.toString(new SortArrayOfSquares().sortArraySquare(arr))); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/TwoPointer/SubarraySizeKthreshold.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold.java 4 | * * Created by Rafsan Ahmad on 4/7/22, 1:20 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.TwoPointer; 10 | 11 | public class SubarraySizeKthreshold { 12 | //Leetcode 1343 13 | /*Given an array of integers arr and two integers k and threshold, return the number of sub-arrays of size k and 14 | average greater than or equal to threshold. 15 | 16 | Example 1: 17 | Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4 18 | Output: 3 19 | Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of 20 | size 3 have averages less than 4 (the threshold). 21 | 22 | Example 2: 23 | Input: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5 24 | Output: 6 25 | Explanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers. 26 | */ 27 | 28 | public int numOfSubarrays(int[] arr, int k, int threshold) { 29 | int start = 0; 30 | int sum = 0; 31 | int len = arr.length; 32 | int result = 0; 33 | 34 | for (int end = 0; end < len; end++) { 35 | sum = sum + arr[end]; 36 | 37 | if (end >= k - 1) { 38 | if (start > 0) sum = sum - arr[start - 1]; 39 | if (sum / k >= threshold) { 40 | result++; 41 | } 42 | start++; 43 | } 44 | } 45 | return result; 46 | } 47 | 48 | public static void main(String[] args) { 49 | SubarraySizeKthreshold subarraySizeKthreshold = new SubarraySizeKthreshold(); 50 | int[] arr2 = {11, 13, 17, 23, 29, 31, 7, 5, 2, 3}; 51 | System.out.println(subarraySizeKthreshold.numOfSubarrays(arr2, 3, 5)); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/TwoPointer/ThreeSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Three Sum.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:50 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.TwoPointer; 9 | 10 | import java.util.ArrayList; 11 | import java.util.Arrays; 12 | import java.util.List; 13 | 14 | //Leetcode 15 15 | /* 16 | * Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, 17 | * and nums[i] + nums[j] + nums[k] == 0. 18 | 19 | Notice that the solution set must not contain duplicate triplets. 20 | 21 | Example 1: 22 | Input: nums = [-1,0,1,2,-1,-4] 23 | Output: [[-1,-1,2],[-1,0,1]] 24 | 25 | Example 2: 26 | Input: nums = [] 27 | Output: [] 28 | */ 29 | public class ThreeSum { 30 | //use two pointer at start and end (Complexity = 0(n2)) 31 | public List> threeSum(int[] nums) { 32 | List> result = new ArrayList<>(); 33 | Arrays.sort(nums); 34 | 35 | for (int i = 0; i < nums.length; i++) { 36 | int start = i + 1; 37 | int end = nums.length - 1; 38 | 39 | //discard duplicate 40 | if (i > 0 && nums[i] == nums[i - 1]) { 41 | continue; 42 | } 43 | 44 | while (start < end) { 45 | //discard duplicate 46 | if (end < nums.length - 1 && nums[end] == nums[end + 1]) { 47 | end--; 48 | continue; 49 | } 50 | if (nums[i] + nums[start] + nums[end] == 0) { 51 | List val = Arrays.asList(nums[i], nums[start], nums[end]); 52 | result.add(val); 53 | start++; 54 | end--; 55 | } else if (nums[i] + nums[start] + nums[end] < 0) { 56 | start++; 57 | } else { 58 | end--; 59 | } 60 | } 61 | } 62 | return result; 63 | } 64 | 65 | public static void main(String[] args) { 66 | ThreeSum sum = new ThreeSum(); 67 | int[] nums = {-1, 0, 1, 2, -1, -4}; 68 | System.out.println(sum.threeSum(nums)); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/TwoPointer/ThreeSumClosest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Three Sum Closest.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:50 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.TwoPointer; 9 | 10 | import java.util.Arrays; 11 | 12 | //Leetcode 16 13 | /* 14 | Given an array nums of n integers and an integer target, 15 | find three integers in nums such that the sum is closest to target. Return the sum of the three integers. 16 | You may assume that each input would have exactly one solution. 17 | 18 | Example 1: 19 | 20 | Input: nums = [-1,2,1,-4], target = 1 21 | Output: 2 22 | Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 23 | * */ 24 | public class ThreeSumClosest { 25 | public int threeSumClosest(int[] nums, int target) { 26 | int diff = Integer.MAX_VALUE; 27 | int result = 0; 28 | Arrays.sort(nums); 29 | 30 | for (int i = 0; i < nums.length; i++) { 31 | int start = i + 1; 32 | int end = nums.length - 1; 33 | 34 | while (start < end && end > 0) { 35 | long sum = nums[i] + nums[start] + nums[end]; 36 | 37 | long d = Math.abs(target - sum); 38 | if (d < diff) { 39 | diff = (int) d; 40 | result = (int) sum; 41 | } 42 | if (nums[i] + nums[start] + nums[end] < target) { 43 | start++; 44 | } else { 45 | end--; 46 | } 47 | } 48 | } 49 | return result; 50 | } 51 | 52 | public static void main(String[] args) { 53 | int[] arr = {2147483647, -2147483648, -2147483648, 0, 1}; 54 | ThreeSumClosest closest = new ThreeSumClosest(); 55 | System.out.println(closest.threeSumClosest(arr, 0)); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Utility/BestTimeToBuyStock.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Best Time To Buy Stock.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Utility; 9 | 10 | public class BestTimeToBuyStock { 11 | //Leetcode 121 12 | /*You are given an array prices where prices[i] is the price of a given stock on the ith day. 13 | 14 | You want to maximize your profit by choosing a single day to buy one stock and choosing a different 15 | day in the future to sell that stock. 16 | 17 | Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 18 | 19 | Example 1: 20 | Input: prices = [7,1,5,3,6,4] 21 | Output: 5 22 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 23 | Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. 24 | Example 2: 25 | 26 | Input: prices = [7,6,4,3,1] 27 | Output: 0 28 | Explanation: In this case, no transactions are done and the max profit = 0.*/ 29 | 30 | public int maxProfit(int[] prices) { 31 | int max = 0; 32 | int min = Integer.MAX_VALUE; 33 | for (int i = 0; i < prices.length; i++) { 34 | if (prices[i] < min) { 35 | min = prices[i]; 36 | } else { 37 | max = Math.max(max, prices[i] - min); 38 | } 39 | } 40 | 41 | return max; 42 | } 43 | 44 | public static void main(String[] args) { 45 | BestTimeToBuyStock stock = new BestTimeToBuyStock(); 46 | int[] prices = {7, 1, 5, 3, 6, 4}; 47 | System.out.println(stock.maxProfit(prices)); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Utility/BigIntegerExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Big Integer Example.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Utility; 9 | 10 | import java.math.BigInteger; 11 | 12 | public class BigIntegerExample { 13 | //Calculate Long Factorials 14 | 15 | public BigInteger getFactorial(int A) { 16 | BigInteger fact = new BigInteger("1"); 17 | while (A > 0) { 18 | fact = fact.multiply(BigInteger.valueOf(A)); 19 | A--; 20 | } 21 | return fact; 22 | } 23 | 24 | public int getTrailingZeros(BigInteger num) { 25 | int result = 0; 26 | while (num.compareTo(BigInteger.ZERO) > 0) { 27 | if (num.mod(BigInteger.valueOf(10)).equals(BigInteger.ZERO)) { 28 | ++result; 29 | } else { 30 | break; 31 | } 32 | num = num.divide(BigInteger.valueOf(10)); 33 | } 34 | return result; 35 | } 36 | 37 | public static void main(String[] args) { 38 | BigIntegerExample example = new BigIntegerExample(); 39 | BigInteger factorial = example.getFactorial(100); 40 | System.out.println(factorial); 41 | System.out.println(example.getTrailingZeros(factorial)); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Utility/GridDistance.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Grid Distance.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Utility; 9 | 10 | import java.util.ArrayList; 11 | 12 | public class GridDistance { 13 | 14 | //Find retail location with distance less than K 15 | // 0 -> Empty location, 1 -> Already filled 16 | public int solution(int K, int[][] A) { 17 | int result = 0; 18 | //Store house location 19 | ArrayList houses = new ArrayList<>(); 20 | for (int i = 0; i < A.length; i++) { 21 | for (int j = 0; j < A[i].length; j++) { 22 | if (A[i][j] == 1) { 23 | houses.add(new int[]{i, j}); 24 | } 25 | } 26 | } 27 | 28 | //Search through 2d grid for possible retail location 29 | for (int i = 0; i < A.length; i++) { 30 | for (int j = 0; j < A[i].length; j++) { 31 | //Empty location found 32 | if (A[i][j] == 0) { 33 | boolean found = true; 34 | for (int m = 0; m < houses.size(); m++) { 35 | int[] location = houses.get(m); 36 | int distance = Math.abs(i - location[0]) + Math.abs(j - location[1]); 37 | if (distance > K) { 38 | found = false; 39 | break; 40 | } 41 | } 42 | if (found) { 43 | ++result; 44 | } 45 | } 46 | } 47 | } 48 | return result; 49 | } 50 | 51 | public static void main(String[] args) { 52 | GridDistance chain = new GridDistance(); 53 | int[] arr1 = {0, 1, 0}; 54 | int[] arr2 = {0, 0, 0}; 55 | int[] arr3 = {0, 0, 1}; 56 | int[][] grid = new int[][]{arr1, arr2, arr3}; 57 | System.out.println(chain.solution(5, grid)); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Utility/MobileKeyboard.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Mobile Keyboard.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Utility; 9 | 10 | public class MobileKeyboard { 11 | 12 | /* C -> Caps Lock toggle 13 | B -> Delete last Character 14 | */ 15 | //System.out.println(MobileKeyboard.mobileKeyboard("CrCellBax")) - Prints "Relax" 16 | public String mobileKeyboard(String S) { 17 | StringBuilder stringBuilder = new StringBuilder(""); 18 | boolean capsLockStatus = false; 19 | for (int i = 0; i < S.length(); i++) { 20 | char ch = S.charAt(i); 21 | if (ch == 'C' || ch == 'B') { 22 | switch (ch) { 23 | case 'C': 24 | capsLockStatus = !capsLockStatus; 25 | break; 26 | case 'B': 27 | if (stringBuilder.length() > 0) { 28 | stringBuilder.deleteCharAt(stringBuilder.length() - 1); 29 | } 30 | break; 31 | 32 | } 33 | continue; 34 | } 35 | if (capsLockStatus) { 36 | stringBuilder.append(Character.toUpperCase(ch)); 37 | } else { 38 | stringBuilder.append(Character.toLowerCase(ch)); 39 | } 40 | } 41 | return stringBuilder.toString(); 42 | } 43 | 44 | public static void main(String[] args) { 45 | MobileKeyboard keyboard = new MobileKeyboard(); 46 | System.out.println(keyboard.mobileKeyboard("CrCellBax")); 47 | } 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Utility/Sort2DArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Sort2DArray.java 4 | * * Created by Rafsan Ahmad on 2/27/22, 12:51 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.Utility; 10 | 11 | import java.util.Arrays; 12 | 13 | public class Sort2DArray { 14 | 15 | public void sortArray(int[][] array) { 16 | Arrays.sort(array, (o1, o2) -> { 17 | if (o2[1] == o1[1]) { 18 | return Integer.compare(o1[0], o2[0]); //Ascending 19 | } 20 | return Integer.compare(o2[1], o1[1]); //Descending 21 | }); 22 | } 23 | 24 | public void printArray(int[][] array) { 25 | for (int i = 0; i < array.length; i++) { 26 | for (int j = 0; j < array[i].length; j++) { 27 | System.out.print(array[i][j] + " "); 28 | } 29 | System.out.println(); 30 | } 31 | } 32 | 33 | public static void main(String[] args) { 34 | int[][] stations = {{10, 60}, {20, 30}, {30, 30}, {60, 40}}; 35 | Sort2DArray array = new Sort2DArray(); 36 | array.sortArray(stations); 37 | array.printArray(stations); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Utility/TestClass.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Solution.java 4 | * * Created by Rafsan Ahmad on 4/20/22, 7:22 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package javaclasses.Utility; 10 | 11 | public class TestClass { 12 | public void testFunc() { 13 | } 14 | 15 | public static void main(String[] args) { 16 | TestClass solution = new TestClass(); 17 | //solution.testFunc(); 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/java/javaclasses/Utility/ThreadSafeSingleton.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Thread Safe Singleton.java 3 | * * Created by Rafsan Ahmad on 10/25/21, 9:49 PM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Utility; 9 | 10 | public final class ThreadSafeSingleton { 11 | private static volatile ThreadSafeSingleton INSTANCE = null; 12 | 13 | private final long licenseNumber; 14 | 15 | public long getLicenseNumber() { 16 | return licenseNumber; 17 | } 18 | 19 | // by making the constructor private, we prevent instantiation 20 | private ThreadSafeSingleton() { 21 | this.licenseNumber = 1999; 22 | } 23 | 24 | public static ThreadSafeSingleton getInstance() { 25 | if (INSTANCE == null) { 26 | synchronized (ThreadSafeSingleton.class) { 27 | if (INSTANCE == null) { 28 | INSTANCE = new ThreadSafeSingleton(); 29 | } 30 | } 31 | } 32 | return INSTANCE; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Utility/TreeMapCustomComparatorByValue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * TreeMap Custom Comparator.java 4 | * * Created by Rafsan Ahmad on 2/25/24, 4:05 AM 5 | * * Copyright (c) 2024 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package javaclasses.Utility; 11 | 12 | import java.util.Comparator; 13 | import java.util.Iterator; 14 | import java.util.Map; 15 | import java.util.Set; 16 | import java.util.TreeMap; 17 | 18 | public class TreeMapCustomComparatorByValue { 19 | 20 | public static > Map 21 | valueSort(final Map map) { 22 | // Static Method with return type Map and 23 | // extending comparator class which compares values 24 | // associated with two keys 25 | Comparator valueComparator = new Comparator() { 26 | 27 | // return comparison results of values of 28 | // two keys 29 | public int compare(K k1, K k2) { 30 | return map.get(k2).compareTo(map.get(k1)); 31 | } 32 | }; 33 | 34 | // SortedMap created using the comparator 35 | Map sorted = new TreeMap(valueComparator); 36 | 37 | sorted.putAll(map); 38 | 39 | return sorted; 40 | } 41 | 42 | public static void main(String[] args) { 43 | TreeMap map = new TreeMap(); 44 | 45 | // Put elements to the map 46 | map.put("Anshu", 2); 47 | map.put("Rajiv", 4); 48 | map.put("Chhotu", 3); 49 | map.put("Golu", 5); 50 | map.put("Sita", 1); 51 | 52 | // Calling the method valueSort 53 | Map sortedMap = valueSort(map); 54 | 55 | // Get a set of the entries on the sorted map 56 | Set set = sortedMap.entrySet(); 57 | 58 | // Get an iterator 59 | Iterator i = set.iterator(); 60 | 61 | // Display elements 62 | while (i.hasNext()) { 63 | 64 | Map.Entry mp = (Map.Entry) i.next(); 65 | System.out.print(mp.getKey() + ": "); 66 | System.out.println(mp.getValue()); 67 | 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/javaclasses/Utility/VariableArguments.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Variable Arguments.java 3 | * * Created by Rafsan Ahmad on 11/28/21, 12:39 AM 4 | * * Copyright (c) 2021 . All rights reserved. 5 | * 6 | */ 7 | 8 | package javaclasses.Utility; 9 | 10 | public class VariableArguments { 11 | 12 | public void someMethod(String... info) { 13 | for (String someInfo : info) { 14 | // any operation 15 | } 16 | // The info can be accessed using index based loops too 17 | for (int i = 0; i < info.length; i++) { 18 | String s = info[i]; 19 | //some operation 20 | System.out.print(s + " "); 21 | } 22 | System.out.println(); 23 | } 24 | 25 | public static void main(String[] args) { 26 | VariableArguments arguments = new VariableArguments(); 27 | arguments.someMethod("Java", "Interview"); 28 | arguments.someMethod("Java", "Interview", "Questions"); 29 | arguments.someMethod(new String[]{"Java", "Interview", "Questions"}); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/Algorithm/MooreVotingAlgorithm.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Moore's Voting Algorithm.kt 4 | * * Created by Rafsan Ahmad on 5/19/25, 6:52PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.Algorithm 11 | 12 | class MooreVotingAlgorithm { 13 | /*Given an array nums of size n, return the majority element. 14 | 15 | The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that 16 | the majority element always exists in the array. 17 | 18 | 19 | 20 | Example 1: 21 | 22 | Input: nums = [3,2,3] 23 | Output: 3 24 | Example 2: 25 | 26 | Input: nums = [2,2,1,1,1,2,2] 27 | Output: 2 28 | 29 | 30 | Constraints: 31 | 32 | n == nums.length 33 | 1 <= n <= 5 * 10^4 34 | -10^9 <= nums[i] <= 10^9 35 | 36 | 37 | Follow-up: Could you solve the problem in linear time and in O(1) space?*/ 38 | 39 | /*Intuition: 40 | The intuition behind the Moore's Voting Algorithm is based on the fact that if there is a 41 | majority element in an array, it will always remain in the lead, even after encountering other 42 | elements. 43 | 44 | Explanation: 45 | Algorithm: 46 | 47 | Initialize two variables: count and candidate. Set count to 0 and candidate to an arbitrary value. 48 | Iterate through the array nums: 49 | a. If count is 0, assign the current element as the new candidate and increment count by 1. 50 | b. If the current element is the same as the candidate, increment count by 1. 51 | c. If the current element is different from the candidate, decrement count by 1. 52 | After the iteration, the candidate variable will hold the majority element.*/ 53 | 54 | fun majorityElement(nums: IntArray): Int { 55 | var element = -1 56 | var count = 0 57 | 58 | for (i in nums.indices) { 59 | if (count == 0) 60 | element = nums[i] 61 | 62 | if (nums[i] == element) { 63 | count++ 64 | } else { 65 | count-- 66 | } 67 | } 68 | 69 | return element 70 | } 71 | } 72 | 73 | fun main(args: Array) { 74 | val votingAlgorithm = MooreVotingAlgorithm() 75 | println(votingAlgorithm.majorityElement(intArrayOf(2, 2, 1, 1, 1, 2, 2))) 76 | } -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/BinarySearch/BinarySearchExample.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * BinarySearchExample.kt 4 | * * Created by Rafsan Ahmad on 3/15/25, 7:46PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.BinarySearch 11 | 12 | class BinarySearchExample { 13 | 14 | fun PerformbinarySearch(arr: IntArray, x: Int): Int { 15 | var start = 0 16 | var end = arr.size - 1 17 | while (start <= end) { 18 | var m = (start + end) / 2 19 | if (arr[m] == x) { 20 | return m 21 | } 22 | if (arr[m] < x) { 23 | //if x is greater = ignore left 24 | start = m + 1 25 | } else { 26 | //if x is smaller, ignore right 27 | end = m - 1 28 | } 29 | } 30 | return -1 31 | } 32 | } 33 | 34 | fun main(args: Array) { 35 | var ob = BinarySearchExample() 36 | var arr = intArrayOf(2, 3, 4, 6, 8, 10, 40, 45, 60) 37 | var result = ob.PerformbinarySearch(arr, 47) 38 | if (result == -1) { 39 | println("Not found") 40 | } else { 41 | println( 42 | "Element found at " 43 | + "index " + result 44 | ) 45 | } 46 | } -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/Collections/ListDifference.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * ListDifference.kt 4 | * * Created by Rafsan Ahmad on 3/15/25, 7:51PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.Collections 11 | 12 | class ListDifference { 13 | 14 | //Find difference between two lists. 15 | data class User(val id: Int, val name: String) 16 | 17 | var list1 = listOf(User(1, "John"), User(2, "Fil")) 18 | var list2 = listOf(User(1, "John"), User(3, "Nappy"), User(2, "Fil")) 19 | 20 | fun bruteForce() { 21 | //Brute force 22 | var res = mutableListOf() 23 | 24 | for (user in list1) { 25 | if (!list2.contains(user)) 26 | res.add(user) 27 | } 28 | for (user in list2) { 29 | if (!list1.contains(user)) 30 | res.add(user) 31 | } 32 | 33 | println(res) 34 | } 35 | 36 | fun usingGroupBy() { 37 | //Using groupBy 38 | val sum = list1 + list2 39 | var res2 = sum.groupBy { it.id } 40 | .filter { it.value.size == 1 } 41 | .flatMap { it.value } 42 | 43 | println(res2) 44 | } 45 | 46 | fun usingHashMap() { 47 | //Using HashMap 48 | val sum = list1 + list2 49 | val userOccurrences = HashMap() 50 | for (user in sum) { 51 | userOccurrences[user] = userOccurrences.getOrDefault(user, 0) + 1; 52 | } 53 | var res3 = sum.filter { user -> userOccurrences[user] == 1 } 54 | println(res3) 55 | } 56 | 57 | fun usingIDIntersect() { 58 | //Using Intersect ID's 59 | val sum = list1 + list2 60 | val list1Ids = list1.map { it.id } 61 | val list2Ids = list2.map { it.id } 62 | val commonIds = list1Ids.intersect(list2Ids) 63 | var res4 = sum.filter { it.id !in commonIds } 64 | println(res4) 65 | } 66 | } 67 | 68 | fun main(args: Array) { 69 | val listDiff = ListDifference() 70 | listDiff.bruteForce() 71 | listDiff.usingGroupBy() 72 | listDiff.usingHashMap() 73 | listDiff.usingIDIntersect() 74 | } -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/Collections/MergeInterval.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Merge Interval.kt 4 | * * Created by Rafsan Ahmad on 4/24/25, 2:26PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.Collections 11 | 12 | import java.util.* 13 | import kotlin.math.max 14 | 15 | class MergeInterval { 16 | /*Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping 17 | intervals, and return an array of the non-overlapping intervals that cover all the 18 | intervals in the input. 19 | 20 | Example 1: 21 | Input: intervals = [[1,3],[2,6],[8,10],[15,18]] 22 | Output: [[1,6],[8,10],[15,18]] 23 | Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6]. 24 | 25 | Example 2: 26 | Input: intervals = [[1,4],[4,5]] 27 | Output: [[1,5]] 28 | Explanation: Intervals [1,4] and [4,5] are considered overlapping. 29 | 30 | 31 | Constraints: 32 | 1 <= intervals.length <= 10^4 33 | intervals[i].length == 2 34 | 0 <= starti <= endi <= 10^4 35 | 36 | */ 37 | //Merge Overlapping inerval - (LeetCode - 56) 38 | fun merge(intervals: Array): Array { 39 | var list: MutableList = arrayListOf() 40 | 41 | Arrays.sort(intervals) { a, b -> a[0] - b[0] } 42 | 43 | for (i in 0..) { 62 | val mergeInterval = MergeInterval() 63 | var intervals = arrayOf( 64 | intArrayOf(1, 3), 65 | intArrayOf(8, 10), 66 | intArrayOf(2, 6), 67 | intArrayOf(15, 18) 68 | ) 69 | println(mergeInterval.merge(intervals).contentDeepToString()) 70 | } -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/Concepts/InterfaceDelegation.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * InterfaceDelegation.kt 4 | * * Created by Rafsan Ahmad on 3/21/25, 1:50PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.Concepts 11 | 12 | import kotlinclasses.Concepts.InterfaceDelegation.Application 13 | import kotlinclasses.Concepts.InterfaceDelegation.ConsoleLogger 14 | 15 | class InterfaceDelegation { 16 | // Define an interface 17 | interface Logger { 18 | fun log(message: String) 19 | } 20 | 21 | // Implement the interface 22 | class ConsoleLogger : Logger { 23 | override fun log(message: String) { 24 | println("Logging to console: $message") 25 | } 26 | } 27 | 28 | // Delegate the implementation of Logger to ConsoleLogger 29 | // Using By Keyword to delegate interface implementation 30 | class Application(logger: Logger) : Logger by logger 31 | } 32 | 33 | fun main() { 34 | val consoleLogger = ConsoleLogger() 35 | val app = Application(consoleLogger) 36 | 37 | // Calls log() method of ConsoleLogger via delegation 38 | app.log("Application started") 39 | } -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/Concepts/Oop/Constructors.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Constructors.kt 4 | * * Created by Rafsan Ahmad on 5/22/25, 2:14 PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.Concepts.Oop 11 | 12 | import kotlinclasses.Concepts.Oop.Constructors.Child 13 | import kotlinclasses.Concepts.Oop.Constructors.Person 14 | 15 | class Constructors { 16 | /*In Kotlin, a class can have: 17 | 18 | Primary Constructor – Defined in the class header. 19 | Secondary Constructor(s) – Defined inside the class body. 20 | 21 | Primary Constructor 22 | a. Declared in the class header. 23 | b. Can have parameters. 24 | c. Cannot contain logic (use init block for initialization). 25 | 26 | 27 | Secondary Constructor 28 | a. Declared inside the class with constructor keyword. 29 | b. Can include logic and default values. 30 | c. Must call the primary constructor (if present) using this(...). 31 | */ 32 | 33 | // Primary constructor 34 | class Person(val name: String) { 35 | 36 | var age: Int = 1 // Default value 37 | 38 | // Secondary constructor 39 | constructor(name: String, age: Int) : this(name) { 40 | this.age = age 41 | println("Person Created: $name is $age years old") 42 | } 43 | } 44 | 45 | open class Parent(val name: String) { 46 | constructor() : this("Default") { 47 | println("Parent secondary constructor") 48 | } 49 | 50 | init { 51 | println("Parent primary constructor: Name is $name") 52 | } 53 | } 54 | 55 | class Child : Parent { 56 | constructor() : super("John") { 57 | println("Child constructor") 58 | } 59 | } 60 | } 61 | 62 | fun main() { 63 | val person1 = Person("Alan") 64 | val person2 = Person("Bob", 29) 65 | // Output: 66 | // Person Created: Bob is 29 years old 67 | 68 | //Constructor order 69 | val child = Child() 70 | //Output: 71 | //Parent primary constructor: Name is John 72 | //Child constructor 73 | } -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/Concepts/Oop/MultipleInheritance.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * MultipleInheritance.kt 4 | * * Created by Rafsan Ahmad on 5/22/25, 2:15 PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.Concepts.Oop 11 | 12 | import kotlinclasses.Concepts.Oop.MultipleInheritance.C 13 | 14 | class MultipleInheritance { 15 | interface A { 16 | fun show() { 17 | println("From A") 18 | } 19 | } 20 | 21 | interface B { 22 | fun show() { 23 | println("From B") 24 | } 25 | } 26 | 27 | // Class implementing two interfaces with the same method 28 | class C : A, B { 29 | override fun show() { 30 | super.show() // Explicitly choosing A's implementation 31 | } 32 | } 33 | 34 | 35 | open class Parent(value: Int = 3) 36 | class Child1(value1: Int, value2: Int) : Parent(value1) 37 | class Child2 : Parent() 38 | class Child3() : Parent(2) 39 | class Child4 : Parent { 40 | constructor(value: Int) : super(value) 41 | } 42 | } 43 | 44 | fun main() { 45 | val obj = C() 46 | obj.show() // Output: "From A" 47 | 48 | val child1 = MultipleInheritance.Child1(2, 4) 49 | val child2 = MultipleInheritance.Child2() 50 | val child3 = MultipleInheritance.Child3() 51 | val child4 = MultipleInheritance.Child4(5) 52 | } -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/Concepts/Oop/VisibilityModifiers.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * VisibilityModifiers.kt 4 | * * Created by Rafsan Ahmad on 3/15/25, 7:53PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.Concepts.Oop 11 | 12 | class VisibilityModifiers { 13 | } 14 | 15 | open class Outer { 16 | private val a = 1 17 | protected open val b = 2 18 | internal open val c = 3 19 | val d = 4 // public/final by default 20 | 21 | protected open class Nested { 22 | public open var e: Int = 5 23 | } 24 | } 25 | 26 | class Subclass : Outer() { 27 | // a is not visible 28 | // b, c and d are visible 29 | // Nested and e are visible 30 | override val b = 5 // 'b' is protected 31 | override val c = 7 // 'c' is internal 32 | 33 | fun test() { 34 | val n = Nested() 35 | n.e = 90 36 | } 37 | } 38 | 39 | class Unrelated(o: Outer) { 40 | // o.a, o.b are not visible 41 | // o.c and o.d are visible (same module) 42 | // Outer.Nested is not visible, and Nested::e is not visible either 43 | } 44 | 45 | open class AA() { 46 | open var price: Int = 0 47 | get() = field + 10 48 | } 49 | 50 | class BB() : AA() { 51 | override var price: Int = 0 52 | get() = field + 20 53 | } -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/Concepts/OperatorFunction.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * OperatorFunction.kt 4 | * * Created by Rafsan Ahmad on 3/15/25, 7:53PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.Concepts 11 | 12 | class OperatorFunction { 13 | } 14 | 15 | operator fun Pen.plus(otherPen: Pen): Pen { 16 | val ink = "$inkColor, ${otherPen.inkColor}" 17 | return Pen(inkColor = ink) 18 | } 19 | 20 | data class Pen(val inkColor: String) { 21 | fun showInkColor() { 22 | println(inkColor) 23 | } 24 | } 25 | 26 | class Colors(val name: String, val value: Int, val usable: Boolean) { 27 | operator fun component1(): String = name 28 | operator fun component2(): Int = value 29 | operator fun component3(): Boolean = usable 30 | } 31 | 32 | val colorMap = mapOf( 33 | 1 to Colors("Red", 0, true), 34 | 2 to Colors("Green", 1, false), 35 | 3 to Colors("Blue", 2, true) 36 | ) 37 | 38 | val showColor: (Colors) -> Unit = { (name, value, usable) -> 39 | if (usable) println("$name, $value is usable") 40 | } 41 | 42 | fun main() { 43 | val bluePen = Pen(inkColor = "Blue") 44 | bluePen.showInkColor() 45 | 46 | val blackPen = Pen(inkColor = "Black") 47 | blackPen.showInkColor() 48 | 49 | val blueBlackPen = bluePen + blackPen 50 | blueBlackPen.showInkColor() 51 | 52 | colorMap.mapValues { (_, value) -> showColor(value) } 53 | } -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/Concepts/SealedClassEx.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * SealedClassEx.kt 4 | * * Created by Rafsan Ahmad on 3/15/25, 7:53PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.Concepts 11 | 12 | class SealedClassEx { 13 | /*Sealed classes let you restrict the use of inheritance. Once you declare a class sealed, 14 | it can only be subclassed from inside the same file where the sealed class is declared. 15 | It cannot be subclassed outside of the file where the sealed class is declared.*/ 16 | 17 | sealed class Mammal(val name: String) // 1 18 | 19 | class Cat(val catName: String) : Mammal(catName) // 2 20 | class Human(val humanName: String, val job: String = "Engineer") : Mammal(humanName) 21 | 22 | fun greetMammal(mammal: Mammal): String { 23 | when (mammal) { // 3 24 | is Human -> return "Hello ${mammal.name}; You're working as a ${mammal.job}" // 4 25 | is Cat -> return "Hello ${mammal.name}" // 5 26 | } // 6 27 | } 28 | /* 29 | 1.Defines a sealed class. 30 | 2.Defines subclasses. Note that all subclasses must be in the same file. 31 | 3.Uses an instance of the sealed class as an argument in a when expression. 32 | 4.A smartcast is performed, casting Mammal to Human. 33 | 5. A smartcast is performed, casting Mammal to Cat. 34 | 6. The else-case is not necessary here since all possible subclasses of the sealed class are covered. 35 | With a non-sealed superclass else would be required.*/ 36 | 37 | } 38 | 39 | fun main() { 40 | var ex = SealedClassEx() 41 | println(ex.greetMammal(SealedClassEx.Cat("Snowy"))) 42 | println(ex.greetMammal(SealedClassEx.Human("Rafsan"))) 43 | } 44 | 45 | -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/Concepts/Thread/ThreadCreation.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * ThreadCreation.kt 4 | * * Created by Rafsan Ahmad on 5/22/25, 2:15 PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.Concepts.Thread 11 | 12 | class ThreadCreation { 13 | // Extending the Thread class to implement threads. 14 | class SimpleThread : Thread() { 15 | public override fun run() { 16 | println("${currentThread()} has run.") 17 | } 18 | } 19 | 20 | // Implementing the Runnable interface to implement threads. 21 | class SimpleRunnable : Runnable { 22 | public override fun run() { 23 | println("${Thread.currentThread()} has run.") 24 | } 25 | } 26 | } 27 | 28 | fun main(args: Array) { 29 | val thread = ThreadCreation.SimpleThread() 30 | thread.start() // Will output: Thread[Thread-0,5,main] has run. 31 | val runnable = ThreadCreation.SimpleRunnable() 32 | val thread1 = Thread(runnable) 33 | thread1.start() // Will output: Thread[Thread-1,5,main] has run 34 | } -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/HashTable/MapVsFlatMap.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Map Vs FlatMap.kt 4 | * * Created by Rafsan Ahmad on 3/15/25, 7:51PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.HashTable 11 | 12 | import java.util.* 13 | import java.util.stream.Collectors 14 | 15 | class MapVsFlatMap { 16 | fun mapVsFlatmap() { 17 | //Map vs Flatmap 18 | // making the array list object 19 | val fruit = ArrayList() 20 | fruit.add("Apple") 21 | fruit.add("mango") 22 | fruit.add("pineapple") 23 | fruit.add("kiwi") 24 | println("List of fruit-$fruit") 25 | 26 | // lets use map() to convert list of fruit 27 | val list: List<*> = fruit.stream() 28 | .map { s: String -> s.length } 29 | .collect(Collectors.toList()) 30 | println("List generated by map-$list") 31 | 32 | //Flatmap 33 | // making the arraylist object of List of Integer 34 | val number: MutableList> = ArrayList() 35 | // adding the elements to number arraylist 36 | number.add(Arrays.asList(1, 2)) 37 | number.add(Arrays.asList(3, 4)) 38 | number.add(Arrays.asList(5, 6)) 39 | number.add(Arrays.asList(7, 8)) 40 | println("List of list-$number") 41 | 42 | // using flatmap() to flatten this list 43 | val flatList = number.stream() 44 | .flatMap { list: List -> list.stream() } 45 | .collect(Collectors.toList()) 46 | // printing the list 47 | println("List generate by flatMap-" + flatList) 48 | } 49 | } 50 | 51 | fun main(args: Array) { 52 | val obj = MapVsFlatMap() 53 | obj.mapVsFlatmap() 54 | } -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/LinkedList/ListNode.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * ListNode.kt 4 | * * Created by Rafsan Ahmad on 5/26/25, 9:22PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.LinkedList 11 | 12 | class ListNode(var `val`: Int) { 13 | var next: ListNode? = null 14 | } -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/Math/PalindromeNumber.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Palindrome Number.kt 4 | * * Created by Rafsan Ahmad on 6/5/25, 12:06PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.Math 11 | 12 | class PalindromeNumber { 13 | //https://leetcode.com/problems/palindrome-number/description/ 14 | /*Given an integer x, return true if x is a palindrome, and false otherwise. 15 | 16 | Example 1: 17 | Input: x = 121 18 | Output: true 19 | Explanation: 121 reads as 121 from left to right and from right to left. 20 | 21 | Example 2: 22 | Input: x = -121 23 | Output: false 24 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. 25 | Therefore it is not a palindrome. 26 | 27 | Example 3: 28 | Input: x = 10 29 | Output: false 30 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 31 | 32 | 33 | Constraints: 34 | -2^31 <= x <= 2^31 - 1 35 | 36 | 37 | Follow up: Could you solve it without converting the integer to a string?*/ 38 | 39 | fun isPalindrome(x: Int): Boolean { 40 | var temp = x 41 | var revInt: Long = 0 42 | if (x < 0) return false 43 | 44 | while (temp > 0) { 45 | val digit = temp % 10 46 | revInt = revInt * 10 + digit 47 | temp /= 10 48 | } 49 | 50 | return x.toLong() == revInt 51 | } 52 | } 53 | 54 | fun main() { 55 | val number = PalindromeNumber() 56 | println(number.isPalindrome(121)) 57 | println(number.isPalindrome(10009901)) 58 | } -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/Problems/TopURLAccessed.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * TopURLAccessed.kt 4 | * * Created by Rafsan Ahmad on 10/9/22, 9:24 PM 5 | * * Copyright (c) 2022 . All rights reserved. 6 | * 7 | */ 8 | 9 | package kotlinclasses.Problems 10 | 11 | import java.util.* 12 | 13 | class TopURLAccessed { 14 | /*Given n find the top n URLs accessed with 200 status code 15 | Log format: "10.10.0.2 200 https://www.google.com" 16 | Format: IP, StatusCode, URL 17 | Data is separated by single space 18 | If equal number of URLs accessed - sort them alphabetically & return the String Array 19 | */ 20 | fun solution(n: Int, logs: Array): Array { 21 | // write your code in Kotlin 22 | val result: MutableList = mutableListOf() 23 | val countMap: MutableMap = mutableMapOf() 24 | for (i in 0 until logs.size) { 25 | val logsSplitted = logs[i].split(" ") 26 | if (logsSplitted.get(1) == "200") { 27 | //Add to map 28 | val url = logsSplitted.get(2) 29 | countMap[url] = countMap.getOrDefault(url, 0) + 1 30 | } 31 | } 32 | // Create a list from elements of HashMap 33 | var list: List> = LinkedList(countMap.entries) 34 | // Sort the list 35 | list = list 36 | .sortedWith>(object : Comparator> { 37 | override fun compare(p0: Map.Entry, p1: Map.Entry): Int { 38 | if (p0.value == p1.value) { 39 | return p0.key.compareTo(p1.key) 40 | } 41 | return p1.value - p0.value 42 | } 43 | }) 44 | 45 | var total = n 46 | for (i in list.indices) { 47 | if (total > 0) { 48 | val mapEntry = list[i] 49 | result.add(mapEntry.key) 50 | total-- 51 | } 52 | } 53 | 54 | return result.toTypedArray() 55 | } 56 | } -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/TwoPointer/MinimumSizeSubarraySum.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * Minimum Size Subarray Sum.kt 4 | * * Created by Rafsan Ahmad on 6/4/25, 4:45PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.TwoPointer 11 | 12 | import kotlin.math.min 13 | 14 | class MinimumSizeSubarraySum { 15 | //https://leetcode.com/problems/minimum-size-subarray-sum/description/ 16 | /*Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose 17 | sum is greater than or equal to target. If there is no such subarray, return 0 instead. 18 | 19 | 20 | Example 1: 21 | Input: target = 7, nums = [2,3,1,2,4,3] 22 | Output: 2 23 | Explanation: The subarray [4,3] has the minimal length under the problem constraint. 24 | 25 | Example 2: 26 | Input: target = 4, nums = [1,4,4] 27 | Output: 1 28 | 29 | Example 3: 30 | Input: target = 11, nums = [1,1,1,1,1,1,1,1] 31 | Output: 0 32 | 33 | 34 | Constraints: 35 | 1 <= target <= 10^9 36 | 1 <= nums.length <= 10^5 37 | 1 <= nums[i] <= 10^4 38 | 39 | 40 | Follow up: If you have figured out the O(n) solution, try coding another solution of which the 41 | time complexity is O(n log(n)).*/ 42 | 43 | fun minSubArrayLen(target: Int, nums: IntArray): Int { 44 | var result = Int.MAX_VALUE 45 | val len = nums.size 46 | var left = 0 47 | var right = 0 48 | var sum = 0 49 | while (left < len && right < len) { 50 | sum += nums[right] 51 | while (sum >= target && left < len) { 52 | result = min(result, right - left + 1) 53 | sum -= nums[left] 54 | left++ 55 | } 56 | 57 | right++ 58 | } 59 | 60 | return if (result == Int.MAX_VALUE) 0 else result 61 | } 62 | } 63 | 64 | fun main() { 65 | val subarraySum = MinimumSizeSubarraySum() 66 | println(subarraySum.minSubArrayLen(7, intArrayOf(2, 3, 1, 2, 4, 3))) 67 | println(subarraySum.minSubArrayLen(4, intArrayOf(1, 4, 4))) 68 | } -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/Utility/BinaryAddition.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * BinaryAddition.kt 4 | * * Created by Rafsan Ahmad on 3/15/25, 7:46PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.Utility 11 | 12 | class BinaryAddition { 13 | 14 | fun addBinaryString(s1: String, s2: String): String { 15 | var result: StringBuilder = StringBuilder("") 16 | var carry = 0 17 | var total = 0 18 | var len1 = s1.length - 1 19 | var len2 = s2.length - 1 20 | 21 | while (len1 >= 0 || len2 >= 0) { 22 | total = 0 23 | if (len1 >= 0) { 24 | total += s1.get(len1) - '0' 25 | } 26 | if (len2 >= 0) { 27 | total += s2.get(len2) - '0' 28 | } 29 | total += carry 30 | //total = s1.get(i).toInt() + s2.get(i).toInt() + carry 31 | if (total % 2 == 0) { 32 | result.insert(0, "0") 33 | } else { 34 | result.insert(0, total % 2) 35 | } 36 | if(total >= 2) { 37 | carry = 1 38 | } else { 39 | carry = 0 40 | } 41 | len1-- 42 | len2-- 43 | } 44 | if (carry > 0) { 45 | result.insert(0, carry) 46 | } 47 | return result.toString() 48 | } 49 | } 50 | 51 | fun main(args: Array) { 52 | var ba = BinaryAddition() 53 | var result = ba.addBinaryString("111010", "101001") 54 | println(result) 55 | } -------------------------------------------------------------------------------- /src/main/java/kotlinclasses/Utility/RightLengthEncoding.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * * 3 | * * RightLengthEncoding.kt 4 | * * Created by Rafsan Ahmad on 3/15/25, 7:54PM 5 | * * Copyright (c) 2025 . All rights reserved. 6 | * * 7 | * 8 | */ 9 | 10 | package kotlinclasses.Utility 11 | 12 | class RightLengthEncoding { 13 | 14 | fun encode(str: String): String { 15 | val withoutSpaceStr = str.filter { !it.isWhitespace() } 16 | if (withoutSpaceStr.isEmpty()) return "" 17 | val strArray = withoutSpaceStr.toCharArray() 18 | var currentChar = strArray[0] 19 | var count = 0 20 | val builder = StringBuilder() 21 | for (i in 0 until strArray.size) { 22 | if (currentChar == strArray[i]) { 23 | count++ 24 | } else { 25 | builder.append(count) 26 | builder.append(currentChar) 27 | currentChar = strArray[i] 28 | count = 1 29 | } 30 | } 31 | //for last character 32 | builder.append(count) 33 | builder.append(currentChar) 34 | return builder.toString() 35 | } 36 | } 37 | 38 | fun main(args: Array) { 39 | var s = "jjjjjjjjjdddddddddiiiuusskkpppuuutttrewqnbhyj" 40 | var s2 = " " 41 | var s3 = " aa b cc " 42 | var encoded = RightLengthEncoding().encode(s3) 43 | println(encoded) 44 | } -------------------------------------------------------------------------------- /step_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/step_1.png -------------------------------------------------------------------------------- /step_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/step_2.png -------------------------------------------------------------------------------- /step_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/step_3.png -------------------------------------------------------------------------------- /step_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafsanahmad/Leetcode-InterviewBit-DSA-Practice/401a22ba456537445ce36cc21d3f544b80235445/step_4.png --------------------------------------------------------------------------------