├── .gitignore ├── README.md ├── build.gradle └── src └── main └── java ├── array ├── AddToArrayFormOfInteger.java ├── ArrayNesting.java ├── ArrayPartitionI.java ├── BattleshipsInABoard.java ├── BestMeetingPoint.java ├── CanPlaceFlowers.java ├── CardFilipGame.java ├── ChampagneTower.java ├── EmployeeFreeTime.java ├── FindPivotIndex.java ├── FindTheCelebrity.java ├── FirstMissingPositive.java ├── FruitIntoBaskets.java ├── HIndex.java ├── ImageSmoother.java ├── IncreasingTripletSubsequence.java ├── InsertInterval.java ├── KEmptySlots.java ├── LargestNumberAtLeastTwice.java ├── LargestTimeForGivenDigits.java ├── LongestIncreasingSubsequence.java ├── LongestLineofConsecutiveOneinMatrix.java ├── MatrixCellsinDistanceOrder.java ├── MaxConsecutiveOnes.java ├── MaxConsecutiveOnesII.java ├── MaxProductOfThreeNumbers.java ├── MaximumSumofTwoNonOverlappingSubarrays.java ├── MaximumSwap.java ├── MeetingRooms.java ├── MeetingScheduler.java ├── MergeIntervals.java ├── MergeSortedArray.java ├── MinimumIndexSumOfTwoLists.java ├── MinimumMovesToEqualArray.java ├── MinimumSwapsToGroupAll1Together.java ├── MinimumTimeDifference.java ├── MissingNumber.java ├── MyCalendarThree.java ├── NextGreaterElementI.java ├── PascalsTriangle.java ├── PourWater.java ├── ProductOfArrayExceptSelf.java ├── ReadNCharacters.java ├── RelativeRanks.java ├── RelativeSortArray.java ├── RevealCardsInIncreasingOrder.java ├── RotateArray.java ├── RotateMatrix.java ├── SetMatrixZeroes.java ├── SortArrayByParityII.java ├── SortColors.java ├── SparseMatrixMultiplication.java ├── SubArraysWithBoundedMaximum.java ├── SubarraySumEqualsK.java ├── SurfaceAreaOfThreeDShapes.java ├── ThirdMaximumNumber.java ├── TwoSum.java ├── TwoSumII.java └── ValidTicTacToeState.java ├── backtracking ├── CombinationSum.java ├── CombinationSumII.java ├── Combinations.java ├── ExpressionAddOperators.java ├── GenerateParentheses.java ├── LetterCasePermutation.java ├── LetterPhoneNumber.java ├── MatchsticksToSquare.java ├── PalindromePartitioning.java ├── Permutations.java ├── PermutationsII.java ├── RegularExpressionMatching.java ├── RemoveInvalidParentheses.java ├── Subsets.java ├── SubsetsII.java ├── TargetSum.java ├── WildcardMatching.java ├── WordSearch.java ├── WordSearchII.java └── ZumaGame.java ├── binary_search ├── ArmstrongNumber.java ├── FindPeakElement.java ├── FirstBadVersion.java ├── HIndexII.java ├── KokoEatingBananas.java ├── MedianOfTwoSortedArrays.java ├── MinSortedRotatedArray.java ├── MinimizeTheMaximumAdjacentElementDifference.java ├── MinimumWindowSubsequence.java ├── PowXN.java ├── SearchForARange.java ├── SearchInsertPosition.java ├── SearchRotatedSortedArray.java ├── SingleElementInASortedArray.java ├── SqrtX.java ├── SwimInRisingWater.java └── TimeBasedKeyValuePair.java ├── bit_manipulation ├── BinaryNumberWithAlternatingBits.java ├── BinaryWatch.java ├── DivideTwoIntegers.java ├── GrayCode.java ├── HammingDistance.java └── TotalHammingDistance.java ├── breadth_first_search ├── BinarayTreeLevelOrderTraversal.java ├── BusRoutes.java ├── CutOffTreesForGolfEvent.java ├── Matrix.java ├── OpenTheLock.java ├── RaceCar.java ├── RottingOranges.java ├── SlidingPuzzle.java ├── WallsAndGates.java ├── WordLadder.java └── WordLadderII.java ├── depth_first_search ├── AccountsMerge.java ├── AlienDictionary.java ├── AllPathsFromSourceToTarget.java ├── AsFarfromLandAsPossible.java ├── BricksFallingWhenHit.java ├── CloneGraph.java ├── ConnectingCitiesWithMinimumCost.java ├── CourseSchedule.java ├── CourseScheduleII.java ├── CrackingTheSafe.java ├── CriticalConnection.java ├── FloodFill.java ├── GraphValidTree.java ├── IslandPerimeter.java ├── LongestConsecutiveSequence.java ├── MaxAreaOfIsland.java ├── Minesweeper.java ├── MinimizeMalwareSpread.java ├── MovieRecommend.java ├── NumberOfDistinctIslands.java ├── NumberOfDistinctIslandsII.java ├── NumberOfEnclaves.java ├── NumberOfIslands.java ├── ParallelCourses.java ├── RobotRoomCleaner.java ├── SatisfiabilityOfEquations.java └── SmallestRectangleEnclosingBlackPixels.java ├── design ├── AutocompleteSystem.java ├── BSTIterator.java ├── CopyListWithRandomPointer.java ├── EncodeAndDecodeTinyURL.java ├── Excel.java ├── LFUCache.java ├── LRUCache.java ├── NestedIterator.java ├── RandomizedCollection.java ├── RandomizedSet.java ├── SerializeDeserializeBinaryTree.java ├── TicTacToe.java ├── Trie.java ├── Twitter.java ├── WordDictionary.java └── WordFilter.java ├── divide_and_conquer ├── KthLargestElementInAnArray.java ├── MyCalendarII.java ├── ReversePairs.java ├── ReversePairsII.java ├── SearchA2DMatrix.java └── TwentyFourGame.java ├── dynamic_programming ├── BestTimeToBuyAndSellStockIII.java ├── BestTimeToBuyAndSellStocks.java ├── BestTimeToBuyAndSellStocksWithFee.java ├── BombEnemy.java ├── BurstBalloons.java ├── CanIWin.java ├── CatAndMouse.java ├── CherryPickup.java ├── CherryPickupII.java ├── ClimbingStairs.java ├── CoinChange.java ├── CoinChange2.java ├── CombinationSumIV.java ├── ConcatenatedWords.java ├── ConstrainedSubsequenceSum.java ├── ContinuousSubarraySum.java ├── CornerRectangles.java ├── CountDifferentPalindromicSubsequences.java ├── CountVowelsPermutation.java ├── DecodeWays.java ├── DecodeWaysII.java ├── DeleteColumnsToMakeSortedIII.java ├── DistinctSubsequences.java ├── DistinctSubsequencesII.java ├── DungeonGame.java ├── EncodeStringWithShortestLength.java ├── FreedomTrail.java ├── HandshakesThatDontCross.java ├── HouseRobber.java ├── HouseRobberII.java ├── InterleavingString.java ├── JumpGameV.java ├── KnightDialer.java ├── KnightProbabilityInChessboard.java ├── LargestMultipleOfThree.java ├── LargestPlusSign.java ├── LargestSumOfAverages.java ├── LengthofLongestFibonacciSubsequence.java ├── LongestChunkedPalindromeDecomposition.java ├── LongestIncreasingSubsequence.java ├── LongestPaliandromicSubstring.java ├── LongestPalindromicSubsequence.java ├── MakeArrayStrictlyIncreasing.java ├── MaxSum3SubArray.java ├── MaximalSquare.java ├── MaximumProductSubarray.java ├── MaximumProfitInJobScheduling.java ├── MaximumSubarray.java ├── MaximumVacationDays.java ├── MinCostClimbingStairs.java ├── MinimumCostForTickets.java ├── MinimumCostToMergeStones.java ├── MinimumDifficultyOfAJobSchedule.java ├── MinimumDistanceToTypeAWordUsingTwoFingers.java ├── MinimumNumberOfRefuelingStops.java ├── MinimumNumberOfTaps.java ├── NonNegativeIntegersWithoutConsecutiveOnes.java ├── NumberOfDiceRollsWithTargetSum.java ├── NumberOfLIS.java ├── NumberOfMusicPlaylists.java ├── NumberOfPathsWithMaxScore.java ├── NumberOfWaysToStayInTheSamePlace.java ├── OddEvenJump.java ├── OnesAndZeroes.java ├── OutOfBoundaryPaths.java ├── PaintHouseII.java ├── PaintHouseIII.java ├── PalindromePairs.java ├── PalindromePartitioningII.java ├── PalindromePartitioningIII.java ├── PalindromeRemoval.java ├── PalindromicSubstrings.java ├── ProfitableSchemes.java ├── RemoveBoxes.java ├── RestoreTheArray.java ├── RussianDollEnvelopes.java ├── ShortestPathVisitingAllNodes.java ├── SmallestSufficientTeam.java ├── SplitArrayLargestSum.java ├── StickersToSpellWord.java ├── StoneGame.java ├── StoneGameIII.java ├── StoneGameIV.java ├── StrangePrinter.java ├── TallestBillboard.java ├── TilingARectangle.java ├── TossStrangeCoins.java ├── TwoKeysKeyboard.java ├── UniqueBinarySearchTrees.java ├── UniqueBinarySearchTreesII.java ├── ValidPalindromeIII.java ├── WordBreak.java └── WordBreakII.java ├── greedy ├── BoatsToSavePeople.java ├── BrokenCalculator.java ├── BurstBalloons.java ├── CourseScheduleIII.java ├── GasStation.java ├── IPO.java ├── JumpGame.java ├── JumpGameII.java ├── LemonadeChange.java ├── MaximumLengthOfPairChain.java ├── MinimumTimeToBuildBlocks.java ├── NonOverlappingIntervals.java ├── PartitionLabels.java ├── QueueReconstructionByHeight.java ├── ReducingDishes.java ├── ScoreAfterFlippingMatrix.java ├── StringWithout3A3B.java ├── TaskScheduler.java └── TwoCityScheduling.java ├── hashing ├── Anagrams.java ├── AnalyzeUserWebsiteVisitPattern.java ├── BrickWall.java ├── ContiguousArray.java ├── CustomSortString.java ├── DistributeCandies.java ├── GroupAnagrams.java ├── GroupsOfSpecialEquivalentStrings.java ├── KdiffPairsInanArray.java ├── LargestUniqueNumber.java ├── MaximumSizeSubarraySumEqualsk.java ├── NumberOfAtoms.java ├── PartitionLabels.java ├── ShortEncodingOfWords.java ├── SortCharByFrequency.java ├── StringTransformsIntoAnotherString.java ├── SubstringConcatenationOfWords.java ├── TwoSum.java └── ValidAnagram.java ├── heap ├── Candy.java ├── DistantBarcodes.java ├── FreqStack.java ├── KClosestPointsToOrigin.java ├── MeetingRoomsII.java ├── ReachableNodesInSubdividedGraph.java ├── SlidingWindowMaximum.java ├── SmallestRotationWithHighestScore.java ├── TheSkylineProblem.java └── TopKFrequentWords.java ├── linked_list ├── DeleteNode.java ├── IntersectionOfTwoLists.java ├── LinkedListCycle.java ├── MergeKSortedLists.java ├── MergeTwoSortedList.java ├── MiddleOfLinkedList.java ├── NextGreaterNodeInLinkedList.java ├── PaliandromeList.java ├── ReverseLinkedList.java ├── ReverseNodesKGroup.java ├── SplitLinkedListInParts.java └── SwapNodesInPairs.java ├── math ├── AddDigits.java ├── AddTwoNumbers.java ├── Base7.java ├── BulbSwitcherII.java ├── CountPrimes.java ├── CouplesHoldingHands.java ├── DecodedStringAtIndex.java ├── ExcelSheetColumnTitle.java ├── GlobalAndLocalInversions.java ├── LargestComponentSizebyCommonFactor.java ├── MinimumIndexSumOfTwoLists.java ├── NthDigit.java ├── NthMagicalNumber.java ├── ProjectionAreaOf3DShapes.java ├── RangeAdditionII.java ├── ReachingPoints.java ├── RectangleOverlap.java ├── RomanToInteger.java ├── RotateFunction.java ├── SmallestRangeI.java ├── SolveTheEquation.java ├── SquirrelSimulation.java ├── SuperWashingMachines.java └── WaterAndJugProblem.java ├── reservoir_sampling └── RandomPickIndex.java ├── stack ├── BasicCalculator.java ├── DecodeString.java ├── DecodedStringAtIndex.java ├── ExclusiveTimeOfFunctions.java ├── LargestRectangleInHistogram.java ├── LongestValidParentheses.java ├── MaximalRectangle.java ├── MinStack.java ├── MyQueue.java ├── StudentAttendanceRecordII.java └── ValidParentheses.java ├── string ├── AddBinary.java ├── CompareVersionNumbers.java ├── CountAndSay.java ├── ExcelSheetColumnNumber.java ├── FindTheClosestPalindrome.java ├── FindWordsThatCanBeFormedbyCharacters.java ├── FirstUniqueCharacterInAString.java ├── ImplementStrStr.java ├── IsomorphicStrings.java ├── KeyboardRow.java ├── LongestCommonPrefix.java ├── LongestPalindrome.java ├── LongestWordInDictonary.java ├── MinimumAddtoMakeParenthesesValid.java ├── MonotoneIncreasingDigits.java ├── MultiplyStrings.java ├── NumberOfMatchingSubsequences.java ├── OneEditDistance.java ├── PermutationInString.java ├── PushDominoes.java ├── ReconstructOriginalDigitsFromEnglish.java ├── RepeatedSubstringPattern.java ├── ReplaceWords.java ├── ReverseStringII.java ├── ReverseWordsII.java ├── ReverseWordsInAString.java ├── RotateString.java ├── ShortestPalindrome.java ├── SimplifyPath.java ├── SplitConcatenatedStrings.java ├── StampingTheSequence.java ├── StringCompression.java ├── StringToInteger.java ├── StudentAttendanceRecordI.java ├── TextJustification.java ├── ValidPalindrome.java ├── ValidPalindromeII.java ├── ValidWordAbbreviation.java ├── ValidWordSquare.java ├── ValidateIPAddress.java └── ZigZagConversion.java ├── tree ├── AllNodesDistanceKInBinaryTree.java ├── AllPossibleFullBinaryTrees.java ├── AverageOfLevelsInBinaryTree.java ├── BSTtoDoublyLinkedList.java ├── BinarayTreeRightSideView.java ├── BinaryTreeInorderTraversal.java ├── BinaryTreeLongestConsecutiveSequenceII.java ├── BinaryTreeMaximumPathSum.java ├── BinaryTreePaths.java ├── BinaryTreePostorderTraversal.java ├── BinaryTreeTilt.java ├── BoundaryOfBinaryTree.java ├── ClosestBinarySearchTreeValue.java ├── ClosestLeafInABinaryTree.java ├── ConstructBinaryTreefromString.java ├── ConstructStringFromBinaryTree.java ├── ConvertBSTToGreaterTree.java ├── ConvertSortedArrayToBST.java ├── DiameterOfBinaryTree.java ├── EqualTreePartition.java ├── FindBottomLeftTreeValue.java ├── FindLargestValueInEachTreeRow.java ├── FlattenBinaryTree.java ├── FlipBinaryTree.java ├── FlipEquivalentBinaryTrees.java ├── InorderSuccessorInBST.java ├── InsufficientNodesinRoottoLeafPaths.java ├── LCA.java ├── LargestBSTSubtree.java ├── LeafSimilarTrees.java ├── LowestCommonAncestorBST.java ├── MaximumBinaryTree.java ├── MaximumLevelSumofABinaryTree.java ├── MaximumWidthOfBinaryTree.java ├── MinimumAbsoluteDifferenceInBST.java ├── MostFrequentSubtreeSum.java ├── NextRightPointer.java ├── NextRightPointerII.java ├── PathSumIII.java ├── PostorderToBT.java ├── PreorderToBT.java ├── RecoverBinarySearchTree.java ├── SameTree.java ├── SerializeAndDeserializeNAryTree.java ├── SortedArrayToBST.java ├── SplitBST.java ├── SubtreeOfAnotherTree.java ├── SumofLeftLeaves.java ├── SymmetricTree.java ├── TwoSumIV.java ├── ValidBinarySearchTree.java └── ZigZagTraversal.java └── two_pointers ├── FourSum.java ├── LastSubstringInLexicographicalOrder.java ├── LongestSubstringWitoutRepeats.java ├── MinimumSizeSubarraySum.java ├── MinimumWindowSubstring.java ├── MoveZeroes.java ├── NumberOfMatchingSubsequences.java ├── RemoveDuplicates.java ├── RemoveDuplicatesII.java ├── SmallestRange.java ├── SubarrayProductLessThanK.java ├── SubarraysWithKDifferentIntegers.java ├── ThreeSum.java ├── ThreeSumClosest.java └── TrappingRainWater.java /.gitignore: -------------------------------------------------------------------------------- 1 | CheckerClass.template 2 | TaskClass.template 3 | TestCaseClass.template 4 | TopCoderTaskClass.template 5 | TopCoderTestCaseClass.template 6 | build/ 7 | chelper.properties 8 | gradle/ 9 | gradlew 10 | gradlew.bat 11 | leetcode.iml 12 | leetcode.ipr 13 | leetcode.iws 14 | out/ 15 | problems/src.iml 16 | .idea 17 | .gradle/ 18 | .DS_Store 19 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'com.diffplug.spotless' version '7.0.0.BETA4' 4 | } 5 | 6 | java { 7 | toolchain { 8 | languageVersion = JavaLanguageVersion.of(23) // Replace with your desired version 9 | } 10 | } 11 | 12 | spotless { 13 | java { 14 | // Use the default import order configuration 15 | importOrder('java', 'javax', 'com.acme', '', '#com.acme', '#') 16 | 17 | // Remove unused imports 18 | removeUnusedImports() 19 | 20 | // Apply formatting to annotations 21 | formatAnnotations() 22 | } 23 | } 24 | 25 | tasks.withType(JavaCompile).configureEach { 26 | options.release = 23 // Match the desired version 27 | } 28 | 29 | repositories { 30 | mavenCentral() 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/array/AddToArrayFormOfInteger.java: -------------------------------------------------------------------------------- 1 | /* (C) 2024 YourCompanyName */ 2 | package array; 3 | 4 | import java.math.BigInteger; 5 | import java.util.*; 6 | 7 | /** 8 | * Created by gouthamvidyapradhan on 25/07/2019 9 | * 10 | *
For a non-negative integer X, the array-form of X is an array of its digits in left to right 11 | * order. For example, if X = 1231, then the array form is [1,2,3,1]. 12 | * 13 | *
Given the array-form A of a non-negative integer X, return the array-form of the integer X+K. 14 | * 15 | *
Example 1: 16 | * 17 | *
Input: A = [1,2,0,0], K = 34 Output: [1,2,3,4] Explanation: 1200 + 34 = 1234 Example 2: 18 | * 19 | *
Input: A = [2,7,4], K = 181 Output: [4,5,5] Explanation: 274 + 181 = 455 Example 3: 20 | * 21 | *
Input: A = [2,1,5], K = 806 Output: [1,0,2,1] Explanation: 215 + 806 = 1021 Example 4: 22 | * 23 | *
Input: A = [9,9,9,9,9,9,9,9,9,9], K = 1 Output: [1,0,0,0,0,0,0,0,0,0,0] Explanation: 24 | * 9999999999 + 1 = 10000000000 25 | * 26 | *
Note: 27 | * 28 | *
1 <= A.length <= 10000 0 <= A[i] <= 9 0 <= K <= 10000 If A.length > 1, then A[0] != 0 29 | * 30 | *
Solution: O(N) use BigInteger to add long numbers
31 | */
32 | public class AddToArrayFormOfInteger {
33 | public static void main(String[] args) {
34 | //
35 | }
36 |
37 | public List Suppose the first element in S starts with the selection of element A[i] of index = i, the
12 | * next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right
13 | * before a duplicate element occurs in S.
14 | *
15 | * Example 1:
16 | *
17 | * Input: A = [5,4,0,3,1,6,2] Output: 4 Explanation: A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4]
18 | * = 1, A[5] = 6, A[6] = 2.
19 | *
20 | * One of the longest S[K]: S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}
21 | *
22 | * Note:
23 | *
24 | * N is an integer within the range [1, 20,000]. The elements of A are all distinct. Each element
25 | * of A is an integer within the range [0, N-1].
26 | */
27 | public class ArrayNesting {
28 | public static void main(String[] args) {
29 | int[] A = {5, 4, 0, 3, 1, 6, 2};
30 | System.out.println(new ArrayNesting().arrayNesting(A));
31 | }
32 |
33 | Set Example 1: Input: [1,4,3,2]
12 | *
13 | * Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).
14 | * Note: n is a positive integer, which is in the range of [1, 10000]. All the integers in the array
15 | * will be in the range of [-10000, 10000].
16 | *
17 | * Solution: O(n log n) General idea is to pair the smallest with the next smallest value inorder
18 | * to get the max sum of minimum.
19 | */
20 | public class ArrayPartitionI {
21 | public static void main(String[] args) {
22 | int[] A = {1, 2, 3, 4};
23 | System.out.println(new ArrayPartitionI().arrayPairSum(A));
24 | }
25 |
26 | public int arrayPairSum(int[] nums) {
27 | Arrays.sort(nums);
28 | int sum = 0;
29 | for (int i = 1; i < nums.length; i += 2) {
30 | sum += Math.min(nums[i - 1], nums[i]);
31 | }
32 | return sum;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/array/FirstMissingPositive.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package array;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 24/06/2017. Given an unsorted integer array, find the first
6 | * missing positive integer.
7 | *
8 | * For example, Given [1,2,0] return 3, and [3,4,-1,1] return 2.
9 | *
10 | * Your algorithm should run in O(n) time and uses constant space.
11 | */
12 | public class FirstMissingPositive {
13 | private int L;
14 |
15 | public static void main(String[] args) throws Exception {
16 | int[] nums = {1, 3, 5, 9};
17 | System.out.println(new FirstMissingPositive().firstMissingPositive(nums));
18 | }
19 |
20 | public int firstMissingPositive(int[] nums) {
21 | L = nums.length;
22 | for (int i = 0; i < L; i++) {
23 | if (nums[i] > 0 && nums[i] <= L && nums[i] != i + 1) {
24 | int v = nums[i];
25 | nums[i] = -1;
26 | replace(v, nums);
27 | }
28 | }
29 |
30 | for (int i = 0; i < L; i++) {
31 | if (nums[i] != i + 1) return i + 1;
32 | }
33 |
34 | return L + 1;
35 | }
36 |
37 | private void replace(int i, int[] nums) {
38 | if (i > 0 && i <= L && i != nums[i - 1]) {
39 | int v = nums[i - 1];
40 | nums[i - 1] = i;
41 | replace(v, nums);
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/array/IncreasingTripletSubsequence.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package array;
3 |
4 | import java.util.Arrays;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 17/12/2017. Given an unsorted array return whether an
8 | * increasing subsequence of length 3 exists or not in the array.
9 | *
10 | * Formally the function should: Return true if there exists i, j, k such that arr[i] < arr[j] <
11 | * arr[k] given 0 ≤ i < j < k ≤ n-1 else return false. Your algorithm should run in O(n) time
12 | * complexity and O(1) space complexity.
13 | *
14 | * Examples: Given [1, 2, 3, 4, 5], return true.
15 | *
16 | * Given [5, 4, 3, 2, 1], return false.
17 | */
18 | public class IncreasingTripletSubsequence {
19 |
20 | /**
21 | * Main method
22 | *
23 | * @param args
24 | * @throws Exception
25 | */
26 | public static void main(String[] args) throws Exception {
27 | int[] A = {1, 2, 3, 4, 5};
28 | System.out.println(new IncreasingTripletSubsequence().increasingTriplet(A));
29 | }
30 |
31 | public boolean increasingTriplet(int[] nums) {
32 | int[] A = new int[3];
33 | Arrays.fill(A, Integer.MAX_VALUE);
34 | for (int num : nums) {
35 | if (num < A[0]) {
36 | A[0] = num;
37 | } else if (num < A[1] && num > A[0]) {
38 | A[1] = num;
39 | } else if (num < A[2] && num > A[1]) {
40 | return true;
41 | }
42 | }
43 | return false;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/array/LargestNumberAtLeastTwice.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package array;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 09/02/2018. In a given integer array nums, there is always
6 | * exactly one largest element.
7 | *
8 | * Find whether the largest element in the array is at least twice as much as every other number
9 | * in the array.
10 | *
11 | * If it is, return the index of the largest element, otherwise return -1.
12 | *
13 | * Example 1:
14 | *
15 | * Input: nums = [3, 6, 1, 0] Output: 1 Explanation: 6 is the largest integer, and for every
16 | * other number in the array x, 6 is more than twice as big as x. The index of value 6 is 1, so we
17 | * return 1.
18 | *
19 | * Example 2:
20 | *
21 | * Input: nums = [1, 2, 3, 4] Output: -1 Explanation: 4 isn't at least as big as twice the value
22 | * of 3, so we return -1.
23 | *
24 | * Note:
25 | *
26 | * nums will have a length in the range [1, 50]. Every nums[i] will be an integer in the range
27 | * [0, 99].
28 | */
29 | public class LargestNumberAtLeastTwice {
30 |
31 | /**
32 | * Main method
33 | *
34 | * @param args
35 | * @throws Exception
36 | */
37 | public static void main(String[] args) throws Exception {}
38 |
39 | public int dominantIndex(int[] nums) {
40 | int index = 0, max = Integer.MIN_VALUE;
41 | for (int i = 0; i < nums.length; i++) {
42 | if (nums[i] > max) {
43 | max = nums[i];
44 | index = i;
45 | }
46 | }
47 | for (int i = 0; i < nums.length; i++) {
48 | if (i == index) continue;
49 | if (((long) nums[i] * 2) > max) {
50 | return -1;
51 | }
52 | }
53 | return index;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/array/LongestIncreasingSubsequence.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package array;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 03/12/2017.
6 | *
7 | * Given an unsorted array of integers, find the length of longest continuous increasing
8 | * subsequence (subarray).
9 | *
10 | * Example 1: Input: [1,3,5,4,7] Output: 3 Explanation: The longest continuous increasing
11 | * subsequence is [1,3,5], its length is 3. Even though [1,3,5,7] is also an increasing subsequence,
12 | * it's not a continuous one where 5 and 7 are separated by 4. Example 2: Input: [2,2,2,2,2] Output:
13 | * 1 Explanation: The longest continuous increasing subsequence is [2], its length is 1. Note:
14 | * Length of the array will not exceed 10,000.
15 | */
16 | public class LongestIncreasingSubsequence {
17 |
18 | /**
19 | * Main method
20 | *
21 | * @param args
22 | * @throws Exception
23 | */
24 | public static void main(String[] args) throws Exception {
25 | int[] A = {1, 3, 5, 4, 7};
26 | System.out.println(new LongestIncreasingSubsequence().findLengthOfLCIS(A));
27 | }
28 |
29 | public int findLengthOfLCIS(int[] nums) {
30 | int max = 1, count = 1;
31 | if (nums.length == 1) return max;
32 | if (nums.length == 0) return 0;
33 | for (int i = 0, j = i + 1; j < nums.length; ) {
34 | if (nums[j] > nums[i]) {
35 | count++;
36 | i++;
37 | j++;
38 | } else {
39 | max = Math.max(max, count);
40 | count = 0;
41 | i = j;
42 | j = i + 1;
43 | }
44 | }
45 | return max;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/array/MaxConsecutiveOnes.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package array;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 08/05/2019 Given a binary array, find the maximum number of
6 | * consecutive 1s in this array.
7 | *
8 | * Example 1: Input: [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three
9 | * digits are consecutive 1s. The maximum number of consecutive 1s is 3. Note:
10 | *
11 | * The input array will only contain 0 and 1. The length of input array is a positive integer and
12 | * will not exceed 10,000
13 | */
14 | public class MaxConsecutiveOnes {
15 | public static void main(String[] args) {
16 | //
17 | }
18 |
19 | public int findMaxConsecutiveOnes(int[] nums) {
20 | int max = 0;
21 | boolean flag = false;
22 | int count = 0;
23 | for (int i = 0; i < nums.length; i++) {
24 | if (nums[i] == 1) {
25 | if (!flag) {
26 | flag = true;
27 | }
28 | count++;
29 | max = Math.max(max, count);
30 | } else {
31 | count = 0;
32 | flag = false;
33 | }
34 | }
35 | return max;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/array/MaxProductOfThreeNumbers.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package array;
3 |
4 | import java.util.Arrays;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 27/06/2017. Given an integer array, find three numbers whose
8 | * product is maximum and output the maximum product.
9 | *
10 | * Example 1: Input: [1,2,3] Output: 6 Example 2: Input: [1,2,3,4] Output: 24 Note: The length of
11 | * the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
12 | * Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.
13 | */
14 | public class MaxProductOfThreeNumbers {
15 | public static void main(String[] args) {
16 | int[] A = {1, 2, 3};
17 | System.out.println(new MaxProductOfThreeNumbers().maximumProduct(A));
18 | }
19 |
20 | public int maximumProduct(int[] nums) {
21 | Arrays.sort(nums);
22 | int prod1 = nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3];
23 | int prod2 = nums[nums.length - 1] * nums[0] * nums[1];
24 | return prod1 > prod2 ? prod1 : prod2;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/array/MaximumSwap.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package array;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 10/12/2017. Given a non-negative integer, you could swap two
6 | * digits at most once to get the maximum valued number. Return the maximum valued number you could
7 | * get.
8 | *
9 | * Example 1: Input: 2736 Output: 7236 Explanation: Swap the number 2 and the number 7. Example
10 | * 2: Input: 9973 Output: 9973 Explanation: No swap. Note: The given number is in the range [0, 108]
11 | *
12 | * Solution O(n): Create a array of digit index. Iterate through the digits starting from left
13 | * and in each iteration check if there is any digit which is greater than the current digit and
14 | * appearing after the current index, if found then swap and return the new integer.
15 | */
16 | public class MaximumSwap {
17 |
18 | public static void main(String[] args) throws Exception {
19 | System.out.println(new MaximumSwap().maximumSwap(2736));
20 | }
21 |
22 | public int maximumSwap(int num) {
23 | int[] D = new int[10];
24 | char[] A = String.valueOf(num).toCharArray();
25 | for (int i = 0; i < A.length; i++) {
26 | D[A[i] - '0'] = i;
27 | }
28 |
29 | boolean found = false;
30 |
31 | for (int i = 0; i < A.length; i++) {
32 | int digit = A[i] - '0';
33 | for (int j = 9; j > digit; j--) {
34 | if (D[j] > i) {
35 | char temp = A[i];
36 | A[i] = (char) (j + '0');
37 | A[D[j]] = temp;
38 | found = true;
39 | break;
40 | }
41 | }
42 | if (found) break;
43 | }
44 |
45 | return Integer.parseInt(String.valueOf(A));
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/array/MeetingRooms.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package array;
3 |
4 | import java.util.Arrays;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 27/11/2017. Given an array of meeting time intervals consisting
8 | * of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all
9 | * meetings.
10 | *
11 | * For example, Given [[0, 30],[5, 10],[15, 20]], return false.
12 | *
13 | * Solution: Sort the interval based on the start interval. Then, for every interval check if the
14 | * previous interval ends before the start of the current interval.
15 | */
16 | public class MeetingRooms {
17 |
18 | public static class Interval {
19 | int start;
20 | int end;
21 |
22 | Interval() {
23 | start = 0;
24 | end = 0;
25 | }
26 |
27 | Interval(int s, int e) {
28 | start = s;
29 | end = e;
30 | }
31 | }
32 |
33 | public static void main(String[] args) throws Exception {
34 | Interval i1 = new Interval(0, 30);
35 | Interval i2 = new Interval(5, 10);
36 | Interval i3 = new Interval(15, 20);
37 | Interval[] intervals = {i1, i2, i3};
38 |
39 | System.out.println(new MeetingRooms().canAttendMeetings(intervals));
40 | }
41 |
42 | public boolean canAttendMeetings(Interval[] intervals) {
43 | Arrays.sort(intervals, (a, b) -> Integer.compare(a.start, b.start));
44 | for (int i = 1; i < intervals.length; i++) {
45 | if (intervals[i].start < intervals[i - 1].end) return false;
46 | }
47 | return true;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/array/MergeSortedArray.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package array;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 29/07/2017. Given two sorted integer arrays nums1 and nums2,
6 | * merge nums2 into nums1 as one sorted array.
7 | *
8 | * Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to
9 | * hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m
10 | * and n respectively.
11 | */
12 | public class MergeSortedArray {
13 | public static void main(String[] args) throws Exception {
14 | int[] A = {0};
15 | int[] B = {1};
16 | new MergeSortedArray().merge(A, 0, B, 1);
17 | for (int i : A) System.out.println(i);
18 | }
19 |
20 | public void merge(int[] nums1, int m, int[] nums2, int n) {
21 | int i = m + n - 1, j = m - 1, k = n - 1;
22 | while (j >= 0 && k >= 0) nums1[i--] = (nums1[j] > nums2[k]) ? nums1[j--] : nums2[k--];
23 | while (k >= 0) nums1[i--] = nums2[k--];
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/array/MissingNumber.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package array;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 04/07/2017. Given an array containing n distinct numbers taken
6 | * from 0, 1, 2, ..., n, find the one that is missing from the array.
7 | *
8 | * For example, Given nums = [0, 1, 3] return 2.
9 | *
10 | * Note: Your algorithm should run in linear runtime complexity. Could you implement it using
11 | * only constant extra space complexity?
12 | */
13 | public class MissingNumber {
14 |
15 | public static void main(String[] args) throws Exception {
16 | int[] nums = {0};
17 | System.out.println(new MissingNumber().missingNumber(nums));
18 | }
19 |
20 | public int missingNumber(int[] nums) {
21 | int sum = 0;
22 | int n = nums.length;
23 | for (int num : nums) {
24 | sum += num;
25 | }
26 | int arrSum = (((n + 1)) * n) / 2;
27 | if (arrSum == sum) return 0;
28 | else return arrSum - sum;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/array/PascalsTriangle.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package array;
3 |
4 | import java.util.ArrayList;
5 | import java.util.Arrays;
6 | import java.util.List;
7 |
8 | /**
9 | * Created by gouthamvidyapradhan on 25/03/2017.
10 | *
11 | * Given an index k, return the kth row of the Pascal's triangle.
12 | *
13 | * For example, given k = 3, Return [1,3,3,1].
14 | *
15 | * Note: Could you optimize your algorithm to use only O(k) extra space?
16 | */
17 | public class PascalsTriangle {
18 | public static void main(String[] args) throws Exception {
19 | System.out.println(new PascalsTriangle().getRow(3));
20 | }
21 |
22 | public List Given an array of n integers where n > 1, nums, return an array output such that output[i] is
8 | * equal to the product of all the elements of nums except nums[i].
9 | *
10 | * Solve it without division and in O(n).
11 | *
12 | * For example, given [1,2,3,4], return [24,12,8,6].
13 | *
14 | * Follow up: Could you solve it with constant space complexity? (Note: The output array does not
15 | * count as extra space for the purpose of space complexity analysis.)
16 | */
17 | public class ProductOfArrayExceptSelf {
18 | public static void main(String[] args) {
19 | int[] nums = {1, 2, 3, 4};
20 | int[] result = new ProductOfArrayExceptSelf().productExceptSelf(nums);
21 | for (int r : result) System.out.print(r + " ");
22 | }
23 |
24 | public int[] productExceptSelf(int[] nums) {
25 | int[] result = new int[nums.length];
26 | for (int i = 0, temp = 1, l = nums.length; i < l; i++) {
27 | result[i] = temp;
28 | temp *= nums[i];
29 | }
30 | for (int i = nums.length - 1, temp = 1; i >= 0; i--) {
31 | result[i] = result[i] * temp;
32 | temp *= nums[i];
33 | }
34 | return result;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/array/ReadNCharacters.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package array;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 09/12/2017. The API: int read4(char *buf) reads 4 characters at
6 | * a time from a file.
7 | *
8 | * The return value is the actual number of characters read. For example, it returns 3 if there
9 | * is only 3 characters left in the file.
10 | *
11 | * By using the read4 API, implement the function int read(char *buf, int n) that reads n
12 | * characters from the file.
13 | *
14 | * Note: The read function will only be called once for each test case.
15 | */
16 | public class ReadNCharacters {
17 |
18 | /**
19 | * Main method
20 | *
21 | * @param args
22 | */
23 | public static void main(String[] args) {}
24 |
25 | /**
26 | * @param buf
27 | * @param n
28 | * @return
29 | */
30 | public int read(char[] buf, int n) {
31 | int i = 0;
32 | int toRead = Math.min(n, buf.length);
33 | while (i < toRead) {
34 | char[] temp = new char[4];
35 | int r = read4(temp);
36 | for (int j = 0; j < r && i < toRead; j++) {
37 | buf[i] = temp[j];
38 | i++;
39 | }
40 | if (r < 4) break;
41 | }
42 | return Math.min(i, toRead);
43 | }
44 |
45 | private int read4(char[] buf) {
46 | return 1; // return fake value just to resolve compilation error
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/array/RotateArray.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package array;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 01/08/2017. Rotate an array of n elements to the right by k
6 | * steps.
7 | *
8 | * For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
9 | *
10 | * Note: Try to come up as many solutions as you can, there are at least 3 different ways to
11 | * solve this problem.
12 | *
13 | * Hint: Could you do it in-place with O(1) extra space? Related problem: Reverse Words in a
14 | * String II
15 | */
16 | public class RotateArray {
17 | /**
18 | * Main method
19 | *
20 | * @param args
21 | * @throws Exception
22 | */
23 | public static void main(String[] args) throws Exception {
24 | int[] A = {1, 2, 3, 4, 5, 6};
25 | new RotateArray().rotate(A, 2);
26 | for (int i : A) System.out.print(i + " ");
27 | }
28 |
29 | public void rotate(int[] nums, int k) {
30 | k = k % nums.length;
31 | reverse(nums, 0, nums.length - 1);
32 | reverse(nums, 0, k - 1);
33 | reverse(nums, k, nums.length - 1);
34 | }
35 |
36 | private void reverse(int[] nums, int s, int e) {
37 | for (int i = s, j = e; i < j; i++, j--) {
38 | int temp = nums[i];
39 | nums[i] = nums[j];
40 | nums[j] = temp;
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/array/RotateMatrix.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package array;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 21/03/2017. You are given an n x n 2D matrix representing an
6 | * image.
7 | *
8 | * Rotate the image by 90 degrees (clockwise).
9 | *
10 | * Follow up: Could you do this in-place?
11 | */
12 | public class RotateMatrix {
13 | /**
14 | * Main method
15 | *
16 | * @param args
17 | * @throws Exception
18 | */
19 | public static void main(String[] args) throws Exception {
20 | int[][] A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
21 | new RotateMatrix().rotate(A);
22 | for (int i = 0; i < A.length; i++) {
23 | for (int j = 0; j < A[0].length; j++) {
24 | System.out.println(A[i][j]);
25 | }
26 | }
27 | }
28 |
29 | public void rotate(int[][] matrix) {
30 | int lc = 0, tr = 0, rc = matrix[0].length - 1, br = matrix.length - 1;
31 | while (tr < br) {
32 | for (int i = lc, j = tr, k = rc, l = br;
33 | i < rc && j < br && k > lc && l > tr;
34 | i++, j++, k--, l--) {
35 | int temp1 = matrix[j][rc];
36 | matrix[j][rc] = matrix[tr][i];
37 | int temp2 = matrix[br][k];
38 | matrix[br][k] = temp1;
39 | temp1 = matrix[l][lc];
40 | matrix[l][lc] = temp2;
41 | matrix[tr][i] = temp1;
42 | }
43 | lc++;
44 | tr++;
45 | rc--;
46 | br--;
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/array/SetMatrixZeroes.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package array;
3 |
4 | import java.util.HashSet;
5 | import java.util.Set;
6 |
7 | /**
8 | * Created by pradhang on 3/28/2017. Given a m x n matrix, if an element is 0, set its entire row
9 | * and column to 0. Do it in place.
10 | *
11 | * click to show follow up.
12 | *
13 | * Follow up: Did you use extra space? A straight forward solution using O(mn) space is probably
14 | * a bad idea. A simple improvement uses O(m + n) space, but still not the best solution. Could you
15 | * devise a constant space solution?
16 | */
17 | public class SetMatrixZeroes {
18 | /**
19 | * Main method
20 | *
21 | * @param args
22 | * @throws Exception
23 | */
24 | public static void main(String[] args) throws Exception {
25 | int[][] matrix = {{0, 8, 7}, {9, 0, 8}, {9, 9, 0}};
26 |
27 | new SetMatrixZeroes().setZeroes(matrix);
28 | }
29 |
30 | public void setZeroes(int[][] matrix) {
31 | Set Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.
11 | *
12 | * You may return any answer array that satisfies this condition.
13 | *
14 | * Example 1:
15 | *
16 | * Input: [4,2,5,7] Output: [4,5,2,7] Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also
17 | * have been accepted.
18 | *
19 | * Note:
20 | *
21 | * 2 <= A.length <= 20000 A.length % 2 == 0 0 <= A[i] <= 1000 Solution: O(N) straight forward
22 | * linear solution, keep track of odd and even indices and increment by 2 every time a value is
23 | * added at the index.
24 | */
25 | public class SortArrayByParityII {
26 | public static void main(String[] args) {
27 | //
28 | }
29 |
30 | public int[] sortArrayByParityII(int[] A) {
31 | int[] R = new int[A.length];
32 | int i = 0, j = 1;
33 | for (int a : A) {
34 | if (a % 2 == 0) {
35 | R[i] = a;
36 | i += 2;
37 | } else {
38 | R[j] = a;
39 | j += 2;
40 | }
41 | }
42 | return R;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/array/TwoSumII.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package array;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 18/03/2017. Given an array of integers that is already sorted
6 | * in ascending order, find two numbers such that they add up to a specific target number.
7 | *
8 | * The function twoSum should return indices of the two numbers such that they add up to the
9 | * target, where index1 must be less than index2. Please note that your returned answers (both
10 | * index1 and index2) are not zero-based.
11 | *
12 | * You may assume that each input would have exactly one solution and you may not use the same
13 | * element twice.
14 | *
15 | * Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2
16 | */
17 | public class TwoSumII {
18 | /**
19 | * Main method
20 | *
21 | * @param args
22 | * @throws Exception
23 | */
24 | public static void main(String[] args) throws Exception {
25 | int[] nums = {2, 7, 11, 15};
26 | int[] result = new TwoSumII().twoSum(nums, 23);
27 | for (int i : result) System.out.println(i);
28 | }
29 |
30 | public int[] twoSum(int[] numbers, int target) {
31 | int i = 0, j = numbers.length - 1;
32 | while (i < j) {
33 | int x = (numbers[i] + numbers[j]);
34 | if (x == target) {
35 | int[] result = new int[2];
36 | result[0] = i + 1;
37 | result[1] = j + 1;
38 | return result;
39 | } else if (x < target) i++;
40 | else j--;
41 | }
42 | return new int[2];
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/backtracking/Combinations.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package backtracking;
3 |
4 | import java.util.ArrayList;
5 | import java.util.List;
6 |
7 | /**
8 | * Created by pradhang on 3/8/2017. Given two integers n and k, return all possible combinations of
9 | * k numbers out of 1 ... n.
10 | *
11 | * For example, If n = 4 and k = 2, a solution is:
12 | *
13 | * [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
14 | */
15 | public class Combinations {
16 |
17 | public static void main(String[] args) throws Exception {
18 | List For example, given n = 3, a solution set is:
12 | *
13 | * [ "((()))", "(()())", "(())()", "()(())", "()()()" ]
14 | */
15 | public class GenerateParentheses {
16 | public static void main(String[] args) throws Exception {
17 | System.out.println(new GenerateParentheses().generateParenthesis(4));
18 | }
19 |
20 | public List Return all possible palindrome partitioning of s.
12 | *
13 | * For example, given s = "aab", Return
14 | *
15 | * [ ["aa","b"], ["a","a","b"] ]
16 | */
17 | public class PalindromePartitioning {
18 | /**
19 | * Main method
20 | *
21 | * @param args
22 | * @throws Exception
23 | */
24 | public static void main(String[] args) throws Exception {
25 | List For example, [1,2,3] have the following permutations: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1],
12 | * [3,1,2], [3,2,1] ]
13 | */
14 | public class Permutations {
15 | /**
16 | * Main method
17 | *
18 | * @param args
19 | * @throws Exception
20 | */
21 | public static void main(String[] args) throws Exception {
22 | int[] nums = {1, 2, 3};
23 | List For example, [1,1,2] have the following unique permutations: [ [1,1,2], [1,2,1], [2,1,1] ]
13 | */
14 | public class PermutationsII {
15 | public static void main(String[] args) {
16 | int[] A = {1, 2, 2};
17 | System.out.println(new PermutationsII().permuteUnique(A));
18 | }
19 |
20 | public List Note: The solution set must not contain duplicate subsets.
12 | *
13 | * For example, If nums = [1,2,3], a solution is:
14 | *
15 | * [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
16 | */
17 | public class Subsets {
18 | /**
19 | * Main method
20 | *
21 | * @param args
22 | * @throws Exception
23 | */
24 | public static void main(String[] args) throws Exception {
25 | int[] n = {1, 2, 3};
26 | List Note: The solution set must not contain duplicate subsets.
13 | *
14 | * For example, If nums = [1,2,2], a solution is:
15 | *
16 | * [ [2], [1], [1,2,2], [2,2], [1,2], [] ]
17 | */
18 | public class SubsetsII {
19 | /**
20 | * Main method
21 | *
22 | * @param args
23 | * @throws Exception
24 | */
25 | public static void main(String[] args) throws Exception {
26 | int[] n = {1, 2, 3};
27 | List Find out how many ways to assign symbols to make sum of integers equal to target S.
10 | *
11 | * Example 1: Input: nums is [1, 1, 1, 1, 1], S is 3. Output: 5 Explanation:
12 | *
13 | * -1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3
14 | *
15 | * There are 5 ways to assign symbols to make the sum of nums be target 3. Note: The length of
16 | * the given array is positive and will not exceed 20. The sum of elements in the given array will
17 | * not exceed 1000. Your output answer is guaranteed to be fitted in a 32-bit integer.
18 | */
19 | public class TargetSum {
20 |
21 | private static int n;
22 | /**
23 | * Main method
24 | *
25 | * @param args
26 | * @throws Exception
27 | */
28 | public static void main(String[] args) throws Exception {
29 | int[] A = {1, 1, 1, 1, 1};
30 | n = 0;
31 | new TargetSum().findTargetSumWays(A, 3);
32 | System.out.println(n);
33 | }
34 |
35 | public int findTargetSumWays(int[] nums, int S) {
36 | backtrack(nums, S, 0, 0);
37 | return n;
38 | }
39 |
40 | private void backtrack(int[] nums, int target, int sum, int i) {
41 | if (i == nums.length) {
42 | if (sum == target) {
43 | n++;
44 | }
45 | } else {
46 | backtrack(nums, target, sum + nums[i], i + 1);
47 | backtrack(nums, target, sum - nums[i], i + 1);
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/main/java/binary_search/ArmstrongNumber.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package binary_search;
3 |
4 | import java.util.*;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 26/11/2019 The k-digit number N is an Armstrong number if and
8 | * only if the k-th power of each digit sums to N.
9 | *
10 | * Given a positive integer N, return true if and only if it is an Armstrong number.
11 | *
12 | * Example 1:
13 | *
14 | * Input: 153 Output: true Explanation: 153 is a 3-digit number, and 153 = 1^3 + 5^3 + 3^3.
15 | * Example 2:
16 | *
17 | * Input: 123 Output: false Explanation: 123 is a 3-digit number, and 123 != 1^3 + 2^3 + 3^3 =
18 | * 36.
19 | *
20 | * Note:
21 | *
22 | * 1 <= N <= 10^8
23 | */
24 | public class ArmstrongNumber {
25 | public static void main(String[] args) {
26 | //
27 | }
28 |
29 | public boolean isArmstrong(int N) {
30 | int s = String.valueOf(N).length();
31 | long sum = 0;
32 | for (char c : String.valueOf(N).toCharArray()) {
33 | int i = Integer.parseInt(String.valueOf(c));
34 | sum += power(i, s);
35 | }
36 | return (sum == N);
37 | }
38 |
39 | private long power(int n, int p) {
40 | long res = 1L;
41 | for (int i = 0; i < p; i++) {
42 | res *= n;
43 | }
44 | return res;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/binary_search/FirstBadVersion.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package binary_search;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 29/11/2017.
6 | *
7 | * You are a product manager and currently leading a team to develop a new product.
8 | * Unfortunately, the latest version of your product fails the quality check. Since each version is
9 | * developed based on the previous version, all the versions after a bad version are also bad.
10 | *
11 | * Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which
12 | * causes all the following ones to be bad.
13 | *
14 | * You are given an API bool isBadVersion(version) which will return whether version is bad.
15 | * Implement a function to find the first bad version. You should minimize the number of calls to
16 | * the API.
17 | */
18 | public class FirstBadVersion {
19 | public static void main(String[] args) throws Exception {
20 | System.out.println(new FirstBadVersion().firstBadVersion(2126753390));
21 | }
22 |
23 | public int firstBadVersion(int n) {
24 | int low = 0, high = n;
25 | while (low < high) {
26 | int mid = (low + high) >>> 1;
27 | if (isBadVersion(mid)) {
28 | high = mid;
29 | } else low = mid + 1;
30 | }
31 | return high;
32 | }
33 |
34 | private boolean isBadVersion(int n) {
35 | if (n >= 1702766719) return true;
36 | return false;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/binary_search/HIndexII.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package binary_search;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 11/12/2017.
6 | *
7 | * Follow up for H-Index: What if the citations array is sorted in ascending order? Could you
8 | * optimize your algorithm?
9 | *
10 | * @see array.HIndex
11 | */
12 | public class HIndexII {
13 | /**
14 | * Main method
15 | *
16 | * @param args
17 | * @throws Exception
18 | */
19 | public static void main(String[] args) throws Exception {
20 | int[] A = {1, 1, 1, 1, 1, 15, 20};
21 | System.out.println(new HIndexII().hIndex(A));
22 | }
23 |
24 | public int hIndex(int[] citations) {
25 | if (citations.length == 0) return 0;
26 | int s = 0, e = citations.length;
27 | int ans = -1;
28 | while (s < e) {
29 | int m = (s + e) >>> 1;
30 | int cit = citations.length - m;
31 | if (citations[m] > cit) {
32 | if (ans < cit) {
33 | ans = cit;
34 | }
35 | e = m;
36 | } else {
37 | if (ans < citations[m]) {
38 | ans = citations[m];
39 | }
40 | s = m + 1;
41 | }
42 | }
43 | return ans;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/binary_search/MinSortedRotatedArray.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package binary_search;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 10/04/2017. Suppose an array sorted in ascending order is
6 | * rotated at some pivot unknown to you beforehand.
7 | *
8 | * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
9 | *
10 | * Find the minimum element.
11 | *
12 | * You may assume no duplicate exists in the array.
13 | */
14 | public class MinSortedRotatedArray {
15 | /**
16 | * Main method
17 | *
18 | * @param args
19 | * @throws Exception
20 | */
21 | public static void main(String[] args) throws Exception {
22 | int[] A = {5, 1, 2, 3, 4};
23 | System.out.println(new MinSortedRotatedArray().findMin(A));
24 | }
25 |
26 | public int findMin(int[] nums) {
27 | if (nums.length == 0) return 0;
28 | else if (nums.length == 1) return nums[0];
29 | int low = 0, high = nums.length - 1;
30 | while (low < high) {
31 | int mid = (low + high) / 2;
32 | if (mid > 0 && nums[mid] < nums[mid - 1]) return nums[mid];
33 | if (nums[low] > nums[mid]) high = mid - 1;
34 | else if (nums[high] < nums[mid]) low = mid + 1;
35 | else high = mid - 1;
36 | }
37 | return nums[low];
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/binary_search/PowXN.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package binary_search;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 23/05/2017.
6 | *
7 | * Implement pow(x, n).
8 | *
9 | * Solution: Works with O(log n)
10 | */
11 | public class PowXN {
12 | /**
13 | * Main method
14 | *
15 | * @param args
16 | * @throws Exception
17 | */
18 | public static void main(String[] args) throws Exception {
19 | System.out.println(1 / new PowXN().myPow(2.00000, -2147483648));
20 | }
21 |
22 | public double myPow(double x, int n) {
23 | if (n == 0) return 1D;
24 | long N = n; // use long to avoid overflow.
25 | return solve(n < 0 ? (1 / x) : x, N < 0 ? (N * -1) : N);
26 | }
27 |
28 | public double solve(double x, long n) {
29 | if (n == 1) return x;
30 | double val = solve(x, n / 2);
31 | return val * val * ((n % 2) == 0 ? 1 : x);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/binary_search/SearchInsertPosition.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package binary_search;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 22/05/2017. Given a sorted array and a target value, return the
6 | * index if the target is found. If not, return the index where it would be if it were inserted in
7 | * order.
8 | *
9 | * You may assume no duplicates in the array.
10 | *
11 | * Here are few examples. [1,3,5,6], 5 → 2 [1,3,5,6], 2 → 1 [1,3,5,6], 7 → 4 [1,3,5,6], 0 → 0
12 | */
13 | public class SearchInsertPosition {
14 | public static void main(String[] args) throws Exception {
15 | int[] A = {1, 3, 5, 6};
16 | new SearchInsertPosition().searchInsert(A, 5);
17 | }
18 |
19 | public int searchInsert(int[] nums, int target) {
20 | int pos = nums.length;
21 | int s = 0, e = nums.length - 1;
22 | while (s <= e) {
23 | int m = s + (e - s) / 2;
24 | if (nums[m] >= target) {
25 | pos = m;
26 | e = m - 1;
27 | } else s = m + 1;
28 | }
29 | return pos;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/binary_search/SearchRotatedSortedArray.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package binary_search;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 10/04/2017. Suppose an array sorted in ascending order is
6 | * rotated at some pivot unknown to you beforehand.
7 | *
8 | * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
9 | *
10 | * You are given a target value to search. If found in the array return its index, otherwise
11 | * return -1.
12 | *
13 | * You may assume no duplicate exists in the array.
14 | */
15 | public class SearchRotatedSortedArray {
16 | /**
17 | * Main method
18 | *
19 | * @param args
20 | * @throws Exception
21 | */
22 | public static void main(String[] args) throws Exception {
23 | int[] A = {5, 4, 3, 2, 1};
24 | System.out.println(new SearchRotatedSortedArray().search(A, 4));
25 | }
26 |
27 | public int search(int[] nums, int target) {
28 | if (nums.length == 0) return -1;
29 | if (nums.length == 1) {
30 | return (nums[0] == target) ? 0 : -1;
31 | }
32 | int low = 0, high = nums.length - 1;
33 | while (low < high) {
34 | int mid = (low + high) >>> 1;
35 | if (nums[mid] == target) return mid;
36 | if ((nums[mid] <= nums[low]) && (target > nums[mid] && target <= nums[high])
37 | || (nums[low] <= nums[mid] && (target < nums[low] || target > nums[mid]))) low = mid + 1;
38 | else high = mid - 1;
39 | }
40 | return (nums[low] == target) ? low : -1;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/binary_search/SqrtX.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package binary_search;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 22/05/2017. Implement int sqrt(int x).
6 | *
7 | * Compute and return the square root of x.
8 | */
9 | public class SqrtX {
10 | public static void main(String[] args) throws Exception {
11 | System.out.println(new SqrtX().mySqrt(Integer.MAX_VALUE));
12 | }
13 |
14 | public int mySqrt(int x) {
15 | int s = 0, e = x;
16 | long ans = 0L;
17 | while (s <= e) {
18 | long m = s + (e - s) / 2;
19 | long prod = m * m;
20 | if (prod <= x) {
21 | s = (int) (m + 1);
22 | ans = m;
23 | } else e = (int) m - 1;
24 | }
25 | return (int) ans;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/bit_manipulation/BinaryNumberWithAlternatingBits.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package bit_manipulation;
3 | /**
4 | * Created by gouthamvidyapradhan on 28/05/2019\ Given a positive integer, check whether it has
5 | * alternating bits: namely, if two adjacent bits will always have different values.
6 | *
7 | * Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Example
8 | * 2: Input: 7 Output: False Explanation: The binary representation of 7 is: 111. Example 3: Input:
9 | * 11 Output: False Explanation: The binary representation of 11 is: 1011. Example 4: Input: 10
10 | * Output: True Explanation: The binary representation of 10 is: 1010.
11 | */
12 | public class BinaryNumberWithAlternatingBits {
13 | public static void main(String[] args) {
14 | System.out.println(new BinaryNumberWithAlternatingBits().hasAlternatingBits(18));
15 | }
16 |
17 | public boolean hasAlternatingBits(int n) {
18 | int curr = n & 1;
19 | int pos = 0;
20 | for (int i = 0; i < 32; i++) {
21 | if ((n & (1 << i)) > 0) {
22 | pos = i;
23 | }
24 | }
25 |
26 | for (int i = 1; i <= pos; i++) {
27 | int temp = (1 << i) & n;
28 | if ((temp > 0 && curr > 0) || (temp == 0 && curr == 0)) return false;
29 | curr = temp;
30 | }
31 | return true;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/bit_manipulation/DivideTwoIntegers.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package bit_manipulation;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 13/02/2018. Divide two integers without using multiplication,
6 | * division and mod operator.
7 | *
8 | * If it is overflow, return MAX_INT.
9 | */
10 | public class DivideTwoIntegers {
11 |
12 | /**
13 | * Main method
14 | *
15 | * @param args
16 | * @throws Exception
17 | */
18 | public static void main(String[] args) throws Exception {
19 | System.out.println(new DivideTwoIntegers().divide(0, 775));
20 | }
21 |
22 | public int divide(int dividend, int divisor) {
23 | if (divisor == 0) return Integer.MAX_VALUE;
24 | else if (dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;
25 | else if (divisor == 1) return dividend;
26 | boolean isNegative = ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0));
27 | dividend = (dividend < 0) ? -dividend : dividend;
28 | divisor = (divisor < 0) ? -divisor : divisor;
29 | int sum, result = 0;
30 | while (true) {
31 | int d1 = divisor;
32 | sum = 0;
33 | if (dividend - d1 == 0) {
34 | sum += 1;
35 | result += sum;
36 | break;
37 | }
38 | if (dividend - d1 < 0) break;
39 | while (dividend - (d1 << 1) > 0) {
40 | d1 <<= 1;
41 | sum += 1;
42 | }
43 | result += (1 << sum);
44 | dividend = dividend - d1;
45 | }
46 | return isNegative ? -result : result;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/bit_manipulation/GrayCode.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package bit_manipulation;
3 |
4 | import java.util.ArrayList;
5 | import java.util.List;
6 |
7 | /**
8 | * Created by gouthamvidyapradhan on 16/03/2017. The gray code is a binary numeral system where two
9 | * successive values differ in only one bit.
10 | *
11 | * Given a non-negative integer n representing the total number of bits in the code, print the
12 | * sequence of gray code. A gray code sequence must begin with 0.
13 | *
14 | * For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
15 | *
16 | * 00 - 0 01 - 1 11 - 3 10 - 2 Note: For a given n, a gray code sequence is not uniquely defined.
17 | *
18 | * For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.
19 | *
20 | * For now, the judge is able to judge based on one instance of gray code sequence. Sorry about
21 | * that.
22 | */
23 | public class GrayCode {
24 |
25 | /**
26 | * Main method
27 | *
28 | * @param args
29 | * @throws Exception
30 | */
31 | public static void main(String[] args) throws Exception {
32 | List Given two integers x and y, calculate the Hamming distance.
9 | *
10 | * Note: 0 ≤ x, y < 231.
11 | *
12 | * Example:
13 | *
14 | * Input: x = 1, y = 4
15 | *
16 | * Output: 2
17 | *
18 | * Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑
19 | *
20 | * The above arrows point to positions where the corresponding bits are different.
21 | *
22 | * Solution O(1): XOR (x, y) and count the number of bits set
23 | */
24 | public class HammingDistance {
25 |
26 | /**
27 | * Main method
28 | *
29 | * @param args
30 | * @throws Exception
31 | */
32 | public static void main(String[] args) throws Exception {}
33 |
34 | public int hammingDistance(int x, int y) {
35 | int z = (x ^ y);
36 | int count = 0;
37 | for (int i = 0; i < 31; i++) {
38 | if ((z & (1 << i)) > 0) {
39 | count++;
40 | }
41 | }
42 | return count;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/bit_manipulation/TotalHammingDistance.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package bit_manipulation;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 01/12/2017. The Hamming distance between two integers is the
6 | * number of positions at which the corresponding bits are different.
7 | *
8 | * Now your job is to find the total Hamming distance between all pairs of the given numbers.
9 | *
10 | * Example: Input: 4, 14, 2
11 | *
12 | * Output: 6
13 | *
14 | * Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing
15 | * the four bits relevant in this case). So the answer will be: HammingDistance(4, 14) +
16 | * HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. Note: Elements of the given array
17 | * are in the range of 0 to 10^9 Length of the array will not exceed 10^4.
18 | *
19 | * Solution: O(N * 32): Count the number of set bits in each of 32 bit positions and then take
20 | * the sum of product of number of set bits x number of un-set bits
21 | */
22 | public class TotalHammingDistance {
23 | /**
24 | * Main method
25 | *
26 | * @param args
27 | * @throws Exception
28 | */
29 | public static void main(String[] args) throws Exception {
30 | int[] A = {1000000000, 4, 14, 2};
31 | System.out.println(new TotalHammingDistance().totalHammingDistance(A));
32 | }
33 |
34 | public int totalHammingDistance(int[] nums) {
35 | int sum = 0;
36 | for (int i = 0; i < 32; i++) {
37 | int numOfOnes = 0;
38 | int p = (1 << i);
39 | for (int num : nums) {
40 | if ((num & p) > 0) {
41 | numOfOnes++;
42 | }
43 | }
44 | sum += ((nums.length - numOfOnes) * numOfOnes);
45 | }
46 | return sum;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/depth_first_search/FloodFill.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package depth_first_search;
3 |
4 | import java.util.*;
5 |
6 | /** Created by gouthamvidyapradhan on 29/01/2020 */
7 | public class FloodFill {
8 | final int[] R = {1, -1, 0, 0};
9 | final int[] C = {0, 0, -1, 1};
10 |
11 | public static void main(String[] args) {
12 | //
13 | }
14 |
15 | boolean done[][];
16 |
17 | public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
18 | done = new boolean[image.length][image[0].length];
19 | int[][] copy = new int[image.length][image[0].length];
20 | for (int i = 0; i < image.length; i++) {
21 | for (int j = 0; j < image[0].length; j++) {
22 | copy[i][j] = image[i][j];
23 | }
24 | }
25 | dfs(copy, sr, sc, image[sr][sc], newColor);
26 | return copy;
27 | }
28 |
29 | private void dfs(int[][] image, int r, int c, int c1, int c2) {
30 | done[r][c] = true;
31 | image[r][c] = c2;
32 | for (int i = 0; i < 4; i++) {
33 | int newR = r + R[i];
34 | int newC = c + C[i];
35 | if (newR >= 0
36 | && newC >= 0
37 | && newR < image.length
38 | && newC < image[0].length
39 | && image[newR][newC] == c1
40 | && !done[newR][newC]) {
41 | dfs(image, newR, newC, c1, c2);
42 | }
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/depth_first_search/MovieRecommend.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package depth_first_search;
3 |
4 | import java.util.*;
5 |
6 | /** Created by gouthamvidyapradhan on 25/02/2017. Accepted */
7 | public class MovieRecommend {
8 | Set Example 1:
11 | *
12 | * 11110 11010 11000 00000 Answer: 1
13 | *
14 | * Example 2:
15 | *
16 | * 11000 11000 00100 00011 Answer: 3
17 | */
18 | public class NumberOfIslands {
19 | int[] R = {0, 0, 1, -1};
20 | int[] C = {1, -1, 0, 0};
21 | private static int M, N;
22 | private static char temp[][];
23 |
24 | public int numIslands(char[][] grid) {
25 | M = grid.length;
26 | if (M == 0) return 0;
27 | N = grid[0].length;
28 | temp = new char[M][N];
29 | int count = 0;
30 |
31 | for (int i = 0; i < M; i++) {
32 | System.arraycopy(grid[i], 0, temp[i], 0, N);
33 | }
34 |
35 | for (int i = 0; i < M; i++) {
36 | for (int j = 0; j < N; j++) {
37 | if (temp[i][j] == '1') {
38 | ++count;
39 | dfs(i, j);
40 | }
41 | }
42 | }
43 |
44 | return count;
45 | }
46 |
47 | private void dfs(int r, int c) {
48 | temp[r][c] = '0';
49 | for (int i = 0; i < 4; i++) {
50 | int newR = r + R[i];
51 | int newC = c + C[i];
52 | if (newR >= 0 && newC >= 0 && newR < M && newC < N) {
53 | if (temp[newR][newC] != '0') // not visited
54 | {
55 | dfs(newR, newC);
56 | }
57 | }
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/design/EncodeAndDecodeTinyURL.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package design;
3 |
4 | import java.util.ArrayList;
5 | import java.util.List;
6 |
7 | /**
8 | * Created by gouthamvidyapradhan on 11/04/2017. TinyURL is a URL shortening service where you enter
9 | * a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as
10 | * http://tinyurl.com/4e9iAk.
11 | *
12 | * Design the encode and decode methods for the TinyURL service. There is no restriction on how
13 | * your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a
14 | * tiny URL and the tiny URL can be decoded to the original URL.
15 | */
16 | public class EncodeAndDecodeTinyURL {
17 | private List For example, Given [3,2,1,5,6,4] and k = 2, return 5.
9 | *
10 | * Note: You may assume k is always valid, 1 ≤ k ≤ array's length.
11 | */
12 | public class KthLargestElementInAnArray {
13 | /**
14 | * Main method
15 | *
16 | * @param args
17 | * @throws Exception
18 | */
19 | public static void main(String[] args) throws Exception {
20 | int[] nums = {3, 2, 1, 5, 6, 4};
21 |
22 | System.out.println(new KthLargestElementInAnArray().findKthLargest(nums, 6));
23 | }
24 |
25 | private int findKthLargest(int[] nums, int k) {
26 | return solve(nums, 0, nums.length - 1, k);
27 | }
28 |
29 | private int solve(int[] nums, int pIndex, int end, int k) {
30 | int pivot = nums[end];
31 | int temp;
32 | int start = pIndex;
33 | for (int i = pIndex; i < end; i++) {
34 | if (nums[i] <= pivot) {
35 | temp = nums[i];
36 | nums[i] = nums[pIndex];
37 | nums[pIndex] = temp;
38 | pIndex += 1;
39 | }
40 | }
41 | temp = nums[pIndex];
42 | nums[pIndex] = nums[end];
43 | nums[end] = temp;
44 |
45 | int pos = (end - pIndex) + 1;
46 | if (pos == k) return nums[pIndex];
47 | else if (pos > k) {
48 | return solve(nums, pIndex + 1, end, k);
49 | } else {
50 | return solve(nums, start, pIndex - 1, k - pos);
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/divide_and_conquer/SearchA2DMatrix.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package divide_and_conquer;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 09/03/2017. Write an efficient algorithm that searches for a
6 | * value in an m x n matrix. This matrix has the following properties:
7 | *
8 | * Integers in each row are sorted in ascending from left to right. Integers in each column are
9 | * sorted in ascending from top to bottom. For example,
10 | *
11 | * Consider the following matrix:
12 | *
13 | * [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23,
14 | * 26, 30] ] Given target = 5, return true.
15 | *
16 | * Given target = 20, return false.
17 | */
18 | public class SearchA2DMatrix {
19 | /**
20 | * Main method
21 | *
22 | * @param args
23 | * @throws Exception
24 | */
25 | public static void main(String[] args) throws Exception {
26 | int[][] matrix = {
27 | {1, 3, 5, 7, 9}, // 1, 3, 5, 7, 9
28 | {2, 4, 6, 8, 10}, // 2, 4, 6, 8, 10
29 | {11, 13, 15, 17, 19}, // 11, 15, 17, 18, 19
30 | {12, 14, 16, 18, 20}, // 13, 20, 21, 22, 23
31 | {21, 22, 23, 24, 25} // 14, 25, 26, 27, 28
32 | };
33 |
34 | System.out.println(new SearchA2DMatrix().searchMatrix(matrix, 11));
35 | }
36 |
37 | private boolean searchMatrix(int[][] matrix, int target) {
38 | if (matrix.length == 0) return false;
39 | int M = matrix.length;
40 | int N = matrix[0].length;
41 | int r = 0, c = N - 1;
42 | while (r < M && c >= 0) {
43 | if (matrix[r][c] == target) return true;
44 | else if (target < matrix[r][c]) --c;
45 | else if (target > matrix[r][c]) r++;
46 | }
47 | return false;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/BestTimeToBuyAndSellStocks.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 17/03/2017. Say you have an array for which the ith element is
6 | * the price of a given stock on day i.
7 | *
8 | * If you were only permitted to complete at most one transaction (ie, buy one and sell one share
9 | * of the stock), design an algorithm to find the maximum profit.
10 | *
11 | * Example 1: Input: [7, 1, 5, 3, 6, 4] Output: 5
12 | *
13 | * max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
14 | * Example 2: Input: [7, 6, 4, 3, 1] Output: 0
15 | *
16 | * In this case, no transaction is done, i.e. max profit = 0.
17 | */
18 | public class BestTimeToBuyAndSellStocks {
19 | /**
20 | * Main method
21 | *
22 | * @param args
23 | * @throws Exception
24 | */
25 | public static void main(String[] args) throws Exception {
26 | int[] prices = {1, 1, 1, 1, 1};
27 | System.out.println(new BestTimeToBuyAndSellStocks().maxProfit(prices));
28 | }
29 |
30 | public int maxProfit(int[] prices) {
31 | if (prices.length == 0) return 0;
32 | int[] max = new int[prices.length];
33 | max[prices.length - 1] = prices[prices.length - 1];
34 | for (int i = prices.length - 2; i >= 0; i--) {
35 | max[i] = Math.max(prices[i], max[i + 1]);
36 | }
37 | int result = Integer.MIN_VALUE;
38 | for (int i = 0, l = max.length; i < l; i++) {
39 | result = Math.max(result, max[i] - prices[i]);
40 | }
41 | return result;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/ClimbingStairs.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 01/04/2017. You are climbing a stair case. It takes n steps to
6 | * reach to the top.
7 | *
8 | * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the
9 | * top?
10 | *
11 | * Note: Given n will be a positive integer.
12 | */
13 | public class ClimbingStairs {
14 | /**
15 | * Main method
16 | *
17 | * @param args
18 | * @throws Exception
19 | */
20 | public static void main(String[] args) throws Exception {}
21 |
22 | public int climbStairs(int n) {
23 | if (n == 0 || n == 1) return 1;
24 | int[] A = new int[n + 1];
25 | A[n] = 1;
26 | A[n - 1] = 1;
27 | for (int i = n - 2; i >= 0; i--) A[i] = A[i + 1] + A[i + 2];
28 | return A[0];
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/CombinationSumIV.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | import java.util.Arrays;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 17/12/2017. Given an integer array with all positive numbers
8 | * and no duplicates, find the number of possible combinations that add up to a positive integer
9 | * target.
10 | *
11 | * Example:
12 | *
13 | * nums = [1, 2, 3] target = 4
14 | *
15 | * The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2)
16 | * (3, 1)
17 | *
18 | * Note that different sequences are counted as different combinations.
19 | *
20 | * Therefore the output is 7. Follow up: What if negative numbers are allowed in the given array?
21 | * How does it change the problem? What limitation we need to add to the question to allow negative
22 | * numbers?
23 | *
24 | * Solution: Backtrack and dp
25 | */
26 | public class CombinationSumIV {
27 |
28 | /**
29 | * Main method
30 | *
31 | * @param args
32 | * @throws Exception
33 | */
34 | public static void main(String[] args) throws Exception {
35 | int[] A = {1, 2, 3};
36 | System.out.println(new CombinationSumIV().combinationSum4(A, 4));
37 | }
38 |
39 | public int combinationSum4(int[] nums, int target) {
40 | int[] dp = new int[target + 1];
41 | Arrays.fill(dp, -1);
42 | dp[0] = 1;
43 | return backtrack(nums, dp, target);
44 | }
45 |
46 | private int backtrack(int[] nums, int[] dp, int sum) {
47 | int total = 0;
48 | if (sum < 0) return 0;
49 | if (dp[sum] != -1) return dp[sum];
50 | else {
51 | for (int num : nums) {
52 | total += backtrack(nums, dp, sum - num);
53 | }
54 | }
55 | dp[sum] = total;
56 | return dp[sum];
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/ConstrainedSubsequenceSum.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | import java.util.*;
5 |
6 | /** Created by gouthamvidyapradhan on 14/05/2020 */
7 | public class ConstrainedSubsequenceSum {
8 |
9 | public static void main(String[] args) {
10 | int[] A = {10, -2, -10, -5, 20};
11 | System.out.println(new ConstrainedSubsequenceSum().constrainedSubsetSum(A, 2));
12 | }
13 |
14 | class Node {
15 | int v, i;
16 |
17 | public int getV() {
18 | return v;
19 | }
20 |
21 | public int getI() {
22 | return i;
23 | }
24 |
25 | Node(int v, int i) {
26 | this.v = v;
27 | this.i = i;
28 | }
29 | }
30 |
31 | public int constrainedSubsetSum(int[] nums, int k) {
32 | Queue 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing digits, determine the
9 | * total number of ways to decode it.
10 | *
11 | * For example, Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
12 | *
13 | * The number of ways decoding "12" is 2.
14 | */
15 | public class DecodeWays {
16 | /**
17 | * Main method
18 | *
19 | * @param args
20 | * @throws Exception
21 | */
22 | public static void main(String[] args) throws Exception {
23 | System.out.println(new DecodeWays().numDecodings("3120"));
24 | }
25 |
26 | public int numDecodings(String s) {
27 | if (s == null || s.isEmpty()) return 0;
28 | int[] dp = new int[s.length() + 2];
29 | dp[s.length()] = 1;
30 | dp[s.length() + 1] = 1;
31 | for (int i = s.length() - 1; i >= 0; i--) {
32 | for (int j = i + 1; j < i + 3; j++) {
33 | if (j <= s.length()) {
34 | String subStr = s.substring(i, j);
35 | if (!subStr.startsWith("0")) {
36 | int intVal = Integer.parseInt(subStr);
37 | if (intVal <= 26) {
38 | dp[i] += dp[j];
39 | }
40 | }
41 | }
42 | }
43 | }
44 | return dp[0];
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/DistinctSubsequencesII.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 | /**
4 | * Created by gouthamvidyapradhan on 08/05/2020 Given a string S, count the number of distinct,
5 | * non-empty subsequences of S .
6 | *
7 | * Since the result may be large, return the answer modulo 10^9 + 7.
8 | *
9 | * Example 1:
10 | *
11 | * Input: "abc" Output: 7 Explanation: The 7 distinct subsequences are "a", "b", "c", "ab", "ac",
12 | * "bc", and "abc". Example 2:
13 | *
14 | * Input: "aba" Output: 6 Explanation: The 6 distinct subsequences are "a", "b", "ab", "ba", "aa"
15 | * and "aba". Example 3:
16 | *
17 | * Input: "aaa" Output: 3 Explanation: The 3 distinct subsequences are "a", "aa" and "aaa".
18 | *
19 | * Note:
20 | *
21 | * S contains only lowercase letters. 1 <= S.length <= 2000
22 | */
23 | public class DistinctSubsequencesII {
24 | public static void main(String[] args) {
25 | System.out.println(new DistinctSubsequencesII().distinctSubseqII("abac"));
26 | }
27 |
28 | final int MOD = (int) 1e9 + 7;
29 |
30 | public int distinctSubseqII(String S) {
31 | int[] DP = new int[S.length() + 1];
32 | DP[S.length()] = 1;
33 | for (int i = S.length() - 1; i >= 0; i--) {
34 | int sum = 0;
35 | for (int j = i + 1; j <= S.length(); j++) {
36 | sum = ((sum + DP[j]) % MOD);
37 | if (j < S.length() && S.charAt(j) == S.charAt(i)) {
38 | break;
39 | }
40 | }
41 | DP[i] = sum;
42 | }
43 | int ans = 0;
44 | for (int i : DP) {
45 | ans = ((ans + i) % MOD);
46 | }
47 | return ans - 1;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/HouseRobber.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | /**
5 | * Created by pradhang on 4/3/2017. You are a professional robber planning to rob houses along a
6 | * street. Each house has a certain amount of money stashed, the only constraint stopping you from
7 | * robbing each of them is that adjacent houses have security system connected and it will
8 | * automatically contact the police if two adjacent houses were broken into on the same night.
9 | *
10 | * Given a list of non-negative integers representing the amount of money of each house,
11 | * determine the maximum amount of money you can rob tonight without alerting the police.
12 | */
13 | public class HouseRobber {
14 | private int[] max;
15 |
16 | /**
17 | * Main method
18 | *
19 | * @param args
20 | * @throws Exception
21 | */
22 | public static void main(String[] args) throws Exception {}
23 |
24 | public int rob(int[] nums) {
25 | if (nums.length == 0) return 0;
26 | max = new int[nums.length];
27 | if (nums.length == 1) return nums[0];
28 | max[nums.length - 1] = nums[nums.length - 1];
29 | max[nums.length - 2] = Math.max(nums[nums.length - 1], nums[nums.length - 2]);
30 | for (int i = nums.length - 3; i >= 0; i--) {
31 | max[i] = Math.max(max[i + 1], nums[i] + max[i + 2]);
32 | }
33 | return max[0];
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/InterleavingString.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 | /**
4 | * Created by gouthamvidyapradhan on 30/01/2020 Given s1, s2, s3, find whether s3 is formed by the
5 | * interleaving of s1 and s2.
6 | *
7 | * Example 1:
8 | *
9 | * Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" Output: true Example 2:
10 | *
11 | * Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" Output: false
12 | */
13 | public class InterleavingString {
14 | public static void main(String[] args) {
15 | System.out.println(new InterleavingString().isInterleave("aabcc", "aabcc", "aabcaabccc"));
16 | }
17 |
18 | public boolean isInterleave(String s1, String s2, String s3) {
19 | boolean[][] DP = new boolean[s1.length() + 1][s2.length() + 1];
20 | DP[0][0] = true;
21 | if (s3.length() != (s2.length() + s1.length())) return false;
22 | for (int i = 0; i <= s1.length(); i++) {
23 | for (int j = 0; j <= s2.length(); j++) {
24 | if (i == 0 && j == 0) continue;
25 | int index = (i + j);
26 | if (j > 0) {
27 | if (s3.charAt(index - 1) == s2.charAt(j - 1) && DP[i][j - 1]) {
28 | DP[i][j] = true;
29 | }
30 | }
31 | if (i > 0) {
32 | if (s3.charAt(index - 1) == s1.charAt(i - 1) && DP[i - 1][j]) {
33 | DP[i][j] = true;
34 | }
35 | }
36 | }
37 | }
38 | return DP[s1.length()][s2.length()];
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/LongestIncreasingSubsequence.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 02/04/2017. Given an unsorted array of integers, find the
6 | * length of longest increasing subsequence.
7 | *
8 | * For example, Given [10, 9, 2, 5, 3, 7, 101, 18], The longest increasing subsequence is [2, 3,
9 | * 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is
10 | * only necessary for you to return the length.
11 | *
12 | * Your algorithm should run in O(n2) complexity.
13 | *
14 | * Follow up: Could you improve it to O(n log n) time complexity?
15 | */
16 | public class LongestIncreasingSubsequence {
17 | /**
18 | * Main method
19 | *
20 | * @param args
21 | * @throws Exception
22 | */
23 | public static void main(String[] args) throws Exception {
24 | int[] nums = {9, 8, 7, 6};
25 | System.out.println(new LongestIncreasingSubsequence().lengthOfLIS(nums));
26 | }
27 |
28 | public int lengthOfLIS(int[] nums) {
29 | if (nums.length == 0) return 0;
30 | int[] A = new int[nums.length];
31 | int max = Integer.MIN_VALUE;
32 | for (int i = 0, l = nums.length; i < l; i++) {
33 | int lis = 1;
34 | for (int j = 0; j < i; j++) {
35 | if (nums[i] > nums[j]) lis = Math.max(lis, A[j] + 1);
36 | }
37 | A[i] = lis;
38 | max = Math.max(max, A[i]);
39 | }
40 | return max;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/LongestPaliandromicSubstring.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 24/02/2017. Given a string s, find the longest palindromic
6 | * substring in s. You may assume that the maximum length of s is 1000.
7 | *
8 | * Example:
9 | *
10 | * Input: "babad"
11 | *
12 | * Output: "bab"
13 | *
14 | * Note: "aba" is also a valid answer. Example:
15 | *
16 | * Input: "cbbd"
17 | *
18 | * Output: "bb"
19 | */
20 | public class LongestPaliandromicSubstring {
21 | /**
22 | * Main method
23 | *
24 | * @param args
25 | * @throws Exception
26 | */
27 | public static void main(String[] args) throws Exception {
28 | System.out.println(new LongestPaliandromicSubstring().longestPalindrome("forgeeksskeegfor"));
29 | }
30 |
31 | public String longestPalindrome(String s) {
32 | int l = s.length();
33 | int startIndex = 0;
34 | int maxLen = 1;
35 | boolean[][] A = new boolean[l][l];
36 | for (int i = 0, j = 0; i < l; i++, j++) A[i][j] = true;
37 |
38 | for (int i = 0, j = i + 1; j < l; i++, j++) {
39 | if (s.charAt(i) == s.charAt(j)) {
40 | A[i][j] = true;
41 | startIndex = i;
42 | maxLen = 2;
43 | }
44 | }
45 |
46 | for (int k = 3; k <= l; k++) {
47 | for (int i = 0, j = k - 1; j < l; i++, j++) {
48 | if (s.charAt(i) == s.charAt(j)) {
49 | A[i][j] = A[i + 1][j - 1];
50 | if (A[i][j]) {
51 | if (k > maxLen) {
52 | startIndex = i;
53 | maxLen = k;
54 | }
55 | }
56 | }
57 | }
58 | }
59 |
60 | return s.substring(startIndex, startIndex + maxLen);
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/LongestPalindromicSubsequence.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 27/03/2017. Given an unsorted array of integers, find the
6 | * length of longest increasing subsequence.
7 | *
8 | * For example, Given [10, 9, 2, 5, 3, 7, 101, 18], The longest increasing subsequence is [2, 3,
9 | * 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is
10 | * only necessary for you to return the length.
11 | *
12 | * Your algorithm should run in O(n2) complexity.
13 | *
14 | * Follow up: Could you improve it to O(n log n) time complexity?
15 | */
16 | public class LongestPalindromicSubsequence {
17 | /**
18 | * Main method
19 | *
20 | * @param args
21 | * @throws Exception
22 | */
23 | public static void main(String[] args) throws Exception {
24 | System.out.println(new LongestPalindromicSubsequence().longestPalindromeSubseq("bbbab"));
25 | }
26 |
27 | public int longestPalindromeSubseq(String s) {
28 | int[][] dp = new int[s.length() + 1][s.length() + 1];
29 | String sI = new StringBuilder(s).reverse().toString();
30 | for (int i = 1, l = s.length(); i <= l; i++)
31 | for (int j = 1; j <= l; j++) {
32 | dp[i][j] =
33 | (s.charAt(i - 1) == sI.charAt(j - 1))
34 | ? dp[i - 1][j - 1] + 1
35 | : Math.max(dp[i - 1][j], dp[i][j - 1]);
36 | }
37 |
38 | return dp[s.length()][s.length()];
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/MaximumProductSubarray.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 02/04/2017. Find the contiguous subarray within an array
6 | * (containing at least one number) which has the largest product.
7 | *
8 | * For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product
9 | * = 6.
10 | */
11 | public class MaximumProductSubarray {
12 | /**
13 | * Main method
14 | *
15 | * @param args
16 | * @throws Exception
17 | */
18 | public static void main(String[] args) throws Exception {
19 | int[] A = {2, 3, -2, 4};
20 | System.out.println(new MaximumProductSubarray().maxProduct(A));
21 | }
22 |
23 | public int maxProduct(int[] nums) {
24 | if (nums.length == 1) return nums[0];
25 | int min = nums[0];
26 | int max = nums[0];
27 | int result = max;
28 | for (int i = 1; i < nums.length; i++) {
29 | int prevMin = min, prevMax = max;
30 | min = Math.min(nums[i], Math.min(nums[i] * prevMin, nums[i] * prevMax));
31 | max = Math.max(nums[i], Math.max(nums[i] * prevMin, nums[i] * prevMax));
32 | result = Math.max(result, max);
33 | }
34 | return result;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/MaximumSubarray.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 07/07/2017. Find the contiguous subarray within an array
6 | * (containing at least one number) which has the largest sum.
7 | *
8 | * For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has
9 | * the largest sum = 6.
10 | */
11 | public class MaximumSubarray {
12 | public static void main(String[] args) throws Exception {
13 | int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
14 | System.out.println(new MaximumSubarray().maxSubArray(nums));
15 | }
16 |
17 | public int maxSubArray(int[] nums) {
18 | if (nums.length == 1) return nums[0];
19 | int max = nums[nums.length - 1];
20 | for (int i = nums.length - 2; i >= 0; i--) {
21 | nums[i] = Math.max(nums[i], nums[i] + nums[i + 1]);
22 | max = Math.max(max, nums[i]);
23 | }
24 | return max;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/MinCostClimbingStairs.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 30/04/2018. On a staircase, the i-th step has some non-negative
6 | * cost cost[i] assigned (0 indexed).
7 | *
8 | * Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to
9 | * reach the top of the floor, and you can either start from the step with index 0, or the step with
10 | * index 1.
11 | *
12 | * Example 1: Input: cost = [10, 15, 20] Output: 15 Explanation: Cheapest is start on cost[1],
13 | * pay that cost and go to the top. Example 2: Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
14 | * Output: 6 Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3]. Note:
15 | * cost will have a length in the range [2, 1000]. Every cost[i] will be an integer in the range [0,
16 | * 999].
17 | *
18 | * Solution: O(N) At every step there are two options, either cost[i] + cost[i + 1] or cost[i] +
19 | * cost[i + 2]
20 | */
21 | public class MinCostClimbingStairs {
22 | public static void main(String[] args) throws Exception {}
23 |
24 | public int minCostClimbingStairs(int[] cost) {
25 | for (int i = cost.length - 1; i >= 0; i--) {
26 | if (i + 1 < cost.length && i + 2 < cost.length) {
27 | cost[i] = Math.min(cost[i] + cost[i + 1], cost[i] + cost[i + 2]);
28 | }
29 | }
30 | return Math.min(cost[0], cost[1]);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/NumberOfMusicPlaylists.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | import java.util.Arrays;
5 |
6 | /** Created by gouthamvidyapradhan on 13/06/2020 */
7 | public class NumberOfMusicPlaylists {
8 | public static void main(String[] args) {
9 | //
10 | }
11 |
12 | int[][] DP;
13 | final int MOD = (int) 1e9 + 7;
14 |
15 | public int numMusicPlaylists(int N, int L, int K) {
16 | DP = new int[L + 1][N + 1];
17 | for (int i = 0; i <= L; i++) {
18 | Arrays.fill(DP[i], -1);
19 | }
20 | DP[0][0] = 1;
21 | return (int) dp(L, N, K, N);
22 | }
23 |
24 | private long dp(int i, int j, int K, int N) {
25 | if (i < j) return 0;
26 | else if (i < 0 || j < 0) return 0;
27 | else if (DP[i][j] != -1) return DP[i][j];
28 | else {
29 | long sum = 0L;
30 | sum += ((dp(i - 1, j - 1, K, N) * (N - (j - 1))) % MOD);
31 | sum += (dp(i - 1, j, K, N) * (Math.max(j - K, 0)) % MOD);
32 | DP[i][j] = (int) (sum % MOD);
33 | return DP[i][j];
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/PalindromeRemoval.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 12/05/2020 Given an integer array arr, in one move you can
6 | * select a palindromic subarray arr[i], arr[i+1], ..., arr[j] where i <= j, and remove that
7 | * subarray from the given array. Note that after removing a subarray, the elements on the left and
8 | * on the right of that subarray move to fill the gap left by the removal.
9 | *
10 | * Return the minimum number of moves needed to remove all numbers from the array.
11 | *
12 | * Example 1:
13 | *
14 | * Input: arr = [1,2] Output: 2 Example 2:
15 | *
16 | * Input: arr = [1,3,4,1,5] Output: 3 Explanation: Remove [4] then remove [1,3,1] then remove
17 | * [5].
18 | *
19 | * Constraints:
20 | *
21 | * 1 <= arr.length <= 100 1 <= arr[i] <= 20
22 | */
23 | public class PalindromeRemoval {
24 | public static void main(String[] args) {
25 | int[] A = {1, 3, 1, 2, 4, 2};
26 | System.out.println(new PalindromeRemoval().minimumMoves(A));
27 | }
28 |
29 | int[][] DP;
30 |
31 | public int minimumMoves(int[] arr) {
32 | DP = new int[arr.length][arr.length];
33 | return dp(0, arr.length - 1, arr);
34 | }
35 |
36 | private int dp(int i, int j, int[] arr) {
37 | if (i > j) return 1;
38 | else if (DP[i][j] != 0) return DP[i][j];
39 | else {
40 | int min = Integer.MAX_VALUE;
41 | for (int t = j; t >= i; t--) {
42 | if (arr[i] == arr[t]) {
43 | min = Math.min(min, dp(i + 1, t - 1, arr) + ((t + 1 > j) ? 0 : dp(t + 1, j, arr)));
44 | }
45 | }
46 | DP[i][j] = min;
47 | return min;
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/TossStrangeCoins.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 19/11/2019 You have some coins. The i-th coin has a probability
6 | * prob[i] of facing heads when tossed.
7 | *
8 | * Return the probability that the number of coins facing heads equals target if you toss every
9 | * coin exactly once.
10 | *
11 | * Example 1:
12 | *
13 | * Input: prob = [0.4], target = 1 Output: 0.40000 Example 2:
14 | *
15 | * Input: prob = [0.5,0.5,0.5,0.5,0.5], target = 0 Output: 0.03125
16 | */
17 | public class TossStrangeCoins {
18 | public static void main(String[] args) {
19 | double[] A = {0.4, 0.4};
20 | System.out.println(new TossStrangeCoins().probabilityOfHeads(A, 1));
21 | }
22 |
23 | public double probabilityOfHeads(double[] prob, int target) {
24 | double[][] DP = new double[target + 1][prob.length];
25 | DP[0][0] = 1 - prob[0];
26 | DP[1][0] = prob[0];
27 | for (int c = 1; c < prob.length; c++) {
28 | for (int t = 0; t <= target; t++) {
29 | if (t == 0) DP[t][c] = DP[t][c - 1] * (1 - prob[c]);
30 | else DP[t][c] = DP[t][c - 1] * (1 - prob[c]) + DP[t - 1][c - 1] * (prob[c]);
31 | }
32 | }
33 | return DP[target][prob.length - 1];
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/TwoKeysKeyboard.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 19/08/2017. Initially on a notepad only one character 'A' is
6 | * present. You can perform two operations on this notepad for each step:
7 | *
8 | * Copy All: You can copy all the characters present on the notepad (partial copy is not
9 | * allowed). Paste: You can paste the characters which are copied last time. Given a number n. You
10 | * have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted.
11 | * Output the minimum number of steps to get n 'A'.
12 | *
13 | * Example 1: Input: 3 Output: 3 Explanation: Intitally, we have one character 'A'. In step 1, we
14 | * use Copy All operation. In step 2, we use Paste operation to get 'AA'. In step 3, we use Paste
15 | * operation to get 'AAA'.
16 | *
17 | * Note: The n will be in the range [1, 1000].
18 | */
19 | public class TwoKeysKeyboard {
20 | /**
21 | * Main method
22 | *
23 | * @param args
24 | * @throws Exception
25 | */
26 | public static void main(String[] args) throws Exception {
27 | System.out.println(new TwoKeysKeyboard().minSteps(8));
28 | }
29 |
30 | public int minSteps(int n) {
31 | int[] DP = new int[n + 1];
32 | for (int i = 2; i <= n; i++) {
33 | DP[i] = i;
34 | for (int j = 2; j < i; j++) {
35 | if ((i % j) == 0) {
36 | DP[i] = Math.min(DP[i], DP[j] + (i / j));
37 | }
38 | }
39 | }
40 | return DP[n];
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/UniqueBinarySearchTrees.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 31/03/2017. Given n, how many structurally unique BST's (binary
6 | * search trees) that store values 1...n?
7 | *
8 | * For example, Given n = 3, there are a total of 5 unique BST's.
9 | *
10 | * 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
11 | */
12 | public class UniqueBinarySearchTrees {
13 | int[] dp;
14 |
15 | /**
16 | * Main method
17 | *
18 | * @param args
19 | */
20 | public static void main(String[] args) throws Exception {
21 | System.out.println(new UniqueBinarySearchTrees().numTrees(5));
22 | }
23 |
24 | public int numTrees(int n) {
25 | dp = new int[n + 1];
26 | dp[0] = 1;
27 | return dp(n);
28 | }
29 |
30 | private int dp(int n) {
31 | if (dp[n] != 0) return dp[n];
32 | for (int i = 1; i <= n; i++) {
33 | dp[n] += dp(n - i) * dp(n - (n - i) - 1);
34 | }
35 | return dp[n];
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/dynamic_programming/ValidPalindromeIII.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package dynamic_programming;
3 |
4 | import java.util.Arrays;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 23/04/2020 Given a string s and an integer k, find out if the
8 | * given string is a K-Palindrome or not.
9 | *
10 | * A string is K-Palindrome if it can be transformed into a palindrome by removing at most k
11 | * characters from it.
12 | *
13 | * Example 1:
14 | *
15 | * Input: s = "abcdeca", k = 2 Output: true Explanation: Remove 'b' and 'e' characters.
16 | *
17 | * Constraints:
18 | *
19 | * 1 <= s.length <= 1000 s has only lowercase English letters. 1 <= k <= s.length
20 | */
21 | public class ValidPalindromeIII {
22 | public static void main(String[] args) {
23 | System.out.println(new ValidPalindromeIII().isValidPalindrome("abc", 0));
24 | }
25 |
26 | int[][] DP;
27 |
28 | public boolean isValidPalindrome(String s, int k) {
29 | DP = new int[s.length()][s.length()];
30 | for (int i = 0; i < s.length(); i++) {
31 | Arrays.fill(DP[i], -1);
32 | }
33 | return dp(0, s.length() - 1, s) <= k;
34 | }
35 |
36 | private int dp(int i, int j, String S) {
37 | if (i == j) return 0;
38 | else if (i > j) return 0;
39 | else if (DP[i][j] != -1) return DP[i][j];
40 | else {
41 | int min = Integer.MAX_VALUE;
42 | if (S.charAt(i) != S.charAt(j)) {
43 | min = Math.min(min, Math.min(dp(i + 1, j, S), dp(i, j - 1, S)) + 1);
44 | } else {
45 | min = dp(i + 1, j - 1, S);
46 | }
47 | DP[i][j] = min;
48 | return min;
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/greedy/GasStation.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package greedy;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 28/06/2017. There are N gas stations along a circular route,
6 | * where the amount of gas at station i is gas[i].
7 | *
8 | * You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i
9 | * to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
10 | *
11 | * Return the starting gas station's index if you can travel around the circuit once, otherwise
12 | * return -1.
13 | *
14 | * Note: The solution is guaranteed to be unique.
15 | *
16 | * Solution: O(N) If point B cant be reached from point A then all the intermediate points
17 | * between A and B cant be the starting point. Therefore reset the starting point to the new
18 | * starting point.
19 | */
20 | public class GasStation {
21 | /**
22 | * Main method
23 | *
24 | * @param args
25 | * @throws Exception
26 | */
27 | public static void main(String[] args) throws Exception {
28 | int[] gas = {10, 20, 30, 10};
29 | int[] cost = {5, 30, 10, 10};
30 | System.out.println(new GasStation().canCompleteCircuit(gas, cost));
31 | }
32 |
33 | public int canCompleteCircuit(int[] gas, int[] cost) {
34 | int debt = 0, sum = 0, start = 0;
35 | for (int i = 0; i < gas.length; i++) {
36 | sum += gas[i] - cost[i];
37 | if (sum < 0) {
38 | debt += sum;
39 | sum = 0;
40 | start = i + 1;
41 | }
42 | }
43 | debt += sum;
44 | return debt >= 0 ? start : -1;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/greedy/JumpGame.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package greedy;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 17/03/2017. Given an array of non-negative integers, you are
6 | * initially positioned at the first index of the array.
7 | *
8 | * Each element in the array represents your maximum jump length at that position.
9 | *
10 | * Determine if you are able to reach the last index.
11 | *
12 | * For example: A = [2,3,1,1,4], return true.
13 | *
14 | * A = [3,2,1,0,4], return false.
15 | */
16 | public class JumpGame {
17 | /**
18 | * Main method
19 | *
20 | * @param args
21 | * @throws Exception
22 | */
23 | public static void main(String[] args) throws Exception {
24 | int[] nums = {1, 2, 1, 0, 4};
25 | System.out.println(new JumpGame().canJump(nums));
26 | }
27 |
28 | public boolean canJump(int[] nums) {
29 | if (nums.length == 0) return false;
30 | int min = nums.length - 1, max = nums.length - 1;
31 | for (int i = nums.length - 2; i >= 0; i--) {
32 | if ((nums[i] + i) >= min) min = i;
33 | }
34 | return (min == 0);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/greedy/JumpGameII.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package greedy;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 02/04/2017. Given an array of non-negative integers, you are
6 | * initially positioned at the first index of the array.
7 | *
8 | * Each element in the array represents your maximum jump length at that position.
9 | *
10 | * Your goal is to reach the last index in the minimum number of jumps.
11 | *
12 | * For example: Given array A = [2,3,1,1,4]
13 | *
14 | * The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then
15 | * 3 steps to the last index.)
16 | *
17 | * Note: You can assume that you can always reach the last index.
18 | */
19 | public class JumpGameII {
20 | /**
21 | * Main method
22 | *
23 | * @param args
24 | * @throws Exception
25 | */
26 | public static void main(String[] args) throws Exception {}
27 |
28 | public int jump(int[] nums) {
29 | int step = 0;
30 | int e = 0, max = 0;
31 | for (int i = 0; i < nums.length - 1; i++) {
32 | max = Math.max(max, i + nums[i]);
33 | if (i == e) {
34 | step++;
35 | e = max;
36 | }
37 | }
38 | return step;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/greedy/PartitionLabels.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package greedy;
3 |
4 | import java.util.*;
5 |
6 | /** Created by gouthamvidyapradhan on 30/11/2019 */
7 | public class PartitionLabels {
8 | public static void main(String[] args) {
9 | System.out.println(new PartitionLabels().partitionLabels("ababcbacadefegdehijhklij"));
10 | }
11 |
12 | public List Note: The number of people is less than 1,100.
14 | *
15 | * Example
16 | *
17 | * Input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
18 | *
19 | * Output: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
20 | */
21 | public class QueueReconstructionByHeight {
22 | public static void main(String[] args) throws Exception {
23 | int[][] A = {{7, 0}, {4, 4}, {7, 1}, {5, 0}, {6, 1}, {5, 2}};
24 | int[][] r = new QueueReconstructionByHeight().reconstructQueue(A);
25 | for (int[] i : r) {
26 | System.out.println(i[0] + " " + i[1]);
27 | }
28 | }
29 |
30 | public int[][] reconstructQueue(int[][] people) {
31 | Arrays.sort(people, ((o1, o2) -> (o2[0] - o1[0] == 0) ? o1[1] - o2[1] : o2[0] - o1[0]));
32 | LinkedList The length of the given array is in range [2, 10,000], and will be even. The number in given
19 | * array is in range [-100,000, 100,000].
20 | *
21 | * Solution: O(N) Use a HashSet to identify all the different possible candies. The maximum types
22 | * of candies sister can get is always Min(N/2, Number Of Unique Type of Candies)
23 | */
24 | public class DistributeCandies {
25 | public static void main(String[] args) {}
26 |
27 | public int distributeCandies(int[] candies) {
28 | int N = candies.length;
29 | Set If no integer occurs once, return -1.
11 | *
12 | * Example 1:
13 | *
14 | * Input: [5,7,3,9,4,9,8,3,1] Output: 8 Explanation: The maximum integer in the array is 9 but it
15 | * is repeated. The number 8 occurs only once, so it's the answer. Example 2:
16 | *
17 | * Input: [9,9,8,8] Output: -1 Explanation: There is no number that occurs only once.
18 | *
19 | * Note:
20 | *
21 | * 1 <= A.length <= 2000 0 <= A[i] <= 1000
22 | */
23 | public class LargestUniqueNumber {
24 | public static void main(String[] args) {
25 | //
26 | }
27 |
28 | public int largestUniqueNumber(int[] A) {
29 | Map You may assume that each input would have exactly one solution, and you may not use the same
11 | * element twice.
12 | *
13 | * Example: Given nums = [2, 7, 11, 15], target = 9,
14 | *
15 | * Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
16 | */
17 | public class TwoSum {
18 | HashMap For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", return false.
9 | *
10 | * Note: You may assume the string contains only lowercase alphabets.
11 | *
12 | * Follow up: What if the inputs contain unicode characters? How would you adapt your solution to
13 | * such case?
14 | */
15 | public class ValidAnagram {
16 | private int[] S = new int[256];
17 | private int[] T = new int[256];
18 |
19 | /**
20 | * Main method
21 | *
22 | * @param args
23 | * @throws Exception
24 | */
25 | public static void main(String[] args) throws Exception {
26 | System.out.println(new ValidAnagram().isAnagram("anagram", "nagaram"));
27 | }
28 |
29 | public boolean isAnagram(String s, String t) {
30 | if (s.length() != t.length()) return false;
31 |
32 | for (int i = 0, l = s.length(); i < l; i++) {
33 | S[s.charAt(i)]++;
34 | }
35 |
36 | for (int i = 0, l = t.length(); i < l; i++) {
37 | T[t.charAt(i)]++;
38 | }
39 |
40 | for (int i = 0; i < 256; i++) {
41 | if (S[i] != T[i]) return false;
42 | }
43 |
44 | return true;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/linked_list/DeleteNode.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package linked_list;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 04/07/2017. Write a function to delete a node (except the tail)
6 | * in a singly linked list, given only access to that node.
7 | *
8 | * Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3,
9 | * the linked list should become 1 -> 2 -> 4 after calling your function.
10 | */
11 | public class DeleteNode {
12 | public static class ListNode {
13 | int val;
14 | ListNode next;
15 |
16 | ListNode(int x) {
17 | val = x;
18 | }
19 | }
20 |
21 | public static void main(String[] args) {
22 | ListNode node = new ListNode(1);
23 | node.next = new ListNode(2);
24 | node.next.next = new ListNode(3);
25 | node.next.next.next = new ListNode(4);
26 | new DeleteNode().deleteNode(node.next.next);
27 | while (node != null) {
28 | System.out.println(node.val);
29 | node = node.next;
30 | }
31 | }
32 |
33 | public void deleteNode(ListNode node) {
34 | ListNode prev = node;
35 | ListNode last = node;
36 | ListNode next = node.next;
37 | while (next != null) {
38 | last = prev;
39 | int temp = prev.val;
40 | prev.val = next.val;
41 | next.val = temp;
42 | prev = prev.next;
43 | next = next.next;
44 | }
45 | last.next = null;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/linked_list/LinkedListCycle.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package linked_list;
3 |
4 | import java.util.HashSet;
5 | import java.util.Set;
6 |
7 | /**
8 | * Created by gouthamvidyapradhan on 23/02/2017. Given a linked list, determine if it has a cycle in
9 | * it.
10 | *
11 | * Follow up: Can you solve it without using extra space?
12 | */
13 | public class LinkedListCycle {
14 | private static Set If there are two middle nodes, return the second middle node.
9 | *
10 | * Example 1:
11 | *
12 | * Input: [1,2,3,4,5] Output: Node 3 from this list (Serialization: [3,4,5]) The returned node
13 | * has value 3. (The judge's serialization of this node is [3,4,5]). Note that we returned a
14 | * ListNode object ans, such that: ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and
15 | * ans.next.next.next = NULL. Example 2:
16 | *
17 | * Input: [1,2,3,4,5,6] Output: Node 4 from this list (Serialization: [4,5,6]) Since the list has
18 | * two middle nodes with values 3 and 4, we return the second one.
19 | *
20 | * Solution: O(N) Return the middle node. middle = count / 2
21 | */
22 | public class MiddleOfLinkedList {
23 |
24 | public class ListNode {
25 | int val;
26 | ListNode next;
27 |
28 | ListNode(int x) {
29 | val = x;
30 | }
31 | }
32 | /**
33 | * Main method
34 | *
35 | * @param args
36 | */
37 | public static void main(String[] args) {}
38 |
39 | public ListNode middleNode(ListNode head) {
40 | int count = 0;
41 | ListNode temp = head;
42 | while (temp != null) {
43 | temp = temp.next;
44 | count++;
45 | }
46 | int mid = count / 2;
47 | int c = 0;
48 | while (head != null && c < mid) {
49 | head = head.next;
50 | c++;
51 | }
52 | return head;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/linked_list/ReverseLinkedList.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package linked_list;
3 |
4 | /** Created by gouthamvidyapradhan on 24/02/2017. Reverse a singly linked list. */
5 | public class ReverseLinkedList {
6 | private ListNode newHead;
7 |
8 | public static class ListNode {
9 | int val;
10 | ListNode next;
11 |
12 | ListNode(int x) {
13 | val = x;
14 | next = null;
15 | }
16 | }
17 |
18 | /**
19 | * Main method
20 | *
21 | * @param args
22 | * @throws Exception
23 | */
24 | public static void main(String[] args) throws Exception {
25 | ListNode node1 = new ListNode(1);
26 | ListNode node2 = new ListNode(2);
27 | ListNode node3 = new ListNode(3);
28 | ListNode node4 = new ListNode(4);
29 | ListNode node5 = new ListNode(5);
30 | ListNode node6 = new ListNode(6);
31 | node1.next = node2;
32 | node2.next = node3;
33 | node3.next = node4;
34 | node4.next = node5;
35 | // node5.next = node6;
36 | ListNode newNode = new ReverseLinkedList().reverseList(node1);
37 | System.out.println(newNode.val);
38 | }
39 |
40 | public ListNode reverseList(ListNode head) {
41 | if (head == null) return null;
42 | else if (head.next == null) return head;
43 | reverse(head).next = null;
44 | return newHead;
45 | }
46 |
47 | private ListNode reverse(ListNode head) {
48 | if (head.next == null) {
49 | newHead = head;
50 | return head;
51 | }
52 | ListNode node = reverse(head.next);
53 | node.next = head;
54 | return head;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/main/java/linked_list/SwapNodesInPairs.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package linked_list;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 13/08/2017. Given a linked list, swap every two adjacent nodes
6 | * and return its head.
7 | *
8 | * For example, Given 1->2->3->4, you should return the list as 2->1->4->3.
9 | *
10 | * Your algorithm should use only constant space. You may not modify the values in the list, only
11 | * nodes itself can be changed.
12 | */
13 | public class SwapNodesInPairs {
14 |
15 | public static class ListNode {
16 | int val;
17 | ListNode next;
18 |
19 | ListNode(int x) {
20 | val = x;
21 | }
22 | }
23 |
24 | public static void main(String[] args) throws Exception {
25 | ListNode node = new ListNode(1);
26 | node.next = new ListNode(2);
27 | node.next.next = new ListNode(3);
28 | node.next.next.next = new ListNode(4);
29 | node.next.next.next.next = new ListNode(5);
30 | node.next.next.next.next.next = new ListNode(6);
31 | ListNode head = new SwapNodesInPairs().swapPairs(node);
32 | while (head != null) {
33 | System.out.println(head.val);
34 | head = head.next;
35 | }
36 | }
37 |
38 | public ListNode swapPairs(ListNode head) {
39 | if (head == null || head.next == null) return head;
40 | ListNode newHead = head.next;
41 | ListNode curr = head.next;
42 | ListNode prev = head;
43 | ListNode prevPrev = new ListNode(-1); // dummy node
44 | while (curr != null) {
45 | prev.next = curr.next;
46 | curr.next = prev;
47 | prevPrev.next = curr;
48 | if (prev.next != null) {
49 | curr = prev.next.next;
50 | prev = prev.next;
51 | prevPrev = prevPrev.next.next;
52 | } else {
53 | curr = null;
54 | }
55 | }
56 | return newHead;
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/main/java/math/AddDigits.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package math;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 02/08/2017. Given a non-negative integer num, repeatedly add
6 | * all its digits until the result has only one digit.
7 | *
8 | * For example:
9 | *
10 | * Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return
11 | * it.
12 | *
13 | * Follow up: Could you do it without any loop/recursion in O(1) runtime?
14 | */
15 | public class AddDigits {
16 |
17 | public static void main(String[] args) throws Exception {
18 | System.out.println(new AddDigits().addDigits(38));
19 | }
20 |
21 | public int addDigits(int num) {
22 | if (num == 0) return 0;
23 | return num % 9 == 0 ? 9 : num % 9;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/math/Base7.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package math;
3 |
4 | import java.util.*;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 01/08/2019 Given an integer, return its base 7 string
8 | * representation.
9 | *
10 | * Example 1: Input: 100 Output: "202" Example 2: Input: -7 Output: "-10" Note: The input will be
11 | * in range of [-1e7, 1e7].
12 | */
13 | public class Base7 {
14 | public static void main(String[] args) {
15 | //
16 | }
17 |
18 | public String convertToBase7(int num) {
19 | Integer.toString(7, 7);
20 | if (num == 0) return "0";
21 | int q = Math.abs(num), r;
22 | StringBuilder sb = new StringBuilder();
23 | while (q != 0) {
24 | r = q % 7;
25 | sb.append(r);
26 | q /= 7;
27 | }
28 | if (num < 0) {
29 | return "-" + sb.reverse().toString();
30 | } else return sb.reverse().toString();
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/math/BulbSwitcherII.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package math;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 08/09/2017. There is a room with n lights which are turned on
6 | * initially and 4 buttons on the wall. After performing exactly m unknown operations towards
7 | * buttons, you need to return how many different kinds of status of the n lights could be.
8 | *
9 | * Suppose n lights are labeled as number [1, 2, 3 ..., n], function of these 4 buttons are given
10 | * below:
11 | *
12 | * Flip all the lights. Flip lights with even numbers. Flip lights with odd numbers. Flip lights
13 | * with (3k + 1) numbers, k = 0, 1, 2, ...
14 | *
15 | * Example 1: Input: n = 1, m = 1. Output: 2 Explanation: Status can be: [on], [off]
16 | *
17 | * Example 2: Input: n = 2, m = 1. Output: 3 Explanation: Status can be: [on, off], [off, on],
18 | * [off, off]
19 | *
20 | * Example 3: Input: n = 3, m = 1. Output: 4 Explanation: Status can be: [off, on, off], [on,
21 | * off, on], [off, off, off], [off, on, on].
22 | *
23 | * Note: n and m both fit in range [0, 1000].
24 | */
25 | public class BulbSwitcherII {
26 |
27 | public static void main(String[] args) throws Exception {
28 | System.out.println(new BulbSwitcherII().flipLights(1, 1000));
29 | }
30 |
31 | public int flipLights(int n, int m) {
32 | if (n == 0 || m == 0) return 1;
33 | if (n == 1 && m >= 1) return 2;
34 | if (n == 2) {
35 | if (m == 1) return 3;
36 | if (m >= 2) return 4;
37 | } else if (n >= 3) {
38 | if (m == 1) return 4;
39 | if (m == 2) return 7;
40 | }
41 | return 8;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/math/CountPrimes.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package math;
3 |
4 | import java.util.BitSet;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 21/03/2017. Description:
8 | *
9 | * Count the number of prime numbers less than a non-negative number, n.
10 | */
11 | public class CountPrimes {
12 | /**
13 | * Main method
14 | *
15 | * @param args
16 | * @throws Exception
17 | */
18 | public static void main(String[] args) throws Exception {
19 | System.out.println(new CountPrimes().countPrimes(999187));
20 | }
21 |
22 | public int countPrimes(int n) {
23 | if (n == 0 || n == 1 || n == 2) return 0;
24 | else if (n == 3) return 1;
25 | BitSet set = new BitSet();
26 | n = n - 1;
27 | int sqRt = (int) Math.sqrt(n);
28 | int count = n;
29 | for (int i = 2; i <= sqRt; i++) {
30 | if (!set.get(i)) {
31 | for (int j = 2; (i * j) <= n; j++) {
32 | if (!set.get(i * j)) {
33 | count--;
34 | set.set(i * j);
35 | }
36 | }
37 | }
38 | }
39 | return count - 1;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/math/ExcelSheetColumnTitle.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package math;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 12/08/2017. Given a positive integer, return its corresponding
6 | * column title as appear in an Excel sheet.
7 | *
8 | * For example:
9 | *
10 | * 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB
11 | */
12 | public class ExcelSheetColumnTitle {
13 |
14 | private static final String CONST = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
15 |
16 | /**
17 | * Main method
18 | *
19 | * @param args
20 | * @throws Exception
21 | */
22 | public static void main(String[] args) throws Exception {
23 | System.out.println(new ExcelSheetColumnTitle().convertToTitle(52));
24 | }
25 |
26 | public String convertToTitle(int n) {
27 | StringBuilder ans = new StringBuilder();
28 | while (n > 0) {
29 | int mod = n % 26;
30 | n /= 26;
31 | if (mod == 0) {
32 | ans.append('Z');
33 | n -= 1;
34 | } else {
35 | ans.append(CONST.charAt(mod - 1));
36 | }
37 | }
38 | return ans.reverse().toString();
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/math/GlobalAndLocalInversions.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package math;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 01/02/2018.
6 | *
7 | * We have some permutation A of [0, 1, ..., N - 1], where N is the length of A.
8 | *
9 | * The number of (global) inversions is the number of i < j with 0 <= i < j < N and A[i] > A[j].
10 | *
11 | * The number of local inversions is the number of i with 0 <= i < N and A[i] > A[i+1].
12 | *
13 | * Return true if and only if the number of global inversions is equal to the number of local
14 | * inversions.
15 | *
16 | * Example 1:
17 | *
18 | * Input: A = [1,0,2] Output: true Explanation: There is 1 global inversion, and 1 local
19 | * inversion. Example 2:
20 | *
21 | * Input: A = [1,2,0] Output: false Explanation: There are 2 global inversions, and 1 local
22 | * inversion. Note:
23 | *
24 | * A will be a permutation of [0, 1, ..., A.length - 1]. A will have length in range [1, 5000].
25 | * The time limit for this problem has been reduced.
26 | *
27 | * Solution: O(N) For every i, Maintain a max value up until (i - 1). If the current element at i
28 | * < max value return false
29 | */
30 | public class GlobalAndLocalInversions {
31 | /**
32 | * Main method
33 | *
34 | * @param args
35 | * @throws Exception
36 | */
37 | public static void main(String[] args) throws Exception {}
38 |
39 | public boolean isIdealPermutation(int[] A) {
40 | if (A.length == 0 || A.length == 1) return true;
41 | int max = Integer.MIN_VALUE;
42 | for (int i = 1; i < A.length; i++) {
43 | if (A[i] < max) {
44 | return false;
45 | } else {
46 | max = Math.max(max, A[i - 1]);
47 | }
48 | }
49 | return true;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/math/NthDigit.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package math;
3 |
4 | /** Created by gouthamvidyapradhan on 05/11/2019 */
5 | public class NthDigit {
6 | public static void main(String[] args) {
7 | System.out.println(new NthDigit().findNthDigit(1000000000));
8 | }
9 |
10 | public int findNthDigit(int n) {
11 | if (n >= 1 && n <= 9) return n;
12 | long sum = 0L;
13 | for (int i = 0; ; i++) {
14 | long pow = (9 * (new Double(Math.pow(10, i)).longValue())) * (i + 1);
15 | sum += pow;
16 | if (sum >= n) {
17 | long diff = (long) n - (sum - pow);
18 | long num = diff / (i + 1);
19 | long mod = diff % (i + 1);
20 | long result = new Double(Math.pow(10, i)).intValue() + (num - 1) + (mod > 0 ? 1 : 0);
21 | String resultStr = String.valueOf(result);
22 | return (mod == 0)
23 | ? Integer.parseInt(String.valueOf(resultStr.charAt(resultStr.length() - 1)))
24 | : Integer.parseInt(String.valueOf(resultStr.charAt((int) mod - 1)));
25 | }
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/math/RangeAdditionII.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package math;
3 |
4 | import java.util.*;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 09/10/2019 Given an m * n matrix M initialized with all 0's and
8 | * several update operations.
9 | *
10 | * Operations are represented by a 2D array, and each operation is represented by an array with
11 | * two positive integers a and b, which means M[i][j] should be added by one for all 0 <= i < a and
12 | * 0 <= j < b.
13 | *
14 | * You need to count and return the number of maximum integers in the matrix after performing all
15 | * the operations.
16 | *
17 | * Example 1: Input: m = 3, n = 3 operations = [[2,2],[3,3]] Output: 4 Explanation: Initially, M
18 | * = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
19 | *
20 | * After performing [2,2], M = [[1, 1, 0], [1, 1, 0], [0, 0, 0]]
21 | *
22 | * After performing [3,3], M = [[2, 2, 1], [2, 2, 1], [1, 1, 1]]
23 | *
24 | * So the maximum integer in M is 2, and there are four of it in M. So return 4. Note: The range
25 | * of m and n is [1,40000]. The range of a is [1,m], and the range of b is [1,n]. The range of
26 | * operations size won't exceed 10,000.
27 | *
28 | * Solution: O(N) where N is the number of operations. For every operation, keep track of minimum
29 | * of each row and column and return the product of minR x minC
30 | */
31 | public class RangeAdditionII {
32 | public static void main(String[] args) {
33 | //
34 | }
35 |
36 | public int maxCount(int m, int n, int[][] ops) {
37 | int minR = m;
38 | int minC = n;
39 | for (int[] v : ops) {
40 | minR = Math.min(minR, v[0]);
41 | minC = Math.min(minC, v[1]);
42 | }
43 | return minR * minC;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/math/RectangleOverlap.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package math;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 30/11/2019 A rectangle is represented as a list [x1, y1, x2,
6 | * y2], where (x1, y1) are the coordinates of its bottom-left corner, and (x2, y2) are the
7 | * coordinates of its top-right corner.
8 | *
9 | * Two rectangles overlap if the area of their intersection is positive. To be clear, two
10 | * rectangles that only touch at the corner or edges do not overlap.
11 | *
12 | * Given two (axis-aligned) rectangles, return whether they overlap.
13 | *
14 | * Example 1:
15 | *
16 | * Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3] Output: true Example 2:
17 | *
18 | * Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1] Output: false Notes:
19 | *
20 | * Both rectangles rec1 and rec2 are lists of 4 integers. All coordinates in rectangles will be
21 | * between -10^9 and 10^9.
22 | */
23 | public class RectangleOverlap {
24 | public static void main(String[] args) {
25 | int[] A = {0, 0, 2, 2};
26 | int[] B = {1, 1, 3, 3};
27 | System.out.println(new RectangleOverlap().isRectangleOverlap(A, B));
28 | }
29 |
30 | public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
31 | boolean x =
32 | ((rec1[0] >= rec2[0] && rec1[0] < rec2[2]) || (rec2[0] >= rec1[0] && rec2[0] < rec1[2]));
33 | boolean y =
34 | ((rec1[1] >= rec2[1] && rec1[1] < rec2[3]) || (rec2[1] >= rec1[1] && rec2[1] < rec1[3]));
35 | return x && y;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/math/RomanToInteger.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package math;
3 |
4 | import java.util.HashMap;
5 | import java.util.Map;
6 |
7 | /**
8 | * Created by gouthamvidyapradhan on 12/08/2017.
9 | *
10 | * Given a roman numeral, convert it to an integer.
11 | *
12 | * Input is guaranteed to be within the range from 1 to 3999.
13 | */
14 | public class RomanToInteger {
15 | /**
16 | * Main method
17 | *
18 | * @param args
19 | * @throws Exception
20 | */
21 | public static void main(String[] args) throws Exception {
22 | System.out.println(new RomanToInteger().romanToInt("DXCIX"));
23 | }
24 |
25 | public int romanToInt(String s) {
26 | Map Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a
9 | * "rotation function" F on A as follow:
10 | *
11 | * F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1].
12 | *
13 | * Calculate the maximum value of F(0), F(1), ..., F(n-1).
14 | *
15 | * Note: n is guaranteed to be less than 105.
16 | *
17 | * Example:
18 | *
19 | * A = [4, 3, 2, 6]
20 | *
21 | * F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 * 6) + (1 * 4) +
22 | * (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 +
23 | * 9 = 23 F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
24 | *
25 | * So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
26 | */
27 | public class RotateFunction {
28 | /**
29 | * Main method
30 | *
31 | * @param args
32 | * @throws Exception
33 | */
34 | public static void main(String[] args) throws Exception {
35 | int[] a = {4, 3, 2, 6};
36 | System.out.println(new RotateFunction().maxRotateFunction(a));
37 | }
38 |
39 | public int maxRotateFunction(int[] A) {
40 | if (A.length == 0 || A.length == 1) return 0;
41 | int max = Integer.MIN_VALUE;
42 | int l = A.length;
43 | int sum = 0, prodSum = 0;
44 | for (int i = 0; i < l; i++) {
45 | prodSum += (A[i] * i);
46 | sum += A[i];
47 | }
48 | max = Math.max(max, prodSum);
49 | for (int i = 0; i < l - 1; i++) {
50 | prodSum = (prodSum - sum + A[i] + ((l - 1) * A[i]));
51 | max = Math.max(max, prodSum);
52 | }
53 | return max;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/math/SmallestRangeI.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package math;
3 |
4 | import java.util.*;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 22/08/2019 Given an array A of integers, for each integer A[i]
8 | * we may choose any x with -K <= x <= K, and add x to A[i].
9 | *
10 | * After this process, we have some array B.
11 | *
12 | * Return the smallest possible difference between the maximum value of B and the minimum value
13 | * of B.
14 | *
15 | * Example 1:
16 | *
17 | * Input: A = [1], K = 0 Output: 0 Explanation: B = [1] Example 2:
18 | *
19 | * Input: A = [0,10], K = 2 Output: 6 Explanation: B = [2,8] Example 3:
20 | *
21 | * Input: A = [1,3,6], K = 3 Output: 0 Explanation: B = [3,3,3] or B = [4,4,4]
22 | *
23 | * Note:
24 | *
25 | * 1 <= A.length <= 10000 0 <= A[i] <= 10000 0 <= K <= 10000
26 | */
27 | public class SmallestRangeI {
28 | public static void main(String[] args) {
29 | //
30 | }
31 |
32 | public int smallestRangeI(int[] A, int K) {
33 | Arrays.sort(A);
34 | if (A.length == 0 || A.length == 1) return 0;
35 | else {
36 | int low = A[0];
37 | int high = A[A.length - 1];
38 | int l = low + (K);
39 | int r = high - (K);
40 | if (r > l) return r - l;
41 | else return 0;
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/math/WaterAndJugProblem.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package math;
3 |
4 | import java.math.BigInteger;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 29/07/2017. You are given two jugs with capacities x and y
8 | * litres. There is an infinite amount of water supply available. You need to determine whether it
9 | * is possible to measure exactly z litres using these two jugs.
10 | *
11 | * If z liters of water is measurable, you must have z liters of water contained within one or
12 | * both buckets by the end.
13 | *
14 | * Operations allowed:
15 | *
16 | * Fill any of the jugs completely with water. Empty any of the jugs. Pour water from one jug
17 | * into another till the other jug is completely full or the first jug itself is empty. Example 1:
18 | * (From the famous "Die Hard" example)
19 | *
20 | * Input: x = 3, y = 5, z = 4 Output: True Example 2:
21 | *
22 | * Input: x = 2, y = 6, z = 5 Output: False
23 | */
24 | public class WaterAndJugProblem {
25 | /**
26 | * Main method
27 | *
28 | * @param args
29 | * @throws Exception
30 | */
31 | public static void main(String[] args) throws Exception {
32 | System.out.println(new WaterAndJugProblem().canMeasureWater(0, 0, 1));
33 | }
34 |
35 | public boolean canMeasureWater(int x, int y, int z) {
36 | if (x == y && y == z) return true;
37 | if (z > (x + y)) return false;
38 | BigInteger b1 = new BigInteger(String.valueOf(x));
39 | BigInteger b2 = new BigInteger(String.valueOf(y));
40 | BigInteger b3 = b1.gcd(b2);
41 | return b3.intValue() != 0 && (z % b3.intValue()) == 0;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/reservoir_sampling/RandomPickIndex.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package reservoir_sampling;
3 |
4 | import java.util.Random;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 10/12/2017. Given an array of integers with possible
8 | * duplicates, randomly output the index of a given target number. You can assume that the given
9 | * target number must exist in the array.
10 | *
11 | * Note: The array size can be very large. Solution that uses too much extra space will not pass
12 | * the judge.
13 | *
14 | * Example:
15 | *
16 | * int[] nums = new int[] {1,2,3,3,3}; Solution solution = new Solution(nums);
17 | *
18 | * // pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal
19 | * probability of returning. solution.pick(3);
20 | *
21 | * // pick(1) should return 0. Since in the array only nums[0] is equal to 1. solution.pick(1);
22 | */
23 | public class RandomPickIndex {
24 |
25 | private int[] nums;
26 | /**
27 | * Main method
28 | *
29 | * @param args
30 | * @throws Exception
31 | */
32 | public static void main(String[] args) throws Exception {
33 | int[] A = {1, 2, 3, 3, 3};
34 | System.out.println(new RandomPickIndex(A).pick(1));
35 | }
36 |
37 | public RandomPickIndex(int[] nums) {
38 | this.nums = nums;
39 | }
40 |
41 | public int pick(int target) {
42 | int count = 0;
43 | for (int num : nums) {
44 | if (num == target) {
45 | count++;
46 | }
47 | }
48 | Random random = new Random();
49 | int nPick = 1 + random.nextInt(count);
50 | count = 0;
51 | for (int i = 0; i < nums.length; i++) {
52 | if (nums[i] == target) {
53 | if (++count == nPick) {
54 | return i;
55 | }
56 | }
57 | }
58 | return 0; // this is impossible
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/stack/ValidParentheses.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package stack;
3 |
4 | import java.util.HashMap;
5 | import java.util.Map;
6 | import java.util.Stack;
7 |
8 | /**
9 | * Created by gouthamvidyapradhan on 25/02/2017. Given a string containing just the characters '(',
10 | * ')', '{', '}', '[' and ']', determine if the input string is valid.
11 | *
12 | * The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and
13 | * "([)]" are not.
14 | */
15 | public class ValidParentheses {
16 | public static void main(String[] args) {
17 | System.out.println(hasBalancedBrackets("(h[e"));
18 | }
19 |
20 | private static Map Given two binary strings, return their sum (also a binary string).
8 | *
9 | * For example, a = "11" b = "1" Return "100".
10 | */
11 | public class AddBinary {
12 |
13 | /**
14 | * Main method
15 | *
16 | * @param args
17 | */
18 | public static void main(String[] args) {
19 | System.out.println(new AddBinary().addBinary("000001010000101001", "0"));
20 | }
21 |
22 | public String addBinary(String a, String b) {
23 | if (a.length() > b.length()) {
24 | return calculate(a, b);
25 | } else return calculate(b, a);
26 | }
27 |
28 | /**
29 | * Calculate sum
30 | *
31 | * @param a length of a should always be greater or equal to b
32 | * @param b length of b should always be smaller of equal to a
33 | * @return
34 | */
35 | private String calculate(String a, String b) {
36 | int carry = 0;
37 | int d = a.length() - b.length();
38 | StringBuilder sb = new StringBuilder();
39 | for (int i = a.length() - 1; i >= 0; i--) {
40 | int first = Integer.parseInt(String.valueOf(a.charAt(i)));
41 | int second = i - d >= 0 ? Integer.parseInt(String.valueOf(b.charAt(i - d))) : 0;
42 | int sum = (first + second + carry);
43 | carry = sum / 2;
44 | sb.append(sum % 2);
45 | }
46 | if (carry != 0) sb.append(carry);
47 | return sb.reverse().toString();
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/string/CountAndSay.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package string;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 20/01/2018.
6 | *
7 | * The count-and-say sequence is the sequence of integers with the first five terms as following:
8 | *
9 | * 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s"
10 | * or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth term
11 | * of the count-and-say sequence.
12 | *
13 | * Note: Each term of the sequence of integers will be represented as a string.
14 | *
15 | * Example 1:
16 | *
17 | * Input: 1 Output: "1" Example 2:
18 | *
19 | * Input: 4 Output: "1211"
20 | */
21 | public class CountAndSay {
22 |
23 | /**
24 | * Main method
25 | *
26 | * @param args
27 | */
28 | public static void main(String[] args) throws Exception {
29 | System.out.println(new CountAndSay().countAndSay(4));
30 | }
31 |
32 | public String countAndSay(int n) {
33 | String result = "1";
34 | for (int i = 1; i < n; i++) {
35 | int count = 1;
36 | char num = result.charAt(0);
37 | StringBuilder temp = new StringBuilder();
38 | for (int j = 1, l = result.length(); j < l; j++) {
39 | if (result.charAt(j) == num) {
40 | count++;
41 | } else {
42 | temp = temp.append(String.valueOf(count)).append(String.valueOf(num));
43 | num = result.charAt(j);
44 | count = 1;
45 | }
46 | }
47 | temp = temp.append(String.valueOf(count)).append(String.valueOf(num));
48 | result = temp.toString();
49 | }
50 | return result;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/string/ExcelSheetColumnNumber.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package string;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 07/07/2017. Given a column title as appear in an Excel sheet,
6 | * return its corresponding column number.
7 | *
8 | * For example:
9 | *
10 | * A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28
11 | */
12 | public class ExcelSheetColumnNumber {
13 | String CONST = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
14 |
15 | public static void main(String[] args) throws Exception {
16 | System.out.println(new ExcelSheetColumnNumber().titleToNumber("AAB"));
17 | }
18 |
19 | public int titleToNumber(String s) {
20 | int total = 0;
21 | int j = 0;
22 | for (int i = s.length() - 1; i >= 0; i--) {
23 | char c = s.charAt(i);
24 | int pos = CONST.indexOf(c) + 1;
25 | int pow = (int) Math.pow(26, j++);
26 | total += (pow * pos);
27 | }
28 | return total;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/string/FirstUniqueCharacterInAString.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package string;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 09/03/2017. Given a string, find the first non-repeating
6 | * character in it and return it's index. If it doesn't exist, return -1.
7 | *
8 | * Examples:
9 | *
10 | * s = "leetcode" return 0.
11 | *
12 | * s = "loveleetcode", return 2. Note: You may assume the string contain only lowercase letters.
13 | */
14 | public class FirstUniqueCharacterInAString {
15 | int[] CHAR = new int[256];
16 |
17 | /**
18 | * Main method
19 | *
20 | * @param args
21 | * @throws Exception
22 | */
23 | public static void main(String[] args) throws Exception {
24 | System.out.println(new FirstUniqueCharacterInAString().firstUniqChar("loveleetcode"));
25 | }
26 |
27 | public int firstUniqChar(String s) {
28 | if (s == null || s.isEmpty()) return -1;
29 |
30 | for (int i = 0, l = s.length(); i < l; i++) CHAR[s.charAt(i)]++;
31 |
32 | for (int i = 0, l = s.length(); i < l; i++) {
33 | if (CHAR[s.charAt(i)] == 1) return i;
34 | }
35 |
36 | return -1;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/string/ImplementStrStr.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package string;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 24/06/2017. Implement strStr().
6 | *
7 | * Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part
8 | * of haystack.
9 | *
10 | * Solution O(N ^ 2)
11 | */
12 | public class ImplementStrStr {
13 | public static void main(String[] args) throws Exception {
14 | System.out.println(new ImplementStrStr().strStr("AABB", ""));
15 | }
16 |
17 | public int strStr(String haystack, String needle) {
18 | if (haystack.isEmpty() && needle.isEmpty()) return 0;
19 | if (needle.isEmpty()) return 0;
20 | for (int i = 0, l = haystack.length(); i < l; i++) {
21 | if (haystack.charAt(i) == needle.charAt(0)) {
22 | if (isEqual(haystack, needle, i)) return i;
23 | }
24 | }
25 | return -1;
26 | }
27 |
28 | private boolean isEqual(String haystack, String needle, int i) {
29 | int hL = haystack.length();
30 | int nL = needle.length();
31 | int j = 0;
32 | while (i < hL && j < nL) {
33 | if (haystack.charAt(i) != needle.charAt(j)) return false;
34 | i++;
35 | j++;
36 | }
37 | return j >= nL;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/string/KeyboardRow.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package string;
3 | /**
4 | * Created by gouthamvidyapradhan on 09/04/2019
5 | *
6 | * Given a List of words, return the words that can be typed using letters of alphabet on only
7 | * one row's of American keyboard like the image below.
8 | *
9 | * Example:
10 | *
11 | * Input: ["Hello", "Alaska", "Dad", "Peace"] Output: ["Alaska", "Dad"]
12 | *
13 | * Note:
14 | *
15 | * You may use one character in the keyboard more than once. You may assume the input string will
16 | * only contain letters of alphabet.
17 | */
18 | import java.util.*;
19 |
20 | public class KeyboardRow {
21 |
22 | /**
23 | * Main method
24 | *
25 | * @param args
26 | */
27 | public static void main(String[] args) {}
28 |
29 | public String[] findWords(String[] words) {
30 | String R1 = "qwertyuiop";
31 | String R2 = "asdfghjkl";
32 | String R3 = "zxcvbnm";
33 | List Solution: O(N x M) where N is the length of the given array and M is the max_length of a
9 | * string.
10 | */
11 | public class LongestCommonPrefix {
12 | /**
13 | * Main method
14 | *
15 | * @param args
16 | */
17 | public static void main(String[] args) throws Exception {
18 | String[] A = {"abc", "a", "adkd"};
19 | System.out.println(new LongestCommonPrefix().longestCommonPrefix(A));
20 | }
21 |
22 | public String longestCommonPrefix(String[] strs) {
23 | if (strs.length == 0) return "";
24 | String result = strs[0];
25 | for (int i = 1; i < strs.length; i++) {
26 | String s = strs[i];
27 | for (int j = 0; j < result.length(); j++) {
28 | if (j >= s.length() || result.charAt(j) != s.charAt(j)) {
29 | result = result.substring(0, j);
30 | break;
31 | }
32 | }
33 | }
34 | return result;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/string/LongestPalindrome.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package string;
3 | /**
4 | * Created by gouthamvidyapradhan on 20/03/2019 Given a string which consists of lowercase or
5 | * uppercase letters, find the length of the longest palindromes that can be built with those
6 | * letters.
7 | *
8 | * This is case sensitive, for example "Aa" is not considered a palindrome here.
9 | *
10 | * Note: Assume the length of given string will not exceed 1,010.
11 | *
12 | * Example:
13 | *
14 | * Input: "abccccdd"
15 | *
16 | * Output: 7
17 | *
18 | * Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
19 | */
20 | import java.util.*;
21 |
22 | public class LongestPalindrome {
23 |
24 | /**
25 | * Main method
26 | *
27 | * @param args
28 | */
29 | public static void main(String[] args) {
30 | int result = new LongestPalindrome().longestPalindrome("asdfasdf");
31 | System.out.println(result);
32 | }
33 |
34 | public int longestPalindrome(String s) {
35 | Map Example : Input: S = "abcde" words = ["a", "bb", "acd", "ace"] Output: 3 Explanation: There
9 | * are three words in words that are a subsequence of S: "a", "acd", "ace". Note:
10 | *
11 | * All words in words and S will only consists of lowercase letters. The length of S will be in
12 | * the range of [1, 50000]. The length of words will be in the range of [1, 5000]. The length of
13 | * words[i] will be in the range of [1, 50].
14 | */
15 | public class NumberOfMatchingSubsequences {
16 |
17 | /**
18 | * Main method
19 | *
20 | * @param args
21 | */
22 | public static void main(String[] args) {
23 | String[] A = {"a", "bb", "acd", "ace"};
24 | System.out.println(new NumberOfMatchingSubsequences().numMatchingSubseq("abcde", A));
25 | }
26 |
27 | public int numMatchingSubseq(String S, String[] words) {
28 | int count = 0;
29 | for (int i = 0; i < words.length; i++) {
30 | String w = words[i];
31 | if (isSubsequence(S, w)) {
32 | count++;
33 | }
34 | }
35 | return count;
36 | }
37 |
38 | private boolean isSubsequence(String S, String P) {
39 | int i = 0, j = 0;
40 | if (P.length() > S.length()) return false;
41 | for (; ; ) {
42 | if (j >= P.length()) return true;
43 | else if (i >= S.length()) return false;
44 | else {
45 | if (S.charAt(i) == P.charAt(j)) {
46 | i++;
47 | j++;
48 | } else {
49 | i++;
50 | }
51 | }
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/string/OneEditDistance.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package string;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 09/12/2017.
6 | *
7 | * Given two strings S and T, determine if they are both one edit distance apart.
8 | */
9 | public class OneEditDistance {
10 |
11 | /**
12 | * Main method
13 | *
14 | * @param args
15 | * @throws Exception
16 | */
17 | public static void main(String[] args) throws Exception {
18 | System.out.println(new OneEditDistance().isOneEditDistance("abxd", "adxb"));
19 | }
20 |
21 | public boolean isOneEditDistance(String s, String t) {
22 | if (Math.abs(s.length() - t.length()) > 1 || s.equals(t)) return false;
23 | if (s.length() > t.length()) {
24 | return hasDiffOne(s, t, false);
25 | } else if (t.length() > s.length()) {
26 | return hasDiffOne(t, s, false);
27 | } else {
28 | return hasDiffOne(s, t, true);
29 | }
30 | }
31 |
32 | private boolean hasDiffOne(String s, String t, boolean sameLength) {
33 | int count = 0, i = 0, j = 0;
34 | for (int l1 = s.length(), l2 = t.length(); i < l1 && j < l2; ) {
35 | if (s.charAt(i) == t.charAt(j)) {
36 | i++;
37 | j++;
38 | } else {
39 | if (count > 0) return false;
40 | count++;
41 | if (sameLength) {
42 | i++;
43 | j++;
44 | } else {
45 | i++;
46 | }
47 | }
48 | }
49 | if (i == j) {
50 | return true;
51 | } else {
52 | return (s.charAt(s.length() - 1) == t.charAt(t.length() - 1));
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/string/PermutationInString.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package string;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 18/09/2017. Given two strings s1 and s2, write a function to
6 | * return true if s2 contains the permutation of s1. In other words, one of the first string's
7 | * permutations is the substring of the second string.
8 | *
9 | * Example 1: Input:s1 = "ab" s2 = "eidbaooo" Output:True Explanation: s2 contains one
10 | * permutation of s1 ("ba").
11 | *
12 | * Example 2: Input:s1= "ab" s2 = "eidboaoo" Output: False Note: The input strings only contain
13 | * lower case letters. The length of both given strings is in range [1, 10,000].
14 | */
15 | public class PermutationInString {
16 | private int[] S1 = new int[256];
17 | private int[] S2 = new int[256];
18 |
19 | /**
20 | * Main method
21 | *
22 | * @param args
23 | * @throws Exception
24 | */
25 | public static void main(String[] args) throws Exception {
26 | System.out.println(new PermutationInString().checkInclusion("ab", "eidboaoo"));
27 | }
28 |
29 | public boolean checkInclusion(String s1, String s2) {
30 | if (s2.length() < s1.length()) return false;
31 | for (int i = 0, l = s1.length(); i < l; i++) {
32 | S1[s1.charAt(i)]++;
33 | S2[s2.charAt(i)]++;
34 | }
35 | if (isEqual()) return true;
36 | for (int i = 1, j = s1.length(), l = s2.length(); j < l; i++, j++) {
37 | S2[s2.charAt(i - 1)]--;
38 | S2[s2.charAt(j)]++;
39 | if (isEqual()) return true;
40 | }
41 | return false;
42 | }
43 |
44 | private boolean isEqual() {
45 | boolean equal = true;
46 | for (int i = 0; i < 256; i++) {
47 | if (S1[i] != S2[i]) {
48 | equal = false;
49 | break;
50 | }
51 | }
52 | return equal;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/string/RepeatedSubstringPattern.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package string;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 25/03/2017. Given a non-empty string check if it can be
6 | * constructed by taking a substring of it and appending multiple copies of the substring together.
7 | * You may assume the given string consists of lowercase English letters only and its length will
8 | * not exceed 10000.
9 | *
10 | * Example 1: Input: "abab"
11 | *
12 | * Output: True
13 | *
14 | * Explanation: It's the substring "ab" twice. Example 2: Input: "aba"
15 | *
16 | * Output: False Example 3: Input: "abcabcabcabc"
17 | *
18 | * Output: True
19 | *
20 | * Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
21 | */
22 | public class RepeatedSubstringPattern {
23 | /**
24 | * Main method
25 | *
26 | * @param args
27 | * @throws Exception
28 | */
29 | public static void main(String[] args) throws Exception {
30 | System.out.println(new RepeatedSubstringPattern().repeatedSubstringPattern("a"));
31 | }
32 |
33 | public boolean repeatedSubstringPattern(String s) {
34 | boolean found;
35 | for (int i = 1, l = s.length(); i < l; i++) {
36 | found = true;
37 | String subI = s.substring(0, i);
38 | int j = i;
39 | if (j >= l) return false;
40 | while (j < l) {
41 | if ((j + i) >= l + 1) return false;
42 | String subJ = s.substring(j, j + i);
43 | if (!subI.equals(subJ)) {
44 | found = false;
45 | break;
46 | }
47 | j += i;
48 | }
49 | if (found) return true;
50 | }
51 | return false;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/string/ReverseStringII.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package string;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 30/07/2019 Given a string and an integer k, you need to reverse
6 | * the first k characters for every 2k characters counting from the start of the string. If there
7 | * are less than k characters left, reverse all of them. If there are less than 2k but greater than
8 | * or equal to k characters, then reverse the first k characters and left the other as original.
9 | * Example: Input: s = "abcdefg", k = 2 Output: "bacdfeg" Restrictions: The string consists of lower
10 | * English letters only. Length of the given string and k will in the range [1, 10000]
11 | *
12 | * Solution O(N)
13 | */
14 | public class ReverseStringII {
15 | public static void main(String[] args) {
16 | System.out.println(new ReverseStringII().reverseStr("abcdefg", 2));
17 | }
18 |
19 | public String reverseStr(String s, int k) {
20 | StringBuilder sb = new StringBuilder();
21 | for (int i = 0, l = s.length(); i < l; i++) {
22 | if (i % (2 * k) == 0) {
23 | int count = 0;
24 | StringBuilder temp = new StringBuilder();
25 | while (count < k && i < l) {
26 | temp.append(s.charAt(i));
27 | count++;
28 | i++;
29 | }
30 | sb.append(temp.reverse());
31 | }
32 | if (i < l) {
33 | sb.append(s.charAt(i));
34 | }
35 | }
36 | return sb.toString();
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/string/ReverseWordsInAString.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package string;
3 |
4 | import java.util.ArrayList;
5 | import java.util.List;
6 | import java.util.StringTokenizer;
7 |
8 | /**
9 | * Created by gouthamvidyapradhan on 04/07/2017. Given an input string, reverse the string word by
10 | * word.
11 | *
12 | * For example, Given s = "the sky is blue", return "blue is sky the".
13 | *
14 | * Clarification: What constitutes a word? A sequence of non-space characters constitutes a word.
15 | * Could the input string contain leading or trailing spaces? Yes. However, your reversed string
16 | * should not contain leading or trailing spaces. How about multiple spaces between two words?
17 | * Reduce them to a single space in the reversed string.
18 | */
19 | public class ReverseWordsInAString {
20 | public static void main(String[] args) throws Exception {
21 | System.out.println(new ReverseWordsInAString().reverseWords(" the sky is blue"));
22 | }
23 |
24 | public String reverseWords(String s) {
25 | if (s == null || s.isEmpty()) return "";
26 | StringBuilder sb = new StringBuilder(s.trim());
27 | String reverse = sb.reverse().toString();
28 | StringTokenizer st = new StringTokenizer(reverse, " ");
29 | List A shift on A consists of taking string A and moving the leftmost character to the rightmost
8 | * position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True
9 | * if and only if A can become B after some number of shifts on A.
10 | *
11 | * Example 1: Input: A = 'abcde', B = 'cdeab' Output: true
12 | *
13 | * Example 2: Input: A = 'abcde', B = 'abced' Output: false Note:
14 | *
15 | * A and B will have length at most 100.
16 | */
17 | public class RotateString {
18 |
19 | /**
20 | * Main method
21 | *
22 | * @param args
23 | */
24 | public static void main(String[] args) {
25 | System.out.println(new RotateString().rotateString("abcde", "cdeab"));
26 | }
27 |
28 | public boolean rotateString(String A, String B) {
29 | if (A.length() == 1 || A.isEmpty() || B.length() == 1 || B.isEmpty()) {
30 | return A.equals(B);
31 | } else if (A.length() != B.length()) {
32 | return false;
33 | }
34 | for (int i = 0, l = A.length(); i < l; i++) {
35 | char s = A.charAt(0);
36 | A = A.substring(1) + s;
37 | if (A.equals(B)) return true;
38 | }
39 | return false;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/string/SimplifyPath.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package string;
3 |
4 | import java.util.ArrayDeque;
5 | import java.util.Deque;
6 | import java.util.StringTokenizer;
7 |
8 | /**
9 | * Created by gouthamvidyapradhan on 28/07/2017.
10 | *
11 | * Given an absolute path for a file (Unix-style), simplify it.
12 | *
13 | * For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c"
14 | *
15 | * Corner Cases: Did you consider the case where path = "/../"? In this case, you should return
16 | * "/". Another corner case is the path might contain multiple slashes '/' together, such as
17 | * "/home//foo/". In this case, you should ignore redundant slashes and return "/home/foo".
18 | */
19 | public class SimplifyPath {
20 | /**
21 | * Main method
22 | *
23 | * @param args
24 | * @throws Exception
25 | */
26 | public static void main(String[] args) throws Exception {
27 | System.out.println(new SimplifyPath().simplifyPath("/home/"));
28 | }
29 |
30 | public String simplifyPath(String path) {
31 | if (path == null || path.isEmpty()) return "/";
32 | StringTokenizer st = new StringTokenizer(path, "/");
33 | Deque You need to return whether the student could be rewarded according to his attendance record.
11 | *
12 | * Example 1: Input: "PPALLP" Output: True Example 2: Input: "PPALLL" Output: False
13 | *
14 | * Solution O(N) Simple linear check
15 | */
16 | public class StudentAttendanceRecordI {
17 | public static void main(String[] args) {}
18 |
19 | public boolean checkRecord(String s) {
20 | int count = 0;
21 | for (int c : s.toCharArray()) {
22 | if (c == 'A') {
23 | count++;
24 | }
25 | if (count > 1) return false;
26 | }
27 | if (s.contains("LLL")) return false;
28 | return true;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/string/ValidPalindrome.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package string;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 13/07/2017. Given a string, determine if it is a palindrome,
6 | * considering only alphanumeric characters and ignoring cases.
7 | *
8 | * For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a
9 | * palindrome.
10 | *
11 | * Note: Have you consider that the string might be empty? This is a good question to ask during
12 | * an interview.
13 | *
14 | * For the purpose of this problem, we define empty string as valid palindrome.
15 | */
16 | public class ValidPalindrome {
17 | public static void main(String[] args) throws Exception {
18 | System.out.println(new ValidPalindrome().isPalindrome("989 "));
19 | }
20 |
21 | public boolean isPalindrome(String s) {
22 | if (s == null || s.isEmpty()) return true;
23 | s = s.toLowerCase();
24 | for (int i = 0, j = s.length() - 1; i < j; ) {
25 | char f = s.charAt(i);
26 | char l = s.charAt(j);
27 | if (!(f >= 'a' && f <= 'z') && !(f >= '0' && f <= '9')) {
28 | i++;
29 | continue;
30 | }
31 | if (!(l >= 'a' && l <= 'z') && !(l >= '0' && l <= '9')) {
32 | j--;
33 | continue;
34 | }
35 | if (f != l) return false;
36 | i++;
37 | j--;
38 | }
39 | return true;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/string/ValidPalindromeII.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package string;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 09/12/2017. Given a non-empty string s, you may delete at most
6 | * one character. Judge whether you can make it a palindrome.
7 | *
8 | * Example 1: Input: "aba" Output: True Example 2: Input: "abca" Output: True Explanation: You
9 | * could delete the character 'c'. Note: The string will only contain lowercase characters a-z. The
10 | * maximum length of the string is 50000.
11 | */
12 | public class ValidPalindromeII {
13 |
14 | /**
15 | * Main method
16 | *
17 | * @param args
18 | * @throws Exception
19 | */
20 | public static void main(String[] args) throws Exception {
21 | System.out.println(new ValidPalindromeII().validPalindrome("aaaaaab"));
22 | }
23 |
24 | public boolean validPalindrome(String s) {
25 | for (int i = 0, j = s.length() - 1; i < j; ) {
26 | if (s.charAt(i) == s.charAt(j)) {
27 | i++;
28 | j--;
29 | } else {
30 | return isPaliandrome(s.substring(i, j)) || isPaliandrome(s.substring(i + 1, j + 1));
31 | }
32 | }
33 | return true;
34 | }
35 |
36 | private boolean isPaliandrome(String s) {
37 | for (int i = 0, j = s.length() - 1; i < j; ) {
38 | if (s.charAt(i) == s.charAt(j)) {
39 | i++;
40 | j--;
41 | } else return false;
42 | }
43 | return true;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/tree/BSTtoDoublyLinkedList.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package tree;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 23/01/2018. Convert a BST to a sorted circular doubly-linked
6 | * list in-place. Think of the left and right pointers as synonymous to the previous and next
7 | * pointers in a doubly-linked list.
8 | *
9 | * Solution: Do a preorder traversal, keep track of previous node at every step and construct the
10 | * dd-linked list in-place.
11 | */
12 | public class BSTtoDoublyLinkedList {
13 |
14 | static class Node {
15 | public int val;
16 | public Node left;
17 | public Node right;
18 |
19 | public Node() {}
20 |
21 | public Node(int _val, Node _left, Node _right) {
22 | val = _val;
23 | left = _left;
24 | right = _right;
25 | }
26 | }
27 |
28 | /**
29 | * Main method
30 | *
31 | * @param args
32 | * @throws Exception
33 | */
34 | public static void main(String[] args) throws Exception {
35 | Node root = new Node(4, new Node(2, null, null), new Node(5, null, null));
36 | Node result = new BSTtoDoublyLinkedList().treeToDoublyList(root);
37 | // print result
38 | }
39 |
40 | public Node treeToDoublyList(Node root) {
41 | if (root == null) return null;
42 | Node head = new Node();
43 | Node last = preorder(root, head);
44 | last.right = head.right;
45 | head.right.left = last;
46 | return head.right;
47 | }
48 |
49 | Node preorder(Node node, Node prev) {
50 | if (node == null) return prev;
51 | else {
52 | Node left = preorder(node.left, prev);
53 | left.right = node;
54 | node.left = left;
55 | return preorder(node.right, node);
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/main/java/tree/BinaryTreeInorderTraversal.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package tree;
3 |
4 | import java.util.ArrayList;
5 | import java.util.List;
6 | import java.util.Stack;
7 |
8 | /**
9 | * Created by gouthamvidyapradhan on 06/08/2017. Given a binary tree, return the inorder traversal
10 | * of its nodes' values.
11 | *
12 | * For example: Given binary tree [1,null,2,3], 1 \ 2 / 3 return [1,3,2].
13 | *
14 | * Note: Recursive solution is trivial, could you do it iteratively?
15 | */
16 | public class BinaryTreeInorderTraversal {
17 | public static class TreeNode {
18 | int val;
19 | TreeNode left;
20 | TreeNode right;
21 |
22 | TreeNode(int x) {
23 | val = x;
24 | }
25 | }
26 |
27 | public static void main(String[] args) throws Exception {
28 | TreeNode root = new TreeNode(3);
29 | root.left = new TreeNode(4);
30 | root.left.left = new TreeNode(5);
31 | root.left.right = new TreeNode(6);
32 | root.left.left.left = new TreeNode(9);
33 | root.left.left.right = new TreeNode(10);
34 | root.right = new TreeNode(2);
35 | root.right.left = new TreeNode(7);
36 | root.right.right = new TreeNode(8);
37 | List For example, given the following binary tree:
11 | *
12 | * 1 / \ 2 3 \ 5 All root-to-leaf paths are:
13 | *
14 | * ["1->2->5", "1->3"]
15 | */
16 | public class BinaryTreePaths {
17 |
18 | public class TreeNode {
19 | int val;
20 | TreeNode left;
21 | TreeNode right;
22 |
23 | TreeNode(int x) {
24 | val = x;
25 | }
26 | }
27 |
28 | public List Example:
11 | *
12 | * Input: [1,null,2,3] 1 \ 2 / 3
13 | *
14 | * Output: [3,2,1] Follow up: Recursive solution is trivial, could you do it iteratively?
15 | *
16 | * Solution: O(N). Maintain a stack, for every node which you pop from stack add it to result
17 | * list, push left and right node to stack. Reverse the result list and return this as the answer.
18 | */
19 | public class BinaryTreePostorderTraversal {
20 | public static class TreeNode {
21 | int val;
22 | TreeNode left;
23 | TreeNode right;
24 |
25 | TreeNode(int x) {
26 | val = x;
27 | }
28 | }
29 |
30 | public static void main(String[] args) throws Exception {
31 | TreeNode root = new TreeNode(1);
32 | root.right = new TreeNode(2);
33 | root.right.left = new TreeNode(3);
34 | List The tilt of a tree node is defined as the absolute difference between the sum of all left
8 | * subtree node values and the sum of all right subtree node values. Null node has tilt 0.
9 | *
10 | * The tilt of the whole tree is defined as the sum of all nodes' tilt.
11 | *
12 | * Example: Input: 1 / \ 2 3 Output: 1 Explanation: Tilt of node 2 : 0 Tilt of node 3 : 0 Tilt of
13 | * node 1 : |2-3| = 1 Tilt of binary tree : 0 + 0 + 1 = 1 Note:
14 | *
15 | * The sum of node values in any subtree won't exceed the range of 32-bit integer. All the tilt
16 | * values won't exceed the range of 32-bit integer.
17 | *
18 | * Solution: Find tilt of left node and find tilt of right node and return left + right + curr to
19 | * its parent.
20 | */
21 | public class BinaryTreeTilt {
22 |
23 | public static class TreeNode {
24 | int val;
25 | TreeNode left;
26 | TreeNode right;
27 |
28 | TreeNode(int x) {
29 | val = x;
30 | }
31 | }
32 |
33 | public static void main(String[] args) {
34 | TreeNode node = new TreeNode(1);
35 | node.left = new TreeNode(2);
36 | node.right = new TreeNode(3);
37 | System.out.println(new BinaryTreeTilt().findTilt(node));
38 | }
39 |
40 | int sum = 0;
41 |
42 | public int findTilt(TreeNode root) {
43 | if (root == null) return 0;
44 | tilt(root);
45 | return sum;
46 | }
47 |
48 | private int tilt(TreeNode node) {
49 | if (node == null) return 0;
50 | int left = tilt(node.left);
51 | int right = tilt(node.right);
52 | sum += Math.abs(left - right);
53 | return left + right + node.val;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/tree/ConvertBSTToGreaterTree.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package tree;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 14/03/2019 Given a Binary Search Tree (BST), convert it to a
6 | * Greater Tree such that every key of the original BST is changed to the original key plus sum of
7 | * all keys greater than the original key in BST.
8 | *
9 | * Example:
10 | *
11 | * Input: The root of a Binary Search Tree like this: 5 / \ 2 13
12 | *
13 | * Output: The root of a Greater Tree like this: 18 / \ 20 13
14 | */
15 | public class ConvertBSTToGreaterTree {
16 |
17 | public static class TreeNode {
18 | int val;
19 | TreeNode left;
20 | TreeNode right;
21 |
22 | TreeNode(int x) {
23 | val = x;
24 | }
25 | }
26 |
27 | /**
28 | * Main method
29 | *
30 | * @param args
31 | */
32 | public static void main(String[] args) {
33 | TreeNode node = new TreeNode(5);
34 | node.right = new TreeNode(13);
35 | node.left = new TreeNode(2);
36 | node.left.left = new TreeNode(1);
37 | node.left.right = new TreeNode(3);
38 | TreeNode result = new ConvertBSTToGreaterTree().convertBST(node);
39 | System.out.println(result);
40 | }
41 |
42 | public TreeNode convertBST(TreeNode root) {
43 | postOrder(root, 0);
44 | return root;
45 | }
46 |
47 | private int postOrder(TreeNode node, int value) {
48 | if (node == null) return value;
49 | int right = postOrder(node.right, value);
50 | node.val = node.val + right;
51 | return postOrder(node.left, node.val);
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/tree/ConvertSortedArrayToBST.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package tree;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 09/03/2017. Given an array where elements are sorted in
6 | * ascending order, convert it to a height balanced BST.
7 | */
8 | public class ConvertSortedArrayToBST {
9 | public class TreeNode {
10 | int val;
11 | TreeNode left;
12 | TreeNode right;
13 |
14 | TreeNode(int x) {
15 | val = x;
16 | }
17 | }
18 |
19 | public TreeNode sortedArrayToBST(int[] nums) {
20 | if (nums.length == 0) return null;
21 | return build(0, nums.length - 1, nums);
22 | }
23 |
24 | private TreeNode build(int s, int e, int[] nums) {
25 | if (s > e) return null;
26 |
27 | int m = (e - s) / 2;
28 | int node = nums[s + m];
29 | TreeNode root = new TreeNode(node);
30 | if (s == e) return root;
31 |
32 | root.left = build(s, s + m - 1, nums);
33 | root.right = build(s + m + 1, e, nums);
34 |
35 | return root;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/tree/DiameterOfBinaryTree.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package tree;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 18/10/2017.
6 | *
7 | * Given a binary tree, you need to compute the length of the diameter of the tree. The diameter
8 | * of a binary tree is the length of the longest path between any two nodes in a tree. This path may
9 | * or may not pass through the root.
10 | *
11 | * Example: Given a binary tree 1 / \ 2 3 / \ 4 5 Return 3, which is the length of the path
12 | * [4,2,1,3] or [5,2,1,3].
13 | *
14 | * Note: The length of path between two nodes is represented by the number of edges between them.
15 | */
16 | public class DiameterOfBinaryTree {
17 |
18 | public static class TreeNode {
19 | int val;
20 | TreeNode left;
21 | TreeNode right;
22 |
23 | TreeNode(int x) {
24 | val = x;
25 | }
26 | }
27 |
28 | private int max = 0;
29 | /**
30 | * Main method
31 | *
32 | * @param args
33 | * @throws Exception
34 | */
35 | public static void main(String[] args) throws Exception {
36 | TreeNode root = new TreeNode(5);
37 | root.left = new TreeNode(4);
38 | System.out.println(new DiameterOfBinaryTree().diameterOfBinaryTree(root));
39 | }
40 |
41 | public int diameterOfBinaryTree(TreeNode root) {
42 | dfs(root);
43 | return max;
44 | }
45 |
46 | private int dfs(TreeNode node) {
47 | if (node != null) {
48 | int left = dfs(node.left);
49 | int right = dfs(node.right);
50 | max = Math.max(max, left + right);
51 | return left > right ? left + 1 : right + 1;
52 | }
53 | return 0;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/tree/FindBottomLeftTreeValue.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package tree;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 30/08/2017. Given a binary tree, find the leftmost value in the
6 | * last row of the tree.
7 | *
8 | * Example 1: Input:
9 | *
10 | * 2 / \ 1 3
11 | *
12 | * Output: 1 Example 2: Input:
13 | *
14 | * 1 / \ 2 3 / / \ 4 5 6 / 7
15 | *
16 | * Output: 7 Note: You may assume the tree (i.e., the given root node) is not NULL. Solution:
17 | * O(N) do a inorder search to find the left most value. Keep a level counter to keep track of what
18 | * level you are at when you do a inorder search.
19 | */
20 | public class FindBottomLeftTreeValue {
21 | private int max = 0, result;
22 |
23 | public static class TreeNode {
24 | int val;
25 | TreeNode left;
26 | TreeNode right;
27 |
28 | TreeNode(int x) {
29 | val = x;
30 | }
31 | }
32 |
33 | public static void main(String[] args) throws Exception {
34 | TreeNode root = new TreeNode(1);
35 | root.left = new TreeNode(2);
36 | root.left.left = new TreeNode(4);
37 | root.right = new TreeNode(3);
38 | root.right.left = new TreeNode(5);
39 | root.right.left.left = new TreeNode(7);
40 | root.right.right = new TreeNode(6);
41 | System.out.println(new FindBottomLeftTreeValue().findBottomLeftValue(root));
42 | }
43 |
44 | public int findBottomLeftValue(TreeNode root) {
45 | inorder(root, 1);
46 | return result;
47 | }
48 |
49 | private void inorder(TreeNode node, int level) {
50 | if (node != null) {
51 | if (level > max) {
52 | result = node.val;
53 | max = level;
54 | }
55 | inorder(node.left, level + 1);
56 | inorder(node.right, level + 1);
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/main/java/tree/FlipBinaryTree.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package tree;
3 |
4 | import java.util.*;
5 |
6 | /** Created by gouthamvidyapradhan on 26/01/2020 */
7 | public class FlipBinaryTree {
8 | public static class TreeNode {
9 | int val;
10 | TreeNode left;
11 | TreeNode right;
12 |
13 | TreeNode(int x) {
14 | val = x;
15 | }
16 | }
17 |
18 | public static void main(String[] args) {
19 | //
20 | }
21 |
22 | private int i, count;
23 | private List According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined
9 | * between two nodes v and w as the lowest node in T that has both v and w as descendants (where we
10 | * allow a node to be a descendant of itself).”
11 | *
12 | * _______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4 For example, the lowest common
13 | * ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node
14 | * can be a descendant of itself according to the LCA definition.
15 | */
16 | public class LCA {
17 | public class TreeNode {
18 | int val;
19 | TreeNode left;
20 | TreeNode right;
21 |
22 | TreeNode(int x) {
23 | val = x;
24 | }
25 | }
26 |
27 | /**
28 | * Main method
29 | *
30 | * @param args
31 | * @throws Exception
32 | */
33 | public static void main(String[] args) throws Exception {}
34 |
35 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
36 | if (root != null) {
37 | if (root.equals(p) || root.equals(q)) return root;
38 | TreeNode left = lowestCommonAncestor(root.left, p, q);
39 | TreeNode right = lowestCommonAncestor(root.right, p, q);
40 | if (left != null && right != null) return root;
41 | else if (left != null) return left;
42 | else return right;
43 | }
44 | return null;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/tree/LowestCommonAncestorBST.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package tree;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 09/03/2017. Given a binary search tree (BST), find the lowest
6 | * common ancestor (LCA) of two given nodes in the BST.
7 | *
8 | * According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined
9 | * between two nodes v and w as the lowest node in T that has both v and w as descendants (where we
10 | * allow a node to be a descendant of itself).”
11 | *
12 | * _______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5 For example, the lowest common
13 | * ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node
14 | * can be a descendant of itself according to the LCA definition.
15 | */
16 | public class LowestCommonAncestorBST {
17 | class TreeNode {
18 | int val;
19 | TreeNode left;
20 | TreeNode right;
21 |
22 | TreeNode(int x) {
23 | val = x;
24 | }
25 | }
26 |
27 | public static void main(String[] args) throws Exception {}
28 |
29 | private TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
30 | if (root == null) return null;
31 |
32 | if (p.val == root.val || q.val == root.val) return root;
33 | else if ((p.val < root.val && q.val > root.val) || (q.val < root.val && p.val > root.val))
34 | return root;
35 | else if (p.val < root.val && q.val < root.val) return lowestCommonAncestor(root.left, p, q);
36 | else return lowestCommonAncestor(root.right, p, q);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/tree/MinimumAbsoluteDifferenceInBST.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package tree;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 15/02/2018. Given a binary search tree with non-negative
6 | * values, find the minimum absolute difference between values of any two nodes.
7 | *
8 | * Example:
9 | *
10 | * Input:
11 | *
12 | * 1 \ 3 / 2
13 | *
14 | * Output: 1
15 | *
16 | * Explanation: The minimum absolute difference is 1, which is the difference between 2 and 1 (or
17 | * between 2 and 3). Note: There are at least two nodes in this BST.
18 | */
19 | public class MinimumAbsoluteDifferenceInBST {
20 |
21 | public static class TreeNode {
22 | int val;
23 | TreeNode left;
24 | TreeNode right;
25 |
26 | TreeNode(int x) {
27 | val = x;
28 | }
29 | }
30 |
31 | int min = Integer.MAX_VALUE;
32 |
33 | public static void main(String[] args) throws Exception {
34 | TreeNode root = new TreeNode(1);
35 | root.right = new TreeNode(2);
36 | root.right.right = new TreeNode(3);
37 | new MinimumAbsoluteDifferenceInBST().getMinimumDifference(root);
38 | }
39 |
40 | public int getMinimumDifference(TreeNode root) {
41 | getMin(root, null);
42 | return min;
43 | }
44 |
45 | private Integer getMin(TreeNode node, Integer prev) {
46 | if (node == null) return prev;
47 | Integer left = getMin(node.left, prev);
48 | if (left != null) {
49 | min = Math.min(min, Math.abs(node.val - left));
50 | }
51 | return getMin(node.right, node.val);
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/tree/PreorderToBT.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package tree;
3 |
4 | import java.util.HashMap;
5 | import java.util.Map;
6 |
7 | /**
8 | * Created by gouthamvidyapradhan on 25/02/2017. Given preorder and inorder traversal of a tree,
9 | * construct the binary tree.
10 | *
11 | * Note: You may assume that duplicates do not exist in the tree.
12 | */
13 | public class PreorderToBT {
14 | public class TreeNode {
15 | int val;
16 | TreeNode left;
17 | TreeNode right;
18 |
19 | TreeNode(int x) {
20 | val = x;
21 | }
22 | }
23 |
24 | Map Two binary trees are considered the same if they are structurally identical and the nodes have
9 | * the same value.
10 | *
11 | * Example 1:
12 | *
13 | * Input: 1 1 / \ / \ 2 3 2 3
14 | *
15 | * [1,2,3], [1,2,3]
16 | *
17 | * Output: true Example 2:
18 | *
19 | * Input: 1 1 / \ 2 2
20 | *
21 | * [1,2], [1,null,2]
22 | *
23 | * Output: false Example 3:
24 | *
25 | * Input: 1 1 / \ / \ 2 1 1 2
26 | *
27 | * [1,2,1], [1,1,2]
28 | *
29 | * Output: false
30 | *
31 | * Solution: Do a pre-order traversal of both the trees in parallel and compare each node
32 | */
33 | public class SameTree {
34 |
35 | public class TreeNode {
36 | int val;
37 | TreeNode left;
38 | TreeNode right;
39 |
40 | TreeNode(int x) {
41 | val = x;
42 | }
43 | }
44 |
45 | /**
46 | * Main method
47 | *
48 | * @param args
49 | * @throws Exception
50 | */
51 | public static void main(String[] args) throws Exception {}
52 |
53 | public boolean isSameTree(TreeNode p, TreeNode q) {
54 | if ((p == null && q != null) || (p != null && q == null)) return false;
55 | if (p == null && q == null) return true;
56 | else {
57 | boolean status = isSameTree(p.left, q.left);
58 | if (!status || p.val != q.val) {
59 | return false;
60 | }
61 | return isSameTree(p.right, q.right);
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/tree/SortedArrayToBST.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package tree;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 25/02/2017. Given an array where elements are sorted in
6 | * ascending order, convert it to a height balanced BST.
7 | */
8 | public class SortedArrayToBST {
9 | public class TreeNode {
10 | int val;
11 | TreeNode left;
12 | TreeNode right;
13 |
14 | TreeNode(int x) {
15 | val = x;
16 | }
17 | }
18 |
19 | /**
20 | * Main method
21 | *
22 | * @param args
23 | * @throws Exception
24 | */
25 | public static void main(String[] args) throws Exception {
26 | int[] A = {1, 2, 3, 4, 5, 6};
27 | new SortedArrayToBST().sortedArrayToBST(A);
28 | }
29 |
30 | public TreeNode sortedArrayToBST(int[] nums) {
31 | if (nums.length == 0) return null;
32 |
33 | TreeNode root = new SortedArrayToBST().build(0, nums.length - 1, nums);
34 | preorder(root);
35 | return root;
36 | }
37 |
38 | private void preorder(TreeNode node) {
39 | if (node != null) {
40 | preorder(node.left);
41 | System.out.println(node.val);
42 | preorder(node.right);
43 | }
44 | }
45 |
46 | private TreeNode build(int s, int e, int[] nums) {
47 | if (s > e) return null;
48 |
49 | int m = (e - s) / 2;
50 | int node = nums[s + m];
51 | TreeNode root = new TreeNode(node);
52 | if (s == e) return root;
53 |
54 | root.left = build(s, s + m - 1, nums);
55 | root.right = build(s + m + 1, e, nums);
56 |
57 | return root;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/main/java/tree/SubtreeOfAnotherTree.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package tree;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 07/07/2017. Given two non-empty binary trees s and t, check
6 | * whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s
7 | * is a tree consists of a node in s and all of this node's descendants. The tree s could also be
8 | * considered as a subtree of itself.
9 | *
10 | * Example 1: Given tree s:
11 | *
12 | * 3 / \ 4 5 / \ 1 2 Given tree t: 4 / \ 1 2 Return true, because t has the same structure and
13 | * node values with a subtree of s. Example 2: Given tree s:
14 | *
15 | * 3 / \ 4 5 / \ 1 2 / 0 Given tree t: 4 / \ 1 2 Return false.
16 | */
17 | public class SubtreeOfAnotherTree {
18 | public class TreeNode {
19 | int val;
20 | TreeNode left;
21 | TreeNode right;
22 |
23 | TreeNode(int x) {
24 | val = x;
25 | }
26 | }
27 |
28 | public static void main(String[] args) throws Exception {}
29 |
30 | public boolean isSubtree(TreeNode s, TreeNode t) {
31 | if (s != null) {
32 | if (s.val == t.val) {
33 | if (equal(s, t)) return true;
34 | else return (isSubtree(s.left, t) || isSubtree(s.right, t));
35 | } else return (isSubtree(s.left, t) || isSubtree(s.right, t));
36 | }
37 | return false;
38 | }
39 |
40 | private boolean equal(TreeNode s, TreeNode t) {
41 | if (s == null && t == null) return true;
42 | else if (s == null || t == null) return false;
43 | else if (s.val != t.val) return false;
44 | else return equal(s.left, t.left) && equal(s.right, t.right);
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/tree/SumofLeftLeaves.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package tree;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 13/12/2017. Find the sum of all left leaves in a given binary
6 | * tree.
7 | *
8 | * Example:
9 | *
10 | * 3 / \ 9 20 / \ 15 7
11 | *
12 | * There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
13 | */
14 | public class SumofLeftLeaves {
15 |
16 | public class TreeNode {
17 | int val;
18 | TreeNode left;
19 | TreeNode right;
20 |
21 | TreeNode(int x) {
22 | val = x;
23 | }
24 | }
25 |
26 | /**
27 | * Main method
28 | *
29 | * @param args
30 | * @throws Exception
31 | */
32 | public static void main(String[] args) throws Exception {}
33 |
34 | public int sumOfLeftLeaves(TreeNode root) {
35 | return inorder(root, false);
36 | }
37 |
38 | private int inorder(TreeNode node, boolean isLeft) {
39 | if (node != null) {
40 | if (node.left == null && node.right == null) {
41 | if (isLeft) {
42 | return node.val;
43 | } else return 0;
44 | }
45 | return inorder(node.left, true) + inorder(node.right, false);
46 | }
47 | return 0;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/tree/SymmetricTree.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package tree;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 14/08/2017. Given a binary tree, check whether it is a mirror
6 | * of itself (ie, symmetric around its center).
7 | *
8 | * For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
9 | *
10 | * 1 / \ 2 2 / \ / \ 3 4 4 3
11 | *
12 | * But the following [1,2,2,null,3,null,3] is not: 1 / \ 2 2 \ \ 3 3
13 | */
14 | public class SymmetricTree {
15 |
16 | static class TreeNode {
17 | int val;
18 | TreeNode left;
19 | TreeNode right;
20 |
21 | TreeNode(int x) {
22 | val = x;
23 | }
24 | }
25 |
26 | /**
27 | * Main method
28 | *
29 | * @param args
30 | * @throws Exception
31 | */
32 | public static void main(String[] args) throws Exception {
33 | TreeNode node = new TreeNode(3);
34 | node.left = new TreeNode(4);
35 | node.right = new TreeNode(5);
36 | System.out.println(new SymmetricTree().isSymmetric(node));
37 | }
38 |
39 | public boolean isSymmetric(TreeNode root) {
40 | if (root == null) return true;
41 | return dfs(root.left, root.right);
42 | }
43 |
44 | private boolean dfs(TreeNode left, TreeNode right) {
45 | if (left == null && right == null) return true;
46 | else if (left == null || right == null) return false;
47 | return dfs(left.left, right.right) && left.val == right.val && dfs(left.right, right.left);
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/tree/TwoSumIV.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package tree;
3 |
4 | import java.util.HashSet;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 16/12/2017. Given a Binary Search Tree and a target number,
8 | * return true if there exist two elements in the BST such that their sum is equal to the given
9 | * target.
10 | *
11 | * Example 1: Input: 5 / \ 3 6 / \ \ 2 4 7
12 | *
13 | * Target = 9
14 | *
15 | * Output: True Example 2: Input: 5 / \ 3 6 / \ \ 2 4 7
16 | *
17 | * Target = 28
18 | *
19 | * Output: False
20 | */
21 | public class TwoSumIV {
22 |
23 | public class TreeNode {
24 | int val;
25 | TreeNode left;
26 | TreeNode right;
27 |
28 | TreeNode(int x) {
29 | val = x;
30 | }
31 | }
32 |
33 | /**
34 | * Main method
35 | *
36 | * @param args
37 | * @throws Exception
38 | */
39 | public static void main(String[] args) throws Exception {}
40 |
41 | public boolean findTarget(TreeNode root, int k) {
42 | return inorder(root, new HashSet<>(), k);
43 | }
44 |
45 | private boolean inorder(TreeNode node, HashSet For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its zigzag
14 | * level order traversal as: [ [3], [20,9], [15,7] ]
15 | */
16 | public class ZigZagTraversal {
17 |
18 | public class TreeNode {
19 | int val;
20 | TreeNode left;
21 | TreeNode right;
22 |
23 | TreeNode(int x) {
24 | val = x;
25 | }
26 | }
27 |
28 | public static void main(String[] args) throws Exception {}
29 |
30 | public List Examples:
14 | *
15 | * Given "abcabcbb", the answer is "abc", which the length is 3.
16 | *
17 | * Given "bbbbb", the answer is "b", with the length of 1.
18 | *
19 | * Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a
20 | * substring, "pwke" is a subsequence and not a substring.
21 | */
22 | public class LongestSubstringWitoutRepeats {
23 | Set Given an array of n positive integers and a positive integer s, find the minimal length of a
8 | * contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
9 | *
10 | * For example, given the array [2,3,1,2,4,3] and s = 7, the subarray [4,3] has the minimal
11 | * length under the problem constraint.
12 | *
13 | * click to show more practice.
14 | *
15 | * Credits: Special thanks to @Freezen for adding this problem and creating all test cases.
16 | *
17 | * Solution: O(n) solution. Solve using sliding window sub-array sum using two pointers.
18 | */
19 | public class MinimumSizeSubarraySum {
20 | /**
21 | * Main method
22 | *
23 | * @param args
24 | * @throws Exception
25 | */
26 | public static void main(String[] args) throws Exception {
27 | int[] nums = {2, 3, 1, 2, 4, 3};
28 | System.out.println(new MinimumSizeSubarraySum().minSubArrayLen(7, nums));
29 | }
30 |
31 | public int minSubArrayLen(int s, int[] nums) {
32 | int sum = 0, count = 0, min = Integer.MAX_VALUE;
33 | for (int i = 0, j = 0; j < nums.length; ) {
34 | if (nums[j] >= s) {
35 | return 1;
36 | } else {
37 | sum += nums[j];
38 | count++;
39 | if (sum >= s) {
40 | min = Math.min(min, count);
41 | while (j > i) {
42 | sum -= nums[i];
43 | count--;
44 | i++;
45 | if (sum < s) break;
46 | min = Math.min(min, count);
47 | }
48 | }
49 | }
50 | j++;
51 | }
52 | if (min == Integer.MAX_VALUE) {
53 | return 0;
54 | }
55 | return min;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/two_pointers/MoveZeroes.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package two_pointers;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 13/06/2017. Accepted Given an array nums, write a function to
6 | * move all 0's to the end of it while maintaining the relative order of the non-zero elements.
7 | *
8 | * For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3,
9 | * 12, 0, 0].
10 | *
11 | * Note: You must do this in-place without making a copy of the array. Minimize the total number
12 | * of operations.
13 | */
14 | public class MoveZeroes {
15 | public static void main(String[] args) throws Exception {
16 | int[] nums = {0, 0, 0, 0, 1, 0, 1, 0, 2};
17 | new MoveZeroes().moveZeroes(nums);
18 | for (int n : nums) System.out.print(n);
19 | }
20 |
21 | public void moveZeroes(int[] nums) {
22 | int i = 0;
23 | for (int j = 0, l = nums.length; j < l; ) {
24 | if (nums[j] == 0) j++;
25 | else {
26 | int temp = nums[i];
27 | nums[i] = nums[j];
28 | nums[j] = temp;
29 | i++;
30 | j++;
31 | }
32 | }
33 | while (i < nums.length) nums[i++] = 0;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/two_pointers/RemoveDuplicates.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package two_pointers;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 04/07/2017. Given a sorted array, remove the duplicates in
6 | * place such that each element appear only once and return the new length.
7 | *
8 | * Do not allocate extra space for another array, you must do this in place with constant memory.
9 | *
10 | * For example, Given input array nums = [1,1,2],
11 | *
12 | * Your function should return length = 2, with the first two elements of nums being 1 and 2
13 | * respectively. It doesn't matter what you leave beyond the new length.
14 | */
15 | public class RemoveDuplicates {
16 | public static void main(String[] args) throws Exception {
17 | int[] nums = {1, 1, 2};
18 | int N = new RemoveDuplicates().removeDuplicates(nums);
19 | for (int i = 0; i < N; i++) System.out.print(nums[i] + " ");
20 | }
21 |
22 | public int removeDuplicates(int[] nums) {
23 | if (nums.length == 1) return 1;
24 | int size = 1;
25 | for (int j = 0, i = 1; i < nums.length; i++) {
26 | if (nums[i] != nums[i - 1]) {
27 | size++;
28 | j++;
29 | nums[j] = nums[i];
30 | }
31 | }
32 | return size;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/two_pointers/RemoveDuplicatesII.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package two_pointers;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 20/01/2018. Follow up for "Remove Duplicates": What if
6 | * duplicates are allowed at most twice?
7 | *
8 | * For example, Given sorted array nums = [1,1,1,2,2,3],
9 | *
10 | * Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2
11 | * and 3. It doesn't matter what you leave beyond the new length.
12 | */
13 | public class RemoveDuplicatesII {
14 |
15 | /**
16 | * Main method
17 | *
18 | * @param args
19 | * @throws Exception
20 | */
21 | public static void main(String[] args) throws Exception {
22 | int[] A = {1, 1, 1, 2, 2, 2, 3, 4, 4};
23 | System.out.println(new RemoveDuplicatesII().removeDuplicates(A));
24 | }
25 |
26 | public int removeDuplicates(int[] nums) {
27 | if (nums.length == 0) return 0;
28 | int j = 0;
29 | int count = 1;
30 | for (int i = 1; i < nums.length; i++) {
31 | if (nums[i - 1] == nums[i]) {
32 | count++;
33 | } else {
34 | count = 1;
35 | }
36 | if (count == 1 || count == 2) {
37 | j++;
38 | nums[j] = nums[i];
39 | }
40 | }
41 | return j + 1;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/two_pointers/ThreeSumClosest.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package two_pointers;
3 |
4 | import java.util.Arrays;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 13/06/2017. Accepted Given an array S of n integers, find three
8 | * integers in S such that the sum is closest to a given number, target. Return the sum of the three
9 | * integers. You may assume that each input would have exactly one solution.
10 | *
11 | * For example, given array S = {-1 2 1 -4}, and target = 1.
12 | *
13 | * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
14 | */
15 | public class ThreeSumClosest {
16 |
17 | public static void main(String[] args) {
18 | int[] a = {-1, 2, 1, -4};
19 | System.out.println(new ThreeSumClosest().threeSumClosest(a, 1));
20 | }
21 |
22 | public int threeSumClosest(int[] a, int target) {
23 | Arrays.sort(a);
24 | int min = Integer.MAX_VALUE, ans = -1;
25 | for (int i = 0, l = a.length; i < l - 2; i++) {
26 | if (i == 0 || !(a[i] == a[i - 1])) {
27 | int j = i + 1, k = l - 1;
28 | while (k > j) {
29 | if (j != i + 1 && (a[j] == a[j - 1])) {
30 | j++;
31 | continue;
32 | }
33 | int sum = a[i] + a[j] + a[k];
34 | if (sum < target) {
35 | int diff = Math.abs(sum - target);
36 | if (diff < min) {
37 | min = diff;
38 | ans = sum;
39 | }
40 | j++;
41 | } else if (sum > target) {
42 | int diff = Math.abs(sum - target);
43 | if (diff < min) {
44 | min = diff;
45 | ans = sum;
46 | }
47 | k--;
48 | } else {
49 | return sum;
50 | }
51 | }
52 | }
53 | }
54 | return ans;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/main/java/two_pointers/TrappingRainWater.java:
--------------------------------------------------------------------------------
1 | /* (C) 2024 YourCompanyName */
2 | package two_pointers;
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 08/03/2017. Given n non-negative integers representing an
6 | * elevation map where the width of each bar is 1, compute how much water it is able to trap after
7 | * raining.
8 | *
9 | * For example, Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
10 | */
11 | public class TrappingRainWater {
12 | /**
13 | * Main method
14 | *
15 | * @param args
16 | * @throws Exception
17 | */
18 | public static void main(String[] args) throws Exception {
19 | int[] height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
20 | System.out.println(new TrappingRainWater().trap(height));
21 | }
22 |
23 | private int trap(int[] height) {
24 | if (height.length == 0) return 0;
25 |
26 | int[] left = new int[height.length];
27 | int[] right = new int[height.length];
28 | int max = 0;
29 | left[0] = 0;
30 | right[height.length - 1] = 0;
31 |
32 | int total = 0;
33 |
34 | for (int i = 1, l = height.length; i < l; i++) {
35 | left[i] = Math.max(max, height[i - 1]);
36 | max = left[i];
37 | }
38 | max = 0;
39 | for (int i = height.length - 2; i >= 0; i--) {
40 | right[i] = Math.max(max, height[i + 1]);
41 | max = right[i];
42 | }
43 | for (int i = 0, l = height.length; i < l; i++) {
44 | int min = Math.min(left[i], right[i]);
45 | if (min > height[i]) {
46 | total += (min - height[i]);
47 | }
48 | }
49 | return total;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
> result = new Combinations().combine(3, 3);
19 | }
20 |
21 | public List
> combine(int n, int k) {
22 | int[] subArr = new int[k];
23 | List
> result = new ArrayList<>();
24 | getNext(0, 0, n, k, subArr, result);
25 | return result;
26 | }
27 |
28 | private void getNext(int i, int count, int n, int k, int[] subArr, List
> result) {
29 | if (k == 0) {
30 | List
> result = new PalindromePartitioning().partition("aaaaaaaaaaaaaaaaaa");
26 | }
27 |
28 | public List
> partition(String s) {
29 | List
> result = new ArrayList<>();
30 | doNext(0, new ArrayList<>(), s, result);
31 | return result;
32 | }
33 |
34 | private void doNext(int i, List
> result) {
35 | if (i == s.length()) {
36 | List
> result = new Permutations().permute(nums);
24 | }
25 |
26 | public List
> permute(int[] nums) {
27 | List
> result = new ArrayList<>();
28 | nextPermutation(0, nums, result);
29 | return result;
30 | }
31 |
32 | private void nextPermutation(int i, int[] nums, List
> result) {
33 | if (i == nums.length - 1) {
34 | List
> permuteUnique(int[] nums) {
21 | List
> result = new ArrayList<>();
22 | Arrays.sort(nums);
23 | nextPermutation(0, nums, result);
24 | return result;
25 | }
26 |
27 | private void nextPermutation(int i, int[] nums, List
> result) {
28 | if (i == nums.length - 1) {
29 | List
> result = new Subsets().subsets(n);
27 | }
28 |
29 | public List
> subsets(int[] nums) {
30 | List
> result = new ArrayList<>();
31 | result.add(new ArrayList<>()); // empty subset
32 | for (int i = 0, l = nums.length; i < l; i++) {
33 | for (int j = 0, resLen = result.size(); j < resLen; j++) {
34 | List
> result = new SubsetsII().subsetsWithDup(n);
28 | }
29 |
30 | public List
> subsetsWithDup(int[] nums) {
31 | List
> result = new ArrayList<>();
32 | result.add(new ArrayList<>()); // empty subset
33 | int start = 0, newStart = 0;
34 | Arrays.sort(nums);
35 | for (int i = 0, l = nums.length; i < l; i++) {
36 | newStart = result.size();
37 | if (i == 0 || nums[i] != nums[i - 1]) {
38 | start = 0;
39 | }
40 | for (int j = start, resLen = result.size(); j < resLen; j++) {
41 | List
> zigzagLevelOrder(TreeNode root) {
31 | List
> result = new ArrayList<>();
32 | if (root == null) return result;
33 | dfs(root, 0, result);
34 | return result;
35 | }
36 |
37 | @SuppressWarnings("unchecked")
38 | private void dfs(TreeNode root, int level, List
> result) {
39 | if (root != null) {
40 | LinkedList