├── .gitignore ├── .vscode ├── settings.json └── tasks.json ├── LICENSE ├── README.md └── src ├── Arrays ├── Arrays 2-D array and Pointers.c ├── Arrays Three Dimensional Array declaration and initialization.c ├── Arrays Three Dimensional Array user input.c ├── Arrays Two Dimensional to one Dimensional .c ├── Arrays Two Dimensional Array user inputt.c ├── Arrays Two Dimensional declaration and initialization user input.c ├── Arrays Two Dimensional declaration and initialization.c ├── Arrays Two Dimensional sum of Rows.c ├── Arrays Two Dimensional sum of columns.c ├── Arrays Two Dimensional sum of diagonal.c ├── Arrays Two Dimensional sum of numbers.c ├── Arrays Two Dimensional to one Dimensionall .c ├── Arrays change number .c ├── Arrays complete implementation.c ├── Arrays declaration and initializing.c ├── Arrays merge.c ├── Arrays one-D array and Pointers.c ├── Arrays one-dimensional array.c ├── Arrays positive,negative zero number.c ├── Arrays store 2 array in one array.c ├── Arrays sum and average.c └── Arrays sum of two arrays.c ├── Dynamic Programming └── README.md ├── Graphs ├── graph Adjacency list.c ├── graph Adjacency matrix.c ├── graph BFS.c ├── graph DFS (Adjacency list).c ├── graph DFS.c └── graph topological sort.c ├── Greedy Algorithms └── 05 AlgoExpert.js ├── HackerRank ├── 00 A Very Big Sum.js └── 01 Diagonal Difference.js ├── Hashing ├── Hash Table Implementation.c ├── Hash Table Separate Chaining.c ├── Hash Table Separate Chaining.c ├── Hash Table Speller checker.c ├── Hash Table _ Linear Probing.c ├── Hash Table _Quadratic Probing.c └── Hash Table __Double Hashing ├── Heap ├── Heap DSA Max-Heap Implementation.c ├── Heap DSA Min-Heap Implementation.c ├── MaxHeap.java └── MinHeap.java ├── LeetCode ├── easy │ ├── 00001 │ │ └── TwoSum.java │ ├── 00009 │ │ └── 9. Palindrome Number.java │ ├── 00013 │ │ └── RomanToInteger.java │ ├── 00014 │ │ └── LongestCommonPrefix.java │ ├── 00020 │ │ └── ValidParentheses.java │ ├── 00021 │ │ └── MergeTwoSortedLists.java │ ├── 00026 │ │ └── removeDuplicates.java │ ├── 00027 │ │ └── 27. Remove Element.java │ ├── 00035 │ │ └── SearchInsertPosition.java │ ├── 00058 │ │ └── LengthOfLastWord.java │ ├── 00066 │ │ └── 66. Plus One.java │ ├── 00069 │ │ └── Sqrt.java │ ├── 00070 │ │ └── ClimbingStairs.java │ ├── 00083 │ │ └── RemoveDuplicatesSortedList.java │ ├── 00088 │ │ └── MergeSortedArray.java │ ├── 00094 │ │ └── BinaryTreeInorderTraversal.java │ ├── 00101 │ │ └── SymmetricTree.java │ ├── 00104 │ │ └── MaximumDepthOfBinaryTree.java │ ├── 00108 │ │ └── SortedArrayToBST.java │ ├── 00112 │ │ └── PathSum.java │ ├── 00121 │ │ └── MaxProfitMultipleTransactions.java │ ├── 00125 │ │ └── PalindromeChecker.java │ ├── 00136 │ │ └── 136. Single Number.java │ ├── 00141 │ │ └── LinkedListCycle.java │ ├── 00144 │ │ └── BinaryTreePreorderTraversal.java │ ├── 00145 │ │ └── BinaryTreePostorderTraversal.java │ ├── 00169 │ │ └── MajorityElement.java │ ├── 00202 │ │ └── HappyNumber.java │ ├── 00206 │ │ └── ReverseLinkedList.java │ ├── 00217 │ │ └── ContainsDuplicate.java │ ├── 00219 │ │ └── ContainsDuplicateII.java │ ├── 00225 │ │ └── MyStack.java │ ├── 00226 │ │ └── InvertBinaryTree.java │ ├── 00231 │ │ └── PowerOfTwo.java │ ├── 00232 │ │ └── MyQueue.java │ ├── 00234 │ │ └── PalindromeLinkedList.java │ ├── 00268 │ │ └── MissingNumber.java │ ├── 00278 │ │ └── firstBadVersion.java │ ├── 00283 │ │ └── 283. Move Zeroes.java │ ├── 00303 │ │ └── NumArray.java │ ├── 00326 │ │ └── PowerOfThree.java │ ├── 00342 │ │ └── PowerOfFour.java │ ├── 00344 │ │ └── ReverseString.java │ ├── 00349 │ │ └── intersection.java │ ├── 00350 │ │ └── intersect.java │ ├── 00367 │ │ └── isPerfectSquare.java │ ├── 00374 │ │ └── GuessGame.java │ ├── 00387 │ │ └── FirstUniqueCharacterInString.java │ ├── 00392 │ │ └── IsSubsequence.java │ ├── 00414 │ │ └── ThirdMaximumNumber.java │ ├── 00441 │ │ └── arrangeCoins.java │ ├── 00448 │ │ └── DisappearedNumber.java │ ├── 00455 │ │ └── AssignCookies.java │ ├── 00485 │ │ └── MaxConsecutiveOnes.java │ ├── 00496 │ │ └── NextGreaterElementI.java │ ├── 00501 │ │ └── FindModeInBinarySearchTree.java │ ├── 00509 │ │ └── FibonacciNumber.java │ ├── 00543 │ │ └── DiameterOfBinaryTree.java │ ├── 00561 │ │ └── ArrayPartition.java │ ├── 00566 │ │ └── MatrixReshape.java │ ├── 00572 │ │ └── SameTree.java │ ├── 00589 │ │ └── NAryTreePreorderTraversal.java │ ├── 00590 │ │ └── NaryTreePostorderTraversal.java │ ├── 00617 │ │ └── MergeBinaryTrees.java │ ├── 00628 │ │ └── 628. Maximum Product of Three Numbers.java │ ├── 00637 │ │ └── AverageOfLevelsInBinaryTree.java │ ├── 00643 │ │ └── Solution.java │ ├── 00645 │ │ └── SetMismatch.java │ ├── 00653 │ │ └── TwoSumIV.java │ ├── 00671 │ │ └── SecondMinimumNodeInBinaryTree.java │ ├── 00680 │ │ └── ValidPalindromeII.java │ ├── 00697 │ │ └── 697. Degree of an Array.java │ ├── 00700 │ │ └── SearchInBST.java │ ├── 00704 │ │ └── 704. Binary Search.java │ ├── 00709 │ │ └── ToLowerCase.java │ ├── 00744 │ │ └── nextGreatestLetter.java │ ├── 00746 │ │ └── MinCostClimbingStairs.java │ ├── 00747 │ │ └── dominantIndex.java │ ├── 00832 │ │ └── ImageProcessor.java │ ├── 00854 │ │ └── 854. Maximum Population Year.java │ ├── 00859 │ │ └── BuddyStrings.java │ ├── 00867 │ │ └── MatrixTranspose.java │ ├── 00876 │ │ └── MiddleOfLinkedList.java │ ├── 00888 │ │ └── intersect.java │ ├── 00905 │ │ └── SortArrayByParity.java │ ├── 00922 │ │ └── SortArrayByParityII.java │ ├── 00977 │ │ └── SquaresOfSortedArray.java │ ├── 00989 │ │ └── 989. Add to Array-Form of Integer.java │ ├── 00993 │ │ └── CousinsInBinaryTree.java │ ├── 01005 │ │ └── MaximizeSumAfterKNegations .java │ ├── 01051 │ │ └── HeightChecker.java │ ├── 01108 │ │ └── DefangingIPAddress.java │ ├── 01122 │ │ └── RelativeSortArray.java │ ├── 01137 │ │ └── TribonacciNumber.java │ ├── 01200 │ │ └── MinimumAbsoluteDifference.java │ ├── 01217 │ │ └── MinCostToMoveChips.java │ ├── 01252 │ │ └── OddCells.java │ ├── 01281 │ │ └── 1281. Subtract the Product and Sum of Digits of an Integer.java │ ├── 01295 │ │ └── FindNumbers.java │ ├── 01304 │ │ └── UniqueIntegersSumZero.java │ ├── 01331 │ │ └── RankTransform.java │ ├── 01346 │ │ └── checkIfExist.java │ ├── 01351 │ │ └── countNegatives.java │ ├── 01365 │ │ └── SmallerNumbersThanCurrent.java │ ├── 01380 │ │ └── LuckyNumbersInMatrix.java │ ├── 01389 │ │ └── ArrayOperations.java │ ├── 01394 │ │ └── 1394. Find Lucky Integer in an Array.java │ ├── 01431 │ │ └── KidsWithCandies.java │ ├── 01437 │ │ └── 1437. Check If All 1's Are at Least Length K Places Away.java │ ├── 01460 │ │ └── MakeTwoArraysEqual.java │ ├── 01464 │ │ └── MaximumProductOfTwoElements.java │ ├── 01470 │ │ └── 1470. Shuffle the Array.java │ ├── 01480 │ │ └── 480_Running_Sum_of_1d_Array │ ├── 01491 │ │ └── AverageSalaryExcludingMinMax.java │ ├── 01502 │ │ └── CanMakeArithmeticProgression.java │ ├── 01512 │ │ └── GoodPairs.java │ ├── 01518 │ │ └── WaterBottles.java │ ├── 01528 │ │ └── ShuffleString.java │ ├── 01539 │ │ └── findKthPositive.java │ ├── 01572 │ │ └── DiagonalSum.java │ ├── 01608 │ │ └── specialArray.java │ ├── 01662 │ │ └── CheckIfStringArraysAreEquivalent.java │ ├── 01672 │ │ └── 1672. Richest Customer Wealth.java │ ├── 01732 │ │ └── 1732. Find the Highest Altitude.java │ ├── 01752 │ │ └── CheckIfSortedAndRotated.java │ ├── 01768 │ │ └── MergeStringsAlternately.java │ ├── 01773 │ │ └── CountMatchingItems.java │ ├── 01784 │ │ └── CheckBinaryStringSegment.java │ ├── 01790 │ │ └── CheckOneStringSwap.java │ ├── 01800 │ │ └── MaximumAscendingSubarraySum.java │ ├── 01832 │ │ └── 1832. Check if the Sentence Is Pangram.java │ ├── 01859 │ │ └── SortingTheSentence.java │ ├── 01863 │ │ └── SumOfAllSubsetXORTotals.java │ ├── 01886 │ │ └── MatrixRotationChecker.java │ ├── 01920 │ │ └── 1920. Build Array from Permutation.java │ ├── 01929 │ │ └── 1929. Concatenation of Array.java │ ├── 02000 │ │ └── ReversePrefixOfWord.java │ ├── 02022 │ │ └── 2022. Convert 1D Array Into 2D Array.java │ ├── 02057 │ │ └── SmallestIndexWithEqualValue.java │ ├── 02089 │ │ └── FindTargetIndices.java │ ├── 02108 │ │ └── FirstPalindromicString.java │ ├── 02119 │ │ └── NumberAfterDoubleReversal.java │ ├── 02133 │ │ └── 2133. Check if Every Row and Column Contains All Numbers.java │ ├── 02144 │ │ └── MinimumCostOfBuyingCandies.java │ ├── 02154 │ │ └── findFinalValue.java │ ├── 02206 │ │ └── DivideArrayIntoEqualPairs.java │ ├── 02215 │ │ └── findDifferenceOfTwoArrays.java │ ├── 02239 │ │ └── FindclosestNumber.java │ ├── 02248 │ │ └── intersectionOfMultipleArrays.java │ ├── 02269 │ │ └── KBeautyOfNumber.java │ ├── 02273 │ │ └── RemoveAnagrams.java │ ├── 02319 │ │ └── 2319. Check if Matrix Is X-Matrix.java │ ├── 02351 │ │ └── FirstLetterToAppearTwice.java │ ├── 02363 │ │ └── MergeSimilarItems.java │ ├── 02379 │ │ └── MinimumRecolorsToGetKConsecutiveBlackBlocks.java │ ├── 02404 │ │ └── MostFrequentEvenElement.java │ ├── 02455 │ │ └── AverageOfEvenNumbersDivisibleByThree.java │ ├── 02460 │ │ └── 2460. Apply Operations to an Array.java │ ├── 02529 │ │ └── 2529. Maximum Count.java │ ├── 02570 │ │ └── Merge2DArraysBySummingValues.java │ ├── 02595 │ │ └── 2595. Number of Even and Odd Bits.java │ ├── 02778 │ │ └── SumOfSquares.java │ ├── 02873 │ │ └── MaximumValueOfOrderedTripletI.java │ ├── 02951 │ │ └── FindPeaks.java │ ├── 02965 │ │ └── FindMissingAndRepeatedValues.java │ ├── 02996 │ │ └── MaximumRepeatingSubstring.java │ └── 03206 │ │ └── AlternatingGroupsI.java ├── hard │ ├── 00041 │ │ └── FirstMissingPositive.java │ ├── 00154 │ │ └── findMin.java │ ├── 00297 │ │ └── SerializeDeserializeBinaryTree.java │ ├── 01095 │ │ └── findInMountainArray.java │ └── 01499 │ │ └── 1499. Max Value of Equation.java └── medium │ ├── 00003 │ └── LongestSubstringWithoutRepeatingCharacters.java │ ├── 00005 │ └── LongestPalindromicSubstring.java │ ├── 00007 │ └── ReverseInteger.java │ ├── 00013 │ └── 13. House Robber II.java │ ├── 00016 │ └── ThreeSumClosest.java │ ├── 00033 │ └── RotatedSortedArraySearch.java │ ├── 00034 │ └── SearchRange.java │ ├── 00039 │ └── CombinationSum.java │ ├── 00046 │ └── Permutations.java │ ├── 00047 │ └── PermutationsII.java │ ├── 00048 │ └── 48 Rotate Image.java │ ├── 00049 │ └── GroupAnagrams.java │ ├── 00053 │ └── MaximumSubarray.java │ ├── 00054 │ └── 54. Spiral Matrix.java │ ├── 00055 │ └── 55. Jump Game.java │ ├── 00056 │ └── MergeIntervals.java │ ├── 00059 │ └── 59. Spiral Matrix II.java │ ├── 00067 │ └── 67 Two Sum II - Input Array Is Sorted.java │ ├── 00073 │ └── 73. Set Matrix Zeroes.java │ ├── 00074 │ └── searchMatrix.java │ ├── 00075 │ └── 75. Sort Colors.java │ ├── 00078 │ └── Subsets.java │ ├── 00080 │ └── 80. Remove Duplicates from Sorted Array II.java │ ├── 00081 │ └── search.java │ ├── 00082 │ └── RemoveDuplicatesFromSortedListII.java │ ├── 00086 │ └── PartitionList.java │ ├── 00090 │ └── SubsetsII.java │ ├── 00098 │ └── ValidateBinarySearchTree.java │ ├── 00099 │ └── RecoverBinarySearchTree.java │ ├── 00102 │ └── BinaryTreeLevelOrderTraversal.java │ ├── 00103 │ └── ZigzagLevelOrderTraversal.java │ ├── 00105 │ └── ConstructBinaryTreeFromPreorderInorder.java │ ├── 00106 │ └── ConstructTreeFromInorderPostorder.java │ ├── 00107 │ └── BinaryTreeLevelOrderTraversal.java │ ├── 00109 │ └── ConvertSortedListToBST.java │ ├── 00114 │ └── FlattenBinaryTreeToLinkedList.java │ ├── 00116 │ └── PopulatingNextRightPointers.java │ ├── 00128 │ └── LongestConsecutiveSequence.java │ ├── 00129 │ └── SumRootToLeafNumbers.java │ ├── 00137 │ └── singleNumber.java │ ├── 00146 │ └── LRUCache.java │ ├── 00148 │ └── SortList.java │ ├── 00152 │ └── 152 Maximum Product Subarray.java │ ├── 00153 │ └── findMin.java │ ├── 00155 │ └── MinStack.java │ ├── 00162 │ └── findPeakElement.java │ ├── 00167 │ └── twoSum.java │ ├── 00173 │ └── BSTIterator.java │ ├── 00189 │ └── 189. Rotate Array.java │ ├── 00190 │ └── peakElement.java │ ├── 00198 │ └── 198. House Robber.java │ ├── 00199 │ └── BinaryTreeRightSideView.java │ ├── 00208 │ └── Trie.java │ ├── 00229 │ └── MajorityElementII.java │ ├── 00230 │ └── KthSmallestElementInBST.java │ ├── 00235 │ └── LowestCommonAncestorBST.java │ ├── 00236 │ └── LowestCommonAncestorOfBinaryTree.java │ ├── 00238 │ └── 238. Product of Array Except Self.java │ ├── 00240 │ └── searchMatrix.java │ ├── 00287 │ └── FindDuplicate.java │ ├── 00304 │ └── NumMatrix.java │ ├── 00322 │ └── CoinChange.java │ ├── 00347 │ └── TopKFrequentElements.java │ ├── 00394 │ └── DecodeString.java │ ├── 00424 │ └── LongestRepeatingCharacterReplacement.java │ ├── 00429 │ └── NaryTreeLevelOrderTraversal.java │ ├── 00436 │ └── findRightInterval.java │ ├── 00442 │ └── findDuplicates.java │ ├── 00450 │ └── DeleteNodeInBST.java │ ├── 00503 │ └── NextGreaterElementII.java │ ├── 00540 │ └── singleNonDuplicate.java │ ├── 00622 │ └── DesignCircularQueue.java │ ├── 00701 │ └── InsertIntoBST.java │ ├── 00713 │ └── SubarrayProductLessThanK.java │ ├── 00735 │ └── AsteroidCollision.java │ ├── 00739 │ └── DailyTemperatures.java │ ├── 00852 │ └── PeakIndex.java │ ├── 00873 │ └── LongestFibonacciSubsequence.java │ ├── 00875 │ └── minEatingSpeed.java │ ├── 00901 │ └── StockSpanner.java │ ├── 00921 │ └── MinimumAddToMakeValid.java │ ├── 01004 │ └── MaxConsecutiveOnesIII.java │ ├── 01008 │ └── ConstructBSTFromPreorder.java │ ├── 01123 │ └── LowestCommonAncestorOfDeepestLeaves.java │ ├── 01352 │ └── ProductOfNumbers.java │ ├── 01358 │ └── NumberOfSubstringsContainingAllThreeCharacters.java │ ├── 01400 │ └── ConstructKPalindromeStrings.java │ ├── 01423 │ └── MaximumPointsYouCanObtainFromCards.java │ ├── 01482 │ └── minDays.java │ ├── 01616 │ └── SplitTwoStringsToMakePalindrome.java │ ├── 01630 │ └── ArithmeticSubarrays.java │ ├── 01679 │ └── Solution.java │ ├── 01749 │ └── MaximumAbsoluteSumSubarray.java │ ├── 01780 │ └── CheckIfNumberIsSumOfPowersOfThree.java │ ├── 01813 │ └── SentenceSimilarityIII.java │ ├── 01887 │ └── 1887 Reduction Operations to Make the Array Elements Equal.jav │ ├── 02140 │ └── SolvingQuestionsWithBrainpower.java │ ├── 02149 │ └── RearrangeArrayBySign.java │ ├── 02161 │ └── PartitionArrayAccordingToGivenPivot.java │ ├── 02260 │ └── MinCardsToPickUp.java │ ├── 02401 │ └── LongestNiceSubarray.java │ ├── 02410 │ └── MaximumMatchingPlayersTrainers.java │ ├── 02415 │ └── ReverseOddLevels.java │ ├── 02476 │ └── ClosestNodesQueries.java │ ├── 02523 │ └── ClosestPrimeNumbersInRange.java │ ├── 02579 │ └── CountTotalNumberOfColoredCells.java │ ├── 02780 │ └── MinimumIndexOfValidSplit.java │ ├── 03191 │ └── MinimumOperationsToMakeBinaryArrayElementsEqualToOne.java │ ├── 03208 │ └── AlternatingGroupsII.java │ └── 03462 │ └── MaximumSumWithLimits.java ├── Linked List ├── 06 reverse LinkedList.js ├── 10 doubly LinkedList.js ├── LinkedList A Singly Linked List.c ├── LinkedList A SinglyList Merge.c ├── LinkedList Circular linked list.c ├── LinkedList Doubly Circular Linked List.c ├── LinkedList Doubly Linked List.c └── LinkedList.java ├── OOP └── 04 friend class .js ├── Other Algorithms ├── 00 A Very Big Sum.js ├── 01 Diagonal Difference.js ├── 02 Area Of Circle.java ├── 03 Area Of Triangle.java ├── 04 Area Of Parallelogram.java.java ├── 05 Area Of Equilateral Triangle.java ├── 06 Perimeter Of Circle.java ├── 07 Prime.js ├── 08 Fibonacci-Sequence.js ├── 09 Kadanes Algorithm.js ├── 10 Volume Of Cone.java ├── 11 isPowerOfTwo.js ├── 12 Ncr and Npr.jav ├── 13 HCF Of Two Numbers.java ├── 14 LCM Of Two Numbers.java ├── 15 Prime.js ├── 16 prime numbers 1 to N.java ├── Disjoint Union Path compression.c ├── Disjoint Union by Rank.c └── algorithms Divide & Conquer.c ├── Queues ├── Queue Circular queue linked list.c ├── Queue Circular queue.c ├── Queue Dequeue Implementation.c ├── Queue priority queue .c ├── Queue priority queue.c ├── Queue queue array.c ├── Queue queue linked list.c ├── Queue queue stack.c └── Queue.java ├── Recursion ├── FibonacciNumber.java ├── PermutationHandler.java ├── SkipCharacters.java ├── Subsequence.java └── printSubsets.java ├── Searching ├── Binary search │ ├── BinarySearch.java │ ├── BinarySearch2D.java │ ├── Search counts the occurrences.c │ ├── Search first and last occurrence BST.c │ ├── Search Binary Search Iterative Method l │ ├── Search Binary Search Iterative Method l.C │ ├── Search Binary Search Iterative Method.C │ ├── Search Binary Search Recursive Method.C │ ├── Search Binary Search.c │ └── Search element in a circular sorted array.c ├── Linear Search │ ├── Search Linear (sequential)Search loop.C │ ├── Search Linear (sequential)Search.C │ ├── Search Second Largest & Smallest Elements in an Array.c │ ├── Search in Two Dimensional Array.c │ ├── Search largest and second-largest number.c │ ├── Search largest number in array.c │ ├── Search largest number recrsively in array.c │ ├── Search number of rotation.c │ ├── Search smallest and secondSmallest.c │ ├── Search smallest number in array.c │ └── Search smallest number recrsively.c └── infiniteArraySearch │ └── InfiniteArraySearch.java ├── Shortest Path └── README.md ├── Sorting ├── Bubble Sort │ ├── BubbleSort.java │ ├── Sort Array Exercise ascending order.c │ ├── Sort Array Exercise descending order.c │ ├── Sort Array Exercise names.c │ ├── Sort Bubble Sort Optimized Version ascending order.c │ ├── Sort Bubble Sort ascending order.c │ └── Sort Bubble Sort descending order.c ├── Bucket Sort │ └── Sort Bucket Sort.c ├── Count Sort │ ├── CountSort.java │ ├── Sort Count Sort character.c │ └── Sort Count Sort numbers.c ├── Heap Sort │ ├── Sort Heap Sort A Min-Heap.c │ ├── Sort Heap Sort A Max-Heap.c │ ├── Sort Heap Sort A Min-Heap K sorted.c │ └── Sort Heap Sort Iterative.c ├── Insertion Sort │ ├── InsertionSort.java │ ├── Sort Insertion sort ascending order.c │ ├── Sort Insertion sort descending order.c │ └── Sort Insertion sort example array.c ├── Merge Sort │ ├── MergeSort.java │ ├── Sort Merge Sort Merge 2 arrays.c │ ├── Sort Merge Sort Merge 4 arrays.c │ └── Sort Merge Sort ascending order.c ├── Quick Sort │ ├── QuickSort.java │ ├── Sort QuickSort Randomized.c │ └── Sort QuickSort implementation.c ├── Radix Sort │ └── Sort Radix Sort numbers.c ├── Selection Sort │ ├── SelectionSort.java │ ├── Sort Selection Sort ascending order.c │ └── Sort Selection Sort descending order.c ├── Shell Sort │ ├── Sort Shell sort bubble variation.c │ └── Sort Shell sort insertion variation.c ├── Topological sort │ └── Sort topological sort.c └── cycle sort │ └── CycleSort.java ├── Spanning Tree ├── graph Minimum Spanning Tree.c └── graph Minimum Spanning Tree.c ├── Stacks ├── GenericStack.java ├── Stack stack Balanced Parentheses.c ├── Stack stack Infix to Postfix.c ├── Stack stack Infix to Postfix.c ├── Stack stack Infix to Prefix.c ├── Stack stack Postfix to Infix.c ├── Stack stack array impl.c ├── Stack stack linked list.c ├── Stack stack reverse string.c └── Stack.java ├── String └── README.md ├── Trees ├── AVLTree.java ├── BinarySearchTree.java ├── SegmentTree.java ├── Tree Binary Search Tree.c ├── Tree Binary Tree Array.c ├── Tree Binary Tree Linked Lis.c ├── Tree Full Binary Tree.c ├── Tree AVL Tree.c ├── Tree B+ tree .c ├── Tree B-Tree.c ├── Tree Red-Black Tree.c └── Tree Splay Tree.c └── Trie ├── Tree Trie (Prefix Tree).c └── Trie.java /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "*html": "html", 4 | "*.php": "css", 5 | } 6 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "tasks": [ 3 | { 4 | "type": "cppbuild", 5 | "label": "C/C++: clang build active file", 6 | "command": "/usr/bin/clang", 7 | "args": [ 8 | "-fcolor-diagnostics", 9 | "-fansi-escape-codes", 10 | "-g", 11 | "${file}", 12 | "-o", 13 | "${fileDirname}/${fileBasenameNoExtension}" 14 | ], 15 | "options": { 16 | "cwd": "${fileDirname}" 17 | }, 18 | "problemMatcher": [ 19 | "$gcc" 20 | ], 21 | "group": { 22 | "kind": "build", 23 | "isDefault": true 24 | }, 25 | "detail": "Task generated by Debugger." 26 | } 27 | ], 28 | "version": "2.0.0" 29 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 saddamarbaa 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/Arrays/Arrays 2-D array and Pointers.c: -------------------------------------------------------------------------------- 1 | /** 2 | Pointers and 2-D Array Examples 3 | 4 | [AUTHOR]: Saddam Arbaa 5 | [Email] : 6 | 7 | program to access two dimensional array using pointer. 8 | Examples show Relationship Between 2 D Arrays and Pointers */ 9 | 10 | 11 | #include 12 | #include 13 | 14 | // the Driver Code 15 | int main() 16 | { 17 | /* 2D array declaration (3) rows and (3) columns. */ 18 | int array[3][3] = { {1,2,3}, 19 | {4,5,6}, 20 | {7,8,9} }; 21 | 22 | // pointer to an array of 3 integers 23 | int (*ptr)[3]; 24 | 25 | // now ptr have the base address of array 26 | ptr = array; 27 | 28 | /* 29 | array => Points to base address of two-dimensional array. 30 | Since array decays to pointer. 31 | *(array) => Points to first row of two-dimensional array. 32 | 33 | *(array + 0) => Points to first row of two-dimensional array. 34 | *(array + 1) => Points to second row of two-dimensional array. 35 | 36 | **array => Points to array[0][0] 37 | 38 | *(*(array + 0)) => Points to array[0][0] 39 | *(*(array + 0) + 0) => Points to array[0][0] 40 | *(*array + 1) => Points to array[0][1] 41 | *(*(array + 0) + 1) => Points to array[0][1] 42 | *(*(array + 2) + 2) => Points to array[2][2] 43 | 44 | and so on */ 45 | 46 | printf("----------------------------------\n"); 47 | 48 | // taking input from user and storing it in an array using pointers) 49 | 50 | // outer loop to access rows 51 | for(int i = 0; i < 3; i++) 52 | { 53 | // inner loop to access column 54 | for(int j = 0; j < 3; j++) 55 | { 56 | // asking input from user 57 | printf("Enter Array [ %d ][ %d ] : ",i,j); 58 | 59 | // *(array + i) + j = equivalent to &array[i][j] 60 | 61 | scanf("%d",*(array + i) + j); 62 | 63 | } 64 | } 65 | 66 | printf("---------------------------------\n"); 67 | 68 | printf("Element in matrix Array are : \n"); 69 | 70 | // printing elements of an array 71 | // outer loop to access rows 72 | for(int i = 0; i < 3; i++) 73 | { 74 | // inner loop to access column 75 | for(int j = 0; j < 3; j++) 76 | { 77 | // *( *(ptr + i) + j) = equivalent to array[i][j] 78 | printf("Array[ %d ][ %d ] = %d\n", i, j, *( *(ptr + i) + j) ); 79 | } 80 | 81 | // print new line after every row 82 | printf("\n"); 83 | } 84 | 85 | return 0;// signal to operating system everything works fine 86 | 87 | }/** End of main function */ 88 | -------------------------------------------------------------------------------- /src/Arrays/Arrays Three Dimensional Array declaration and initialization.c: -------------------------------------------------------------------------------- 1 | /** 2 | Three Dimensional Array declaration and initialization 3 | [AUTHOR]: Saddam Arbaa 4 | [Email] : 5 | 6 | Syntax: 7 | data_type array_name[size1][size2][size3]; 8 | 9 | Program of Three Dimensional Array in C 10 | declaration and initialization 11 | */ 12 | 13 | #include 14 | #include 15 | 16 | // the Driver Code 17 | int main() 18 | { 19 | //declaration 3 variables to be use as counter in loop 20 | int i,j,k; 21 | 22 | /* 3D array declaration */ 23 | int array[2][3][3]; 24 | 25 | /* 3D array declaration and initialization */ 26 | int threeD_Array[2][2][4] = {11, 3, 30, 15, 38, 9, -22, 24, 5, 10, 34, 56, 23, -256, 10, 37}; 27 | 28 | /* 3D array declaration and initialization */ 29 | int secondArray[3][3][3]= 30 | { {{10,20,30},{40,50,60},{70,80,90}}, //elements of block 1 31 | {{11,22,33},{44,55,66},{77,88,99}}, //elements of block 2 32 | {{12,23,34},{45,56,67},{78,89,90}} //elements of block 3 33 | }; 34 | 35 | /* 3D array declaration and initialization */ 36 | int threeDArray[3][3][3]= 37 | { 38 | {//elements of block 1 39 | {11, 12, 13}, 40 | {14, 15, 16}, 41 | {17, 18, 19} 42 | }, 43 | {//elements of block 2 44 | {21, 22, 23}, 45 | {24, 25, 26}, 46 | {27, 28, 29} 47 | }, 48 | { //elements of block 3 49 | {31, 32, 33}, 50 | {34, 35, 36}, 51 | {37, 38, 39} 52 | }, 53 | }; 54 | 55 | printf("printing the 3D array element : \n"); 56 | 57 | // we need 3 for loop for this 58 | 59 | // first loop represents block 60 | for(i = 0; i < 3; i++) 61 | { 62 | // second loop represents rows 63 | for(j = 0; j < 3; j++) 64 | { 65 | // third loop represents columns 66 | for(k = 0; k < 3; k++) 67 | { 68 | printf("%d\t",threeDArray[i][j][k]); 69 | 70 | } /** End of third loop */ 71 | 72 | printf("\n"); 73 | 74 | } /** End of second loop */ 75 | 76 | printf("\n"); 77 | 78 | }/** End of first loop */ 79 | 80 | 81 | return 0;// signal to operating system everything works fine 82 | 83 | }/** End of main function */ 84 | -------------------------------------------------------------------------------- /src/Arrays/Arrays Three Dimensional Array user input.c: -------------------------------------------------------------------------------- 1 | /** 2 | Three Dimensional Array 3 | [AUTHOR]: Saddam Arbaa 4 | [Email] : 5 | 6 | Three Dimensional Array declaration and initializing user input taking input from user 7 | */ 8 | 9 | #include 10 | #include 11 | 12 | // the Driver Code 13 | int main() 14 | { 15 | //declaration 3 variables to be use as counter in loop 16 | int i,j,k; 17 | 18 | /* 3D array declaration */ 19 | int matrix[2][3][3]; 20 | 21 | // taking input from user and storing it in an array(matrix) 22 | printf("enter the values in the array: \n"); 23 | 24 | // first loop represents block 25 | for(i = 0; i < 2; i++) 26 | { 27 | // second loop represents rows 28 | for(j = 0; j < 3; j++) 29 | { 30 | // third loop represents columns 31 | for(k = 0; k < 3; k++) 32 | { 33 | 34 | // The use of '&' before a variable name,mean user input will 35 | // be store in the address of matrix[i][j][k]. 36 | 37 | // asking input from user 38 | printf("Enter matrix[ %d ][ %d ][ %d ]: ",i,j,k); 39 | scanf("%d",&matrix[i][j][k]); 40 | 41 | } /** End of third loop */ 42 | } /** End of second loop */ 43 | 44 | } /** End of first loop */ 45 | 46 | printf("--------------------------\n"); 47 | 48 | printf("element in matrix Array are : \n"); 49 | 50 | // first loop represents block 51 | for(i = 0; i < 2; i++) 52 | { 53 | // second loop represents rows 54 | for(j = 0; j < 3; j++) 55 | { 56 | // third loop represents columns 57 | for(k = 0; k < 3; k++) 58 | { 59 | printf("%d\t",matrix[i][j][k]); 60 | 61 | } /** End of third loop */ 62 | 63 | printf("\n"); 64 | 65 | }/** End of second loop */ 66 | printf("\n"); 67 | 68 | }/** End of first loop */ 69 | 70 | return 0;// signal to operating system everything works fine 71 | 72 | }/** End of main function */ 73 | -------------------------------------------------------------------------------- /src/Arrays/Arrays Two Dimensional declaration and initialization user input.c: -------------------------------------------------------------------------------- 1 | /** 2 | [AUTHOR]: Saddam Arbaa 3 | [Email] : 4 | 5 | C two dimensional Arrays Examples 6 | Program that ask user to enter 2 number one for number 7 | of rows and one for number of columns( both must be bigger 8 | than zero) then do the flowing 9 | 10 | (1) create 2 dimensional array with number of rows and 11 | columns given 12 | 13 | (2) ask user to enter all the 2 D array element and store 14 | them in an array. 15 | 16 | (3) Print the elements stored in the array 17 | (size must be bigger than 0) 18 | 19 | */ 20 | 21 | #include 22 | 23 | // the Driver Code 24 | int main() 25 | { 26 | // variable for Rows and columns will be entered by user 27 | int row,colum; 28 | 29 | // asking the length of number of rows from user 30 | do 31 | { 32 | // asking the length of number of rows from user 33 | printf("Enter the number of Rows\n(number of Rows must be bigger than zero): "); 34 | 35 | scanf("%d",&row); 36 | 37 | }while (row <= 0); 38 | 39 | // asking the length of number of rows from user 40 | do 41 | { 42 | // asking the length of number of rows from user 43 | printf("Enter the number of columns \n(number of columns must be bigger than zero): "); 44 | 45 | scanf("%d",&colum); 46 | 47 | }while (colum <= 0); 48 | 49 | /* 2D array declaration with (row) rows and (colum) columns. */ 50 | int matrix [row][colum] ; 51 | 52 | printf("--------------------------------------\n"); 53 | 54 | // taking input from user and storing it in an array(matrix) 55 | 56 | // outer loop to access rows 57 | for(int i = 0; i < row; i++) 58 | { 59 | // inner loop to access coulm 60 | for(int j = 0; j < colum; j++) 61 | { 62 | // asking input from user 63 | printf("Enter matrix [ %d ][ %d ] : ",i,j); 64 | 65 | // The use of '&' before a variable name,mean user input will 66 | // be store in the address of matrix[i][j]. 67 | 68 | scanf("%d",& matrix[i][j]); 69 | } 70 | } 71 | 72 | printf("----------------------------\n"); 73 | 74 | printf("element in matrix Array are : \n"); 75 | 76 | // printing elements of an array 77 | // outer loop to access rows 78 | for(int i = 0; i < row; i++) 79 | { 80 | // inner loop to access coulm 81 | for(int j = 0; j < colum; j++) 82 | { 83 | 84 | printf("%d\t", matrix[i][j]); 85 | } 86 | 87 | // print new line after every row 88 | printf("\n"); 89 | 90 | } 91 | 92 | return 0;// signal to operating system everything works fine 93 | 94 | }/** End of main function */ 95 | 96 | 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /src/Arrays/Arrays Two Dimensional declaration and initialization.c: -------------------------------------------------------------------------------- 1 | /* 2 | [AUTHOR]: Saddam Arbaa 3 | [Email] : 4 | 5 | Two Dimensional Array in C 6 | in C we can create an array of arrays 7 | (defined as an array of arrays). 8 | These arrays are known as multidimensional arrays 9 | because A two-dimensional array is an array in which 10 | each element is itself a 1-D array 11 | 12 | The syntax to declare the 2D array 13 | data_type array_name[rows][columns]; */ 14 | 15 | 16 | #include 17 | #include 18 | 19 | // the Driver Code 20 | int main() 21 | { 22 | /* 2D array declaration with 4 rows and 4 columns. */ 23 | int AA[4][4]; 24 | 25 | // Different ways to initialize two-dimensional array in c 26 | int c[2][3] = {{4, 12, 6}, {0, 15, 8}}; 27 | 28 | int u[][3] = {{1, 3, 2}, {-11, 15, 19}}; 29 | 30 | int p[2][3] = {{1, 2, 0, },{-1, 5, 9}}; 31 | 32 | /* 2D array declaration with 3 rows and 4 columns. */ 33 | int B[3][4] = { 34 | 35 | {10, 1, 2, 33} , /* initializers for row indexe 0 */ 36 | 37 | {43, 5, 6, 17} , /* initializers for row indexed 1 */ 38 | 39 | {6, 9, 0, 21} /* initializers for row indexed 2 */ 40 | }; 41 | 42 | //traversing 2D array 43 | // access rows of the array 44 | for(int i = 0; i < 4; i++) 45 | { 46 | // access columns of the array 47 | for(int j = 0; j < 3; j++) 48 | { 49 | printf("array B[ %d] [%d] = %d \n",i,j,B[i][j]); 50 | } //end of j 51 | } //end of i 52 | 53 | return 0;// signal to operating system everything works fine 54 | 55 | }/** End of main function */ 56 | -------------------------------------------------------------------------------- /src/Arrays/Arrays Two Dimensional sum of Rows.c: -------------------------------------------------------------------------------- 1 | /** 2 | [AUTHOR]: Saddam Arbaa 3 | [Email] : 4 | 5 | write C program that do the flowing 6 | 7 | (1)declare Two Dimensional Array named matrix[3][3] 8 | 9 | (2) ask user to enter all the array element and store 10 | them in matrix array 11 | 12 | (3) Print the elements stored in the array 13 | 14 | (4) find the sum of numbers in each row and printed 15 | 16 | (4) find the sum of all numbers which entered by user 17 | 18 | (5) print the sum of all number at last 19 | 20 | */ 21 | 22 | 23 | #include 24 | #include 25 | 26 | // the Driver Code 27 | int main() 28 | { 29 | /* 2D array declaration with 3 rows and 3 columns. */ 30 | int matrix[3][3]; 31 | 32 | // variable to store sum of all numbers 33 | int sum = 0; 34 | 35 | // variable to store sum of each row numbers 36 | int sum_of_each_row; 37 | 38 | printf("Enter All the numbers :\n"); 39 | 40 | // taking input from user and storing it in an array(matrix) 41 | 42 | for(int row = 0; row < 3; row++) 43 | { 44 | /* 45 | make sum_of_eachrow variable to zero after 46 | calculate and printing sum of each row */ 47 | 48 | sum_of_each_row = 0; 49 | 50 | // inner loop to access coulmn 51 | for(int coulm = 0; coulm < 3; coulm++) 52 | { 53 | // asking input from user 54 | printf("Enter matrix [ %d ][ %d ] : ",row,coulm); 55 | 56 | // The use of '&' before a variable name,mean user input will 57 | // be store in the address of matrix[row][coulm]. 58 | 59 | scanf("%d",& matrix[row][coulm]); 60 | 61 | // calculation the sum of each row 62 | sum_of_each_row = sum_of_each_row + matrix[row][coulm]; 63 | 64 | // calculation the sum of all number 65 | // sum = sum + matrix[row][coulm]; 66 | // also we can calculate outside like blow 67 | 68 | } 69 | 70 | printf ("the sum of row number [ %d ] : %d \n",(row + 1),sum_of_each_row); 71 | 72 | // calculation the sum of all number 73 | sum = sum + sum_of_each_row; 74 | } 75 | 76 | printf("\n"); 77 | 78 | printf("--------------------------------------\n"); 79 | 80 | // printing elements of an array 81 | // outer loop to access rows 82 | for(int row = 0; row < 3; row++) 83 | { 84 | // inner loop to access coulm 85 | for(int coulm = 0; coulm < 3; coulm++) 86 | { 87 | printf("matrix [ %d [ %d ] : %d\n",row,coulm,matrix[row][coulm]); 88 | 89 | } 90 | } 91 | 92 | // printing the sum of numbers 93 | printf("The sum of all elements is : %d\n",sum); 94 | 95 | return 0;// signal to operating system everything works fine 96 | 97 | }/** End of main function */ 98 | 99 | -------------------------------------------------------------------------------- /src/Arrays/Arrays Two Dimensional sum of columns.c: -------------------------------------------------------------------------------- 1 | /** 2 | [AUTHOR]: Saddam Arbaa 3 | [Email] : 4 | 5 | write C program that do the flowing 6 | 7 | (1)declare Two Dimensional Array named matrix[3][3] 8 | 9 | (2) ask user to enter all the array element and store 10 | them in matrix array 11 | 12 | (3) Print the elements stored in the array 13 | 14 | (4) find the sum of numbers in each columns and printed 15 | 16 | */ 17 | 18 | #include 19 | #include 20 | 21 | // the Driver Code 22 | int main() 23 | { 24 | /* 2D array declaration with 3 rows and 3 columns. */ 25 | int matrix[3][3]; 26 | 27 | /* variable to store sum of numbers in each column 28 | i don,t give any value because in each loop start 29 | i will make it value to zero */ 30 | 31 | int sum = 0; 32 | 33 | printf("Enter All the numbers :\n"); 34 | 35 | // taking input from user and storing it in an array(matrix) 36 | 37 | for(int row = 0; row < 3; row++) 38 | { 39 | // inner loop to access column 40 | for(int coulm = 0; coulm < 3; coulm++) 41 | { 42 | // asking input from user 43 | printf("Enter matrix [ %d ][ %d ] : ",row,coulm); 44 | 45 | // The use of '&' before a variable name,mean user input will 46 | // be store in the address of matrix[row][coulm]. 47 | 48 | scanf("%d",& matrix[row][coulm]); 49 | } 50 | } 51 | 52 | printf("--------------------------------------\n"); 53 | printf("Element in Array are :\n"); 54 | 55 | // printing elements of an array 56 | // outer loop to access rows 57 | for(int row = 0; row < 3; row++) 58 | { 59 | // inner loop to access column 60 | for(int coulm = 0; coulm < 3; coulm++) 61 | { 62 | printf("%d\t",matrix[row][coulm]); 63 | } 64 | 65 | // new new after printing element in each row 66 | printf("\n"); 67 | } 68 | 69 | // loop to calculate the sum of number in each 70 | // column and printed 71 | 72 | // outer loop to access rows 73 | for(int row = 0; row < 3; row++) 74 | { 75 | 76 | /* 77 | make sum variable to zero after calculate and 78 | printing sum of numbers each in column */ 79 | 80 | sum = 0; 81 | 82 | // inner loop to access column 83 | for(int coulm = 0; coulm < 3; coulm++) 84 | { 85 | // calculation the sum of each row 86 | sum = sum + matrix[coulm][row]; 87 | } 88 | 89 | printf ("the sum of number in column [ %d ] : %d \n",(row + 1),sum); 90 | 91 | } 92 | return 0;// signal to operating system everything works fine 93 | 94 | }/** End of main function */ 95 | 96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /src/Arrays/Arrays Two Dimensional sum of numbers.c: -------------------------------------------------------------------------------- 1 | /** 2 | [AUTHOR]: Saddam Arbaa 3 | [Email] : 4 | 5 | write C program that do the flowing 6 | 7 | (1) declare Two Dimensional Array named matrix[3][3] 8 | 9 | (2) ask user to enter all the array element and store 10 | them in matrix array 11 | 12 | (3) Print the elements stored in the array 13 | 14 | (4) find the sum of n numbers which entered by user 15 | 16 | (5) print the sum */ 17 | 18 | #include 19 | #include 20 | 21 | // the Driver Code 22 | int main() 23 | { 24 | /* 2D array declaration with 3 rows and 3 columns. */ 25 | int matrix[3][3]; 26 | 27 | // variable to store sum of all numbers 28 | int sum = 0; 29 | 30 | printf("Enter All the numbers :\n"); 31 | 32 | // taking input from user and storing it in an array(matrix) 33 | for(int row = 0; row < 3; row++) 34 | { 35 | // inner loop to access coulmn 36 | for(int coulm = 0; coulm < 3; coulm++) 37 | { 38 | // asking input from user 39 | printf("Enter matrix [ %d ][ %d ] : ",row,coulm); 40 | 41 | // The use of '&' before a variable name,mean user input will 42 | // be store in the address of matrix[row][coulm]. 43 | 44 | scanf("%d",& matrix[row][coulm]); 45 | 46 | // calculation the sum of all numbers 47 | sum = sum + matrix[row][coulm]; 48 | } 49 | } 50 | 51 | printf("-----------------------------\n"); 52 | 53 | // printing elements of an array 54 | // outer loop to access rows 55 | for(int row = 0; row < 3; row++) 56 | { 57 | // inner loop to access coulm 58 | for(int coulm = 0; coulm < 3; coulm++) 59 | { 60 | printf("matrix [ %d [ %d ] : %d\n",row,coulm,matrix[row][coulm]); 61 | 62 | } 63 | } 64 | 65 | // printing the sum of numbers 66 | printf("The sum of all elements is : %d\n",sum); 67 | 68 | return 0;// signal to operating system everything works fine 69 | 70 | }/** End of main function */ 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /src/Arrays/Arrays change number .c: -------------------------------------------------------------------------------- 1 | /** 2 | [AUTHOR]: Saddam Arbaa 3 | [Email] : 4 | 5 | C Arrays Examples 6 | Program to take array size from user and create array with 7 | the size given by user and then ask user to enter all the array 8 | element and store them in an array. 9 | the lastly do the flowing 10 | (1) Print all the element in array 11 | (2) change all the number bigger than zero to one and all the smaller than zero to -1 12 | (3) Print all the element in array again 13 | the array(size must be bigger than 0) 14 | */ 15 | 16 | 17 | #include 18 | #include 19 | 20 | // the Driver Code 21 | int main() 22 | { 23 | // size of the array and counter i 24 | int N ,i; 25 | 26 | // get valid size first 27 | do 28 | { 29 | // asking the length of array from user 30 | printf("Enter number of elements(size must be bigger than zero): "); 31 | scanf("%d",&N); 32 | 33 | } while (N <= 0); 34 | 35 | // Array declaration 36 | int vector [N]; 37 | 38 | printf("-----------------\n"); 39 | 40 | printf("Enter %d numbers: \n",N); 41 | 42 | // taking input from user and storing it in an array 43 | for (i = 0; i <= N - 1; i++) 44 | { 45 | // The use of '&' before a variable name,mean user input will 46 | // be store in the address of variable. 47 | 48 | printf("Enter vector[ %d ]: ",(i+1) ); 49 | scanf("%d",&vector[i]); 50 | } 51 | 52 | printf("-------------------------\n"); 53 | 54 | printf("element in Array are : \n"); 55 | 56 | // printing elements of an array 57 | for (i = 0; i <= N - 1; i++) 58 | { 59 | printf("vector[ %d ] : %d\n", i +1 ,vector[i]); 60 | } 61 | 62 | // change number bigger than zero to 1 and smaller to -1 63 | for (i = 0; i <= N - 1; i++) 64 | { 65 | if (vector[i] > 0) 66 | { 67 | vector[i] = 1; //change to 1 68 | } 69 | else if (vector[i] < 0) 70 | { 71 | vector[i] = -1; //change to -1 72 | } 73 | } 74 | 75 | printf("---------------------------\n"); 76 | printf("element in Array are: \n"); 77 | 78 | // printing elements of an array again 79 | for (i = 0; i <= N - 1; i++) 80 | { 81 | printf("vector[ %d ] : %d\n", i +1 ,vector[i]); 82 | } 83 | 84 | return 0;// signal to operating system everything works fine 85 | 86 | }/** End of main function */ 87 | -------------------------------------------------------------------------------- /src/Arrays/Arrays declaration and initializing.c: -------------------------------------------------------------------------------- 1 | /** 2 | [AUTHOR]: Saddam Arbaa 3 | [Email] : 4 | 5 | C Arrays Examples 6 | Program to take array size from user and create array with 7 | the size given user and ask user to enter all the array 8 | element and store them in an array and lastly Print the 9 | elements stored in the array(size must be bigger than 0) 10 | */ 11 | 12 | 13 | #include 14 | #include 15 | 16 | // the Driver Code 17 | int main() 18 | { 19 | // N size of the array and counter i 20 | int N ,i; 21 | 22 | // get valid size first 23 | do 24 | { 25 | // asking the length of array from user 26 | printf("Enter the length of the vector(size must be bigger than zero): "); 27 | scanf("%d",&N); 28 | 29 | } while (N <= 0); 30 | 31 | // Array declaration 32 | int vector [N]; 33 | 34 | printf("---------------------------------\n"); 35 | 36 | printf("Enter %d integers: \n",N); 37 | 38 | // taking input from user and storing it in an array 39 | for (i = 0; i <= N - 1; i++) 40 | { 41 | // The use of '&' before a variable name,mean user input will 42 | // be store in the address of variable. 43 | 44 | printf("Enter vector[ %d ]: ",(i+1) ); 45 | scanf("%d",&vector[i]); 46 | } 47 | 48 | printf("--------------------------------\n"); 49 | 50 | printf("Displaying integers: \n"); 51 | 52 | // printing elements of an array 53 | for (i = 0; i <= N - 1; i++) 54 | { 55 | printf("vector[ %d ] : %d\n", i +1 ,vector[i]); 56 | 57 | } 58 | 59 | return 0;// signal to operating system everything works fine 60 | 61 | }/** End of main function */ 62 | -------------------------------------------------------------------------------- /src/Arrays/Arrays one-D array and Pointers.c: -------------------------------------------------------------------------------- 1 | /** 2 | [AUTHOR]: Saddam Arbaa 3 | [Email] : 4 | 5 | C Arrays and Pointers Examples 6 | Examples show different idea Relationship Between 7 | Arrays and Pointers */ 8 | 9 | 10 | #include 11 | #include 12 | 13 | // the Driver Code 14 | int main() 15 | { 16 | // N size of the array and counter i 17 | int N ,i; 18 | 19 | // get valid size first 20 | do 21 | { 22 | // asking the length of array from user 23 | printf("Enter the length of the vector(size must be bigger than zero): "); 24 | scanf("%d",&N); 25 | 26 | } while (N <= 0); 27 | 28 | // Array declaration 29 | int vector [N]; 30 | 31 | // Pointer to an integer 32 | int *p; 33 | 34 | // Pointer to an array of N integers 35 | int (*ptr)[N]; 36 | 37 | // Points to 0th element of the array vector 38 | p = vector; 39 | 40 | // Points to 0th element of the array vector 41 | int *q = vector; 42 | 43 | // both give same address 44 | //printf("%p\t%p\t",p,vector ); 45 | 46 | printf("-----------------------------------\n"); 47 | 48 | printf("Enter %d number for vector Array: \n",N); 49 | 50 | // taking input from user and storing it in an array 51 | for (i = 0; i <= N - 1; i++) 52 | { 53 | // The use of '&' before a variable name,mean user input will 54 | // be store in the address of variable. 55 | // all blow give same result 56 | //printf("Enter vector[ %d ]: ",(i+1) ); 57 | //scanf("%d",&vector[i]); 58 | 59 | //printf("Enter vector[ %d ]: ",(i+1) ); 60 | //scanf("%d",(q+i) ); 61 | 62 | printf("Enter vector[ %d ]: ",(i+1) ); 63 | scanf("%d",&vector[i]); 64 | } 65 | 66 | printf("-----------------------------------\n"); 67 | 68 | printf("Displaying value in vector Array: \n"); 69 | 70 | // printing elements of an array 71 | for (i = 0; i <= N - 1; i++) 72 | { 73 | // all blow give same result 74 | //printf("vector[ %d ] : %d\n", i +1 ,vector[i]); 75 | 76 | printf("vector[ %d ] : %d\n", i +1 ,( *q + i)); 77 | // *q + i = vector[i] 78 | 79 | } 80 | // Array of 5 integer 81 | int array[5] = {10, 20, 30, 40, 50}; 82 | 83 | // Pointer to an integer 84 | int * ptrr; 85 | 86 | // ptr is assigned the address of the third element 87 | ptrr = & array[3]; 88 | printf("\n*ptrr = %d \n",*ptrr);// 40 89 | printf("\n*(ptrr + 1) = %d \n",*(ptrr + 1 ));// 50 90 | printf("\n*(ptrr - 1) = %d \n",*(ptrr - 1));// 30 91 | 92 | return 0;// signal to operating system everything works fine 93 | 94 | }/** End of main function */ 95 | -------------------------------------------------------------------------------- /src/Arrays/Arrays one-dimensional array.c: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | [AUTHOR]: Saddam Arbaa 4 | [Email] : 5 | 6 | C Arrays 7 | 8 | Arrays are used to store multiple values in a single variable, 9 | instead of declaring separate variables for each value. 10 | 11 | so An array is defined as the collection of similar type of data items 12 | stored at contiguous memory locations. Arrays are the derived data type 13 | in C programming language which can store the primitive type of data such 14 | as int, char, double, float, etc. It also has the capability to store 15 | the collection of derived data types, such as pointers, structure, etc. 16 | The array is the simplest data structure where each data element can be 17 | randomly accessed by using its index number. 18 | 19 | By using the array, we can access the elements easily. 20 | 21 | To declare an array, define the variable type, specify the 22 | name of the array followed by square brackets and specify the 23 | number of elements it should store: 24 | 25 | */ 26 | 27 | #include 28 | #include 29 | 30 | int main() 31 | { 32 | 33 | // Array declaration by initializing elements 34 | int fullmark[] = {5, 10, 20, 30, 40, 50, 60}; 35 | 36 | // declare an array of user specified size 37 | int m = 100; 38 | int array[m]; 39 | 40 | // Array declaration by specifying size and initializing elements 41 | int arr[7] = { 1, 2, 3, 4, 5}; 42 | 43 | // Compiler creates an array of size 7, initializes first 44 | // 5 elements as specified by user and rest two elements as 0. 45 | // above is same as "int arr[] = {1, 2, 3, 4, 5, 0,0}" 46 | 47 | int grde[5] = {100, 200, 300, 400, 500}; 48 | 49 | /*You can also initialize an array like this. 50 | int grade[] = {100, 200, 300, 400, 500}; 51 | Here, we haven't specified the size. However, 52 | the compiler knows its size is 5 as we are 53 | initializing it with 5 elements 54 | 55 | grde[0] is equal to 100 56 | grde[1] is equal to 200 57 | grde[2] is equal to 300 58 | grde[3] is equal to 400 59 | grde[4] is equal to 500 60 | 61 | */ 62 | 63 | //Change Value of Array elements 64 | 65 | int grade[5] = {100, 200, 300, 400, 500}; 66 | 67 | // make the value of the third element to 11 68 | grade[2] = 11; 69 | 70 | // make the value of the fifth element to 50 71 | grade[4] = 50; 72 | 73 | //Input and Output Array Elements 74 | 75 | // print the first element of the array 76 | printf("%d\n", grade[0]); 77 | 78 | // print the third element of the array 79 | printf("%d\n", grade[2]); 80 | 81 | // print ith element of the array 82 | //printf("%d", grade[i -1]); 83 | 84 | return 0;// signal to operating system everything works fine 85 | 86 | }/** End of main function */ 87 | -------------------------------------------------------------------------------- /src/Arrays/Arrays positive,negative zero number.c: -------------------------------------------------------------------------------- 1 | /** 2 | [AUTHOR]: Saddam Arbaa 3 | [Email] : 4 | 5 | C Arrays Examples 6 | Program to take array size from user and create array with 7 | the size given by user and ask user to enter all the array 8 | element and store them in an array. 9 | the lastly 10 | Print the number of element bigger than zero (positive number) 11 | Print the number of element bigger smaller than zero(negative number) 12 | Print the number of element equal to zero 13 | the array(size must be bigger than 0) 14 | */ 15 | 16 | #include 17 | #include 18 | 19 | // the Driver Code 20 | int main() 21 | { 22 | // size of the array N and counter i 23 | int N ,i; 24 | 25 | /* I need 3 variables one to store numbers of positive number 26 | one to store numbers of negative number and one to store 27 | zero numbers */ 28 | 29 | int positive_number = 0; 30 | int negative_number = 0; 31 | int zero_numbers = 0; 32 | 33 | // get valid size first 34 | do 35 | { 36 | // asking the length of array from user 37 | printf("Enter number of elements(size must be bigger than zero): "); 38 | scanf("%d",&N); 39 | } while (N <= 0); 40 | 41 | // Array declaration 42 | int vector [N]; 43 | 44 | printf("-----------------------------\n"); 45 | 46 | printf("Enter %d numbers: \n",N); 47 | 48 | // taking input from user and storing it in an array 49 | for (i = 0; i <= N - 1; i++) 50 | { 51 | // The use of '&' before a variable name,mean user input will 52 | // be store in the address of variable. 53 | 54 | printf("Enter vector[ %d ]: ",(i+1) ); 55 | scanf("%d",&vector[i]); 56 | 57 | if (vector[i] > 0) 58 | { 59 | positive_number++;// update positive numbers 60 | } 61 | else if (vector[i] < 0) 62 | { 63 | negative_number++; // update negative_number 64 | } 65 | else 66 | { 67 | zero_numbers++; // update zero_numbers 68 | } 69 | 70 | } 71 | 72 | printf("--------------------------\n"); 73 | 74 | printf("element in Array are: \n"); 75 | 76 | // printing elements of an array 77 | for (i = 0; i <= N - 1; i++) 78 | { 79 | printf("vector[ %d ] : %d\n", i +1 ,vector[i]); 80 | } 81 | 82 | // printing the number of positive numbers 83 | printf("\nThe number of positive numbers is : %d \n", positive_number); 84 | 85 | // printing the number of negative numbers 86 | printf("The number of negative numbers is : %d \n", negative_number); 87 | 88 | // printing the number zero negative numbers 89 | printf("The number of zero numbers is: %d \n", zero_numbers); 90 | 91 | return 0;// signal to operating system everything works fine 92 | 93 | }/** End of main function */ 94 | -------------------------------------------------------------------------------- /src/Arrays/Arrays sum and average.c: -------------------------------------------------------------------------------- 1 | /** 2 | [AUTHOR]: Saddam Arbaa 3 | 4 | [Email] : 5 | 6 | C Arrays Examples 7 | Program to take array size from user and create array with 8 | the size given by user and ask user to enter all the array 9 | element and store them in an array. 10 | Print the elements stored in the array(size must be bigger than 0) 11 | find the sum and average of n numbers which entered by user 12 | print the sum and and average */ 13 | 14 | #include 15 | #include 16 | 17 | /* function to Valid size for array */ 18 | int get_Valid_Size(int); 19 | 20 | int main() // the Driver Code 21 | { 22 | int N; // size of the array 23 | float sum = 0.0; // variables sum and average 24 | double average; 25 | 26 | /* get valid size first */ 27 | N = get_Valid_Size('V'); /* call get_Valid_Size() */ 28 | 29 | int vector [N]; // Array declaration 30 | 31 | printf("-----------------------------------------\n"); 32 | printf("Enter the elements one by one %d numbers \n",N); 33 | 34 | // taking input from user and storing it in an array 35 | for (int i = 0; i <= N - 1; i++) 36 | { 37 | // The use of '&' before a variable name,mean user input will 38 | // be store in the address of variable. 39 | 40 | printf("Enter vector[ %d ]: ",(i+1) ); 41 | scanf("%d",&vector[i]); 42 | 43 | /* Summation starts */ 44 | // adding number entered by the user to the sum variable 45 | sum += vector[i]; /*this means sum = sum + vector[i] */ 46 | printf("\nsum = %.1f \n", sum); 47 | } 48 | 49 | average = (double)sum/(double)N; // calculation average 50 | 51 | printf(" -----------------\n"); 52 | 53 | printf("Elements in array are : \n"); 54 | 55 | // printing elements of an array 56 | for (int i = 0; i <= N - 1; i++) 57 | printf("vector[ %d ] : %d\n", i +1 ,vector[i]); 58 | 59 | // printing the average and sum 60 | printf("\n Sum of all numbers = %.2f\n", sum); 61 | 62 | printf("\n Average of all input numbers = %.2f\n",average); 63 | 64 | return 0;// signal to operating system everything works fine 65 | 66 | } /** End of main function */ 67 | 68 | 69 | /** 70 | function to get valid size for given array, the valid size here 71 | is positive number bigger than zero and less than maximum array size 72 | */ 73 | 74 | int get_Valid_Size(int A) 75 | { 76 | int size; // variable declaration 77 | 78 | do // get valid size for Array 79 | { 80 | // asking the length of array from user 81 | printf("Enter size for Array : size must be bigger than zero : "); 82 | scanf("%d", &size); 83 | } while(size <= 0); 84 | 85 | /* if its reach this line already got the valid size just return */ 86 | return size; 87 | 88 | } /** END of get_Valid_Size */ 89 | -------------------------------------------------------------------------------- /src/Dynamic Programming/README.md: -------------------------------------------------------------------------------- 1 | # Todo 2 | 3 | -------------------------------------------------------------------------------- /src/HackerRank/00 A Very Big Sum.js: -------------------------------------------------------------------------------- 1 | // HackerRank (A Very Big Sum problem) => Array Sum 2 | // https://www.hackerrank.com/challenges/a-very-big-sum/problem 3 | 4 | "use strict"; 5 | 6 | const fs = require("fs"); 7 | 8 | process.stdin.resume(); 9 | process.stdin.setEncoding("utf-8"); 10 | 11 | let inputString = ""; 12 | let currentLine = 0; 13 | 14 | process.stdin.on("data", (inputStdin) => { 15 | inputString += inputStdin; 16 | }); 17 | 18 | process.stdin.on("end", (_) => { 19 | inputString = inputString 20 | .replace(/\s*$/, "") 21 | .split("\n") 22 | .map((str) => str.replace(/\s*$/, "")); 23 | 24 | main(); 25 | }); 26 | 27 | function readLine() { 28 | return inputString[currentLine++]; 29 | } 30 | 31 | // Complete the aVeryBigSum function below. 32 | function aVeryBigSum(ar) { 33 | let result = 0; 34 | for (let i = 0; i < ar.length; i++) { 35 | result += ar[i]; 36 | // console.log(result) 37 | } 38 | // console.log(result) 39 | return result; 40 | } 41 | 42 | function main() { 43 | const ws = fs.createWriteStream(process.env.OUTPUT_PATH); 44 | 45 | const arCount = parseInt(readLine(), 10); 46 | 47 | const ar = readLine() 48 | .split(" ") 49 | .map((arTemp) => parseInt(arTemp, 10)); 50 | 51 | let result = aVeryBigSum(ar); 52 | 53 | ws.write(result + "\n"); 54 | 55 | ws.end(); 56 | } 57 | -------------------------------------------------------------------------------- /src/HackerRank/01 Diagonal Difference.js: -------------------------------------------------------------------------------- 1 | // HackerRank (Diagonal Difference problem) => 2D Array 2 | // https://www.hackerrank.com/challenges/diagonal-difference/problem 3 | 4 | "use strict"; 5 | 6 | const fs = require("fs"); 7 | 8 | process.stdin.resume(); 9 | process.stdin.setEncoding("utf-8"); 10 | 11 | let inputString = ""; 12 | let currentLine = 0; 13 | 14 | process.stdin.on("data", function (inputStdin) { 15 | inputString += inputStdin; 16 | }); 17 | 18 | process.stdin.on("end", function () { 19 | inputString = inputString.split("\n"); 20 | 21 | main(); 22 | }); 23 | 24 | function readLine() { 25 | return inputString[currentLine++]; 26 | } 27 | 28 | /* 29 | * Complete the 'diagonalDifference' function below. 30 | * 31 | * The function is expected to return an INTEGER. 32 | * The function accepts 2D_INTEGER_ARRAY arr as parameter. 33 | */ 34 | 35 | function diagonalDifference(arr) { 36 | // Write your code here 37 | let firstDiagonalSum = 0; 38 | let secondDiagonalSum = 0; 39 | let totalSum = 0; 40 | 41 | for (let i = 0, length = arr.length; i < length; i++) { 42 | firstDiagonalSum += arr[i][i]; 43 | secondDiagonalSum += arr[length - 1 - i][i]; 44 | } 45 | totalSum = Math.abs(firstDiagonalSum - secondDiagonalSum); 46 | return totalSum; 47 | } 48 | 49 | function main() { 50 | const ws = fs.createWriteStream(process.env.OUTPUT_PATH); 51 | 52 | const n = parseInt(readLine().trim(), 10); 53 | 54 | let arr = Array(n); 55 | 56 | for (let i = 0; i < n; i++) { 57 | arr[i] = readLine() 58 | .replace(/\s+$/g, "") 59 | .split(" ") 60 | .map((arrTemp) => parseInt(arrTemp, 10)); 61 | } 62 | 63 | const result = diagonalDifference(arr); 64 | 65 | ws.write(result + "\n"); 66 | 67 | ws.end(); 68 | } 69 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00070/ClimbingStairs.java: -------------------------------------------------------------------------------- 1 | /*** 2 | * 70. Climbing Stairs 3 | * 4 | * Easy 5 | * 6 | * You are climbing a staircase. It takes n steps to reach the top. 7 | * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 8 | * 9 | * Example: 10 | * Input: n = 3 11 | * Output: 3 12 | * Explanation: 13 | * There are three ways to climb to the top: 14 | * 1. 1 step + 1 step + 1 step 15 | * 2. 1 step + 2 steps 16 | * 3. 2 steps + 1 step 17 | * 18 | * Constraints: 19 | * - 1 <= n <= 45 20 | */ 21 | 22 | public class ClimbingStairs { 23 | 24 | // ================================================== 25 | // Solution 1: Recursive Approach (inefficient) 26 | // ================================================== 27 | public int climbStairs(int n) { 28 | if (n == 1) return 1; 29 | if (n == 2) return 2; 30 | return climbStairs(n - 1) + climbStairs(n - 2); 31 | } 32 | 33 | // ================================================== 34 | // Solution 2: Iterative Approach (efficient) 35 | // ================================================== 36 | public int climbStairsIterative(int n) { 37 | if (n == 1) return 1; 38 | if (n == 2) return 2; 39 | 40 | int a = 1, b = 2; 41 | for (int i = 3; i <= n; i++) { 42 | int temp = a + b; 43 | a = b; 44 | b = temp; 45 | } 46 | return b; 47 | } 48 | 49 | // ================================================== 50 | // Main method to test the solution 51 | // ================================================== 52 | public static void main(String[] args) { 53 | ClimbingStairs solution = new ClimbingStairs(); 54 | 55 | // Test case 1: 56 | int n = 3; 57 | System.out.println("Test case 1: " + solution.climbStairs(n)); // Output: 3 58 | System.out.println("Test case 1 (iterative): " + solution.climbStairsIterative(n)); // Output: 3 59 | 60 | // Test case 2: 61 | n = 5; 62 | System.out.println("Test case 2: " + solution.climbStairs(n)); // Output: 8 63 | System.out.println("Test case 2 (iterative): " + solution.climbStairsIterative(n)); // Output: 8 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00108/SortedArrayToBST.java: -------------------------------------------------------------------------------- 1 | /** 2 | 108. Convert Sorted Array to Binary Search Tree 3 | 4 | Easy 5 | 6 | Given an integer array nums where the elements are sorted in ascending order, convert it to a 7 | height-balanced 8 | binary search tree. 9 | 10 | Example 1: 11 | 12 | Input: nums = [-10,-3,0,5,9] 13 | Output: [0,-3,9,-10,null,5] 14 | Explanation: [0,-10,5,null,-3,null,9] is also accepted: 15 | 16 | Example 2: 17 | 18 | 19 | Input: nums = [1,3] 20 | Output: [3,1] 21 | Explanation: [1,null,3] and [3,1] are both height-balanced BSTs. 22 | 23 | 24 | Constraints: 25 | 26 | 1 <= nums.length <= 104 27 | -104 <= nums[i] <= 104 28 | nums is sorted in a strictly increasing order. 29 | */ 30 | 31 | public class SortedArrayToBST { 32 | 33 | // TreeNode class definition 34 | public static class TreeNode { 35 | int val; 36 | TreeNode left; 37 | TreeNode right; 38 | TreeNode() {} 39 | TreeNode(int val) { this.val = val; } 40 | TreeNode(int val, TreeNode left, TreeNode right) { 41 | this.val = val; 42 | this.left = left; 43 | this.right = right; 44 | } 45 | } 46 | 47 | /** 48 | * Converts a sorted array into a height-balanced binary search tree. 49 | * 50 | * @param nums the sorted array of integers 51 | * @return the root node of the constructed BST 52 | */ 53 | public TreeNode sortedArrayToBST(int[] nums) { 54 | return buildBST(nums, 0, nums.length - 1); 55 | } 56 | 57 | /** 58 | * Helper method to build the BST recursively from the sorted array. 59 | * 60 | * @param nums the sorted array 61 | * @param start the starting index of the current subarray 62 | * @param end the ending index of the current subarray 63 | * @return the root node of the subtree constructed from the subarray 64 | */ 65 | private TreeNode buildBST(int[] nums, int start, int end) { 66 | if (start > end) { 67 | return null; 68 | } 69 | // Find the middle index to ensure the tree is height-balanced 70 | int mid = start + (end - start) / 2; 71 | TreeNode node = new TreeNode(nums[mid]); 72 | // Recursively build left and right subtrees 73 | node.left = buildBST(nums, start, mid - 1); 74 | node.right = buildBST(nums, mid + 1, end); 75 | return node; 76 | } 77 | 78 | // Main method for testing 79 | public static void main(String[] args) { 80 | SortedArrayToBST solution = new SortedArrayToBST(); 81 | int[] nums = {-10, -3, 0, 5, 9}; 82 | TreeNode root = solution.sortedArrayToBST(nums); 83 | // The root should be the middle element of the array, which is 0 84 | System.out.println("Root value: " + root.val); // Output: 0 85 | } 86 | } -------------------------------------------------------------------------------- /src/LeetCode/easy/00136/136. Single Number.java: -------------------------------------------------------------------------------- 1 | /* 2 | 136. Single Number 3 | Easy 4 | Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. 5 | 6 | You must implement a solution with a linear runtime complexity and use only constant extra space. 7 | 8 | Example 1: 9 | 10 | Input: nums = [2,2,1] 11 | Output: 1 12 | Example 2: 13 | 14 | Input: nums = [4,1,2,1,2] 15 | Output: 4 16 | Example 3: 17 | 18 | Input: nums = [1] 19 | Output: 1 20 | Constraints: 21 | 22 | 1 <= nums.length <= 3 * 104 23 | -3 * 104 <= nums[i] <= 3 * 104 24 | Each element in the array appears twice except for one element which appears only once. 25 | */ 26 | 27 | 28 | import java.util.Arrays; 29 | 30 | public class SingleNumber { 31 | public static void main(String[] args) { 32 | int[] nums1 = {1, 2, 2, 3, 3, 4, 4}; 33 | int expected1 = 1; 34 | int result1 = singleNumber(nums1); 35 | System.out.println("Test Case 1 - Input: " + Arrays.toString(nums1)); 36 | System.out.println("Test Case 1 - Expected result: " + expected1); 37 | System.out.println("Test Case 1 - Actual result: " + result1); 38 | System.out.println("Test Case 1 - Result matches expected: " + (result1 == expected1)); 39 | 40 | int[] nums2 = {5, 5, 3, 3, 4, 4, 2}; 41 | int expected2 = 2; 42 | int result2 = singleNumber(nums2); 43 | System.out.println("Test Case 2 - Input: " + Arrays.toString(nums2)); 44 | System.out.println("Test Case 2 - Expected result: " + expected2); 45 | System.out.println("Test Case 2 - Actual result: " + result2); 46 | System.out.println("Test Case 2 - Result matches expected: " + (result2 == expected2)); 47 | 48 | int[] nums3 = {1}; 49 | int expected3 = 1; 50 | int result3 = singleNumber(nums3); 51 | System.out.println("Test Case 3 - Input: " + Arrays.toString(nums3)); 52 | System.out.println("Test Case 3 - Expected result: " + expected3); 53 | System.out.println("Test Case 3 - Actual result: " + result3); 54 | System.out.println("Test Case 3 - Result matches expected: " + (result3 == expected3)); 55 | 56 | } 57 | 58 | 59 | public static int singleNumber(int[] nums) { 60 | Arrays.sort(nums); // sort the array of integers 61 | int n = nums.length; 62 | for (int i = n - 1; i > 0; i -= 2) { // iterate through the array from the end to the beginning in steps of 2 63 | int current = nums[i]; 64 | int previous = nums[i - 1]; 65 | if (current != previous) { // if the current element and the previous element are not equal, return the 66 | // current element 67 | return current; 68 | } 69 | } 70 | return nums[0]; 71 | } 72 | } 73 | 74 | 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00202/HappyNumber.java: -------------------------------------------------------------------------------- 1 | /** 2 | 202. Happy Number 3 | Easy 4 | Write an algorithm to determine if a number n is happy. 5 | 6 | A happy number is a number defined by the following process: 7 | 8 | Starting with any positive integer, replace the number by the sum of the squares of its digits. 9 | Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. 10 | Those numbers for which this process ends in 1 are happy. 11 | Return true if n is a happy number, and false if not. 12 | 13 | 14 | 15 | Example 1: 16 | 17 | Input: n = 19 18 | Output: true 19 | Explanation: 20 | 12 + 92 = 82 21 | 82 + 22 = 68 22 | 62 + 82 = 100 23 | 12 + 02 + 02 = 1 24 | Example 2: 25 | 26 | Input: n = 2 27 | Output: false 28 | */ 29 | public class HappyNumber { 30 | public static void main(String[] args) { 31 | // Test case 1: Happy number 32 | int num1 = 19; 33 | boolean result1 = isHappy(num1); 34 | System.out.println("Test Case 1 - Input number: " + num1); 35 | System.out.println("Test Case 1 - Is happy number: " + result1); 36 | 37 | // Test case 2: Not a happy number 38 | int num2 = 2; 39 | boolean result2 = isHappy(num2); 40 | System.out.println("Test Case 2 - Input number: " + num2); 41 | System.out.println("Test Case 2 - Is happy number: " + result2); 42 | 43 | // Test case 3: Single digit number 44 | int num3 = 1; 45 | boolean result3 = isHappy(num3); 46 | System.out.println("Test Case 3 - Input number: " + num3); 47 | System.out.println("Test Case 3 - Is happy number: " + result3); 48 | } 49 | 50 | /** 51 | * Determines if a number is a happy number using the fast and slow pointer approach. 52 | * A happy number is a number where the sum of the squares of its digits eventually equals 1. 53 | * If a cycle is detected (i.e., a repeated number), then the number is not happy. 54 | * 55 | * Time Complexity: O(log n), where n is the number of digits in the number. 56 | * Space Complexity: O(1), as no extra space is used apart from the pointers. 57 | */ 58 | public static boolean isHappy(int n) { 59 | // Initialize slow and fast pointers 60 | int slow = n; 61 | int fast = getNext(n); 62 | 63 | // Loop until the fast pointer reaches 1 (happy) or slow meets fast (cycle detected) 64 | while (fast != 1 && slow != fast) { 65 | slow = getNext(slow); // Move slow pointer by one step 66 | fast = getNext(getNext(fast)); // Move fast pointer by two steps 67 | } 68 | 69 | // If fast reaches 1, it's a happy number; otherwise, there's a cycle (not happy) 70 | return fast == 1; 71 | } 72 | 73 | /** 74 | * Helper method to calculate the next number in the sequence (sum of squares of digits) 75 | */ 76 | private static int getNext(int n) { 77 | int sum = 0; 78 | while (n > 0) { 79 | int digit = n % 10; // Get the last digit 80 | sum += digit * digit; // Add the square of the digit to the sum 81 | n = n / 10; // Remove the last digit 82 | } 83 | return sum; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00219/ContainsDuplicateII.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | /** 4 | * 219. Contains Duplicate II 5 | * Easy 6 | * 7 | * Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array 8 | * such that nums[i] == nums[j] and |i - j| <= k. 9 | * 10 | * Example 1: 11 | * Input: nums = [1,2,3,1], k = 3 12 | * Output: true 13 | * 14 | * Example 2: 15 | * Input: nums = [1,0,1,1], k = 1 16 | * Output: true 17 | * 18 | * Example 3: 19 | * Input: nums = [1,2,3,1,2,3], k = 2 20 | * Output: false 21 | */ 22 | public class ContainsDuplicateII { 23 | public static void main(String[] args) { 24 | 25 | // Test case 1 - Contains duplicates within range k 26 | int[] nums1 = {1, 2, 3, 1}; 27 | int k1 = 3; 28 | boolean expected1 = true; 29 | boolean result1 = containsNearbyDuplicate(nums1, k1); 30 | System.out.println("Test Case 1 - Expected: " + expected1); 31 | System.out.println("Test Case 1 - Actual: " + result1); 32 | 33 | // Test case 2 - Contains duplicates within range k 34 | int[] nums2 = {1, 0, 1, 1}; 35 | int k2 = 1; 36 | boolean expected2 = true; 37 | boolean result2 = containsNearbyDuplicate(nums2, k2); 38 | System.out.println("Test Case 2 - Expected: " + expected2); 39 | System.out.println("Test Case 2 - Actual: " + result2); 40 | 41 | // Test case 3 - No duplicates within range k 42 | int[] nums3 = {1, 2, 3, 1, 2, 3}; 43 | int k3 = 2; 44 | boolean expected3 = false; 45 | boolean result3 = containsNearbyDuplicate(nums3, k3); 46 | System.out.println("Test Case 3 - Expected: " + expected3); 47 | System.out.println("Test Case 3 - Actual: " + result3); 48 | } 49 | 50 | /** 51 | * Checks if there are any duplicates within a given range k. 52 | * 53 | * @param nums The integer array to check for duplicates. 54 | * @param k The maximum allowed difference between indices of duplicates. 55 | * @return True if there are duplicates within range k, false otherwise. 56 | */ 57 | public static boolean containsNearbyDuplicate(int[] nums, int k) { 58 | // HashMap to store the index of each element 59 | HashMap map = new HashMap<>(); 60 | 61 | for (int i = 0; i < nums.length; i++) { 62 | // If element exists in map and the difference of indices is <= k 63 | if(map.containsKey(nums[i]) && Math.abs(map.get(nums[i]) - i) <= k){ 64 | return true; 65 | } 66 | // Update the index of the current element 67 | map.put(nums[i], i); 68 | } 69 | 70 | // No duplicates found within range k 71 | return false; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00231/PowerOfTwo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 231. Power of Two 3 | * Easy 4 | * 5 | * Given an integer n, return true if it is a power of two. Otherwise, return false. 6 | * An integer n is a power of two if there exists an integer x such that n == 2^x. 7 | * 8 | * Example 1: 9 | * Input: n = 1 10 | * Output: true 11 | * Explanation: 2^0 = 1 12 | * 13 | * Example 2: 14 | * Input: n = 16 15 | * Output: true 16 | * Explanation: 2^4 = 16 17 | * 18 | * Example 3: 19 | * Input: n = 3 20 | * Output: false 21 | * 22 | * Constraints: 23 | * -231 <= n <= 231 - 1 24 | */ 25 | 26 | public class PowerOfTwo { 27 | 28 | public static void main(String[] args) { 29 | // Test cases for checking Power of Two 30 | testPowerOfTwo(1, true); 31 | testPowerOfTwo(16, true); 32 | testPowerOfTwo(3, false); 33 | testPowerOfTwo(4, true); 34 | testPowerOfTwo(0, false); 35 | testPowerOfTwo(-16, false); 36 | } 37 | 38 | /** 39 | * Method to test the Power of Two function. 40 | * 41 | * @param n The number to be tested. 42 | * @param expected The expected boolean result. 43 | */ 44 | public static void testPowerOfTwo(int n, boolean expected) { 45 | boolean result = isPowerOfTwo(n); 46 | System.out.println("Input: " + n); 47 | System.out.println("Expected: " + expected); 48 | System.out.println("Result: " + result); 49 | System.out.println("Test passed: " + (result == expected)); 50 | System.out.println(); 51 | } 52 | 53 | 54 | public static boolean isPowerOfTwo(int n) { 55 | // Base case: if n is 1, it is a power of two (2^0 = 1) 56 | if (n == 1) { 57 | return true; 58 | } 59 | // Base case: if n is less than or equal to 0, or n is not divisible by 2, it's not a power of two 60 | if (n <= 0 || n % 2 != 0) { 61 | return false; 62 | } 63 | // Recursive case: check if n / 2 is a power of two 64 | return isPowerOfTwo(n / 2); 65 | } 66 | 67 | 68 | public static boolean isPowerOfTwo1(int n) { 69 | if (n <= 0) { 70 | return false; 71 | } 72 | 73 | // Loop until n becomes 1, continuously dividing by 2 74 | while (n > 1) { 75 | if (n % 2 != 0) { 76 | return false; // If n is not divisible by 2, it's not a power of two 77 | } 78 | n /= 2; // Divide n by 2 79 | } 80 | 81 | return true; // If we exit the loop with n = 1, it's a power of two 82 | } 83 | 84 | public static boolean isPowerOfTwo2(int n) { 85 | // A power of two will have only one bit set in its binary representation 86 | // Example: 16 -> 10000 (binary), n & (n - 1) would be 0 if it's a power of two 87 | if (n <= 0) { 88 | return false; 89 | } 90 | return (n & (n - 1)) == 0; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00278/firstBadVersion.java: -------------------------------------------------------------------------------- 1 | /* 2 | 278. First Bad Version 3 | Easy 4 | You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of 5 | your product fails the quality check. Since each version is developed based on the previous version, all the 6 | versions after a bad version are also bad. 7 | 8 | Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following 9 | ones to be bad. 10 | 11 | You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find 12 | the first bad version. You should minimize the number of calls to the API. 13 | 14 | Example 1: 15 | 16 | Input: n = 5, bad = 4 17 | Output: 4 18 | Explanation: 19 | call isBadVersion(3) -> false 20 | call isBadVersion(5) -> true 21 | call isBadVersion(4) -> true 22 | Then 4 is the first bad version. 23 | Example 2: 24 | 25 | Input: n = 1, bad = 1 26 | Output: 1 27 | 28 | 29 | Constraints: 30 | 31 | 1 <= bad <= n <= 231 - 1 32 | */ 33 | 34 | 35 | public class BadVersion { 36 | public static void main(String[] args) { 37 | // Test case 1 38 | } 39 | 40 | 41 | public int firstBadVersion(int n) { 42 | int firstBad = -1; 43 | int start = 0; 44 | int end = n; 45 | 46 | while (start <= end) { 47 | int mid = start + (end - start) / 2; 48 | boolean isBad = isBadVersion(mid); 49 | 50 | if (isBad) { 51 | firstBad = mid; 52 | end = mid - 1; 53 | } else { 54 | start = mid + 1; 55 | } 56 | } 57 | 58 | return firstBad; 59 | } 60 | 61 | 62 | public int firstBadVersion2(int n) { 63 | for (int i = 1; i <= n; i++) { 64 | if (isBadVersion(i)) { 65 | return i; 66 | } 67 | } 68 | return -1; // Indicates no bad version found 69 | } 70 | } -------------------------------------------------------------------------------- /src/LeetCode/easy/00303/NumArray.java: -------------------------------------------------------------------------------- 1 | /*** 2 | 303. Range Sum Query - Immutable 3 | 4 | Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 5 | 6 | Implement the NumArray class: 7 | 8 | NumArray(int[] nums) Initializes the object with the integer array nums. 9 | int sumRange(int i, int j) Returns the sum of the elements of nums between indices i and j (i ≤ j), inclusive. 10 | 11 | Example 1: 12 | Input: 13 | ["NumArray", "sumRange", "sumRange", "sumRange"] 14 | [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] 15 | Output: 16 | [null, 1, 1, -3] 17 | 18 | Explanation: 19 | NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); 20 | numArray.sumRange(0, 2); // return 1 (i.e sum of the elements nums[0] + nums[1] + nums[2] = -2 + 0 + 3 = 1) 21 | numArray.sumRange(2, 5); // return 1 (i.e sum of the elements nums[2] + nums[3] + nums[4] + nums[5] = 3 + -5 + 2 + -1 = 1) 22 | numArray.sumRange(0, 5); // return -3 (i.e sum of the elements nums[0] + nums[1] + nums[2] + nums[3] + nums[4] + nums[5] = -2 + 0 + 3 + -5 + 2 + -1 = -3) 23 | 24 | Constraints: 25 | 26 | 1 <= nums.length <= 10^4 27 | -10^9 <= nums[i] <= 10^9 28 | 0 <= i <= j < nums.length 29 | At most 10^4 calls will be made to sumRange. 30 | */ 31 | 32 | public class NumArray { 33 | private int[] prefixSum; 34 | 35 | public NumArray(int[] nums) { 36 | int n = nums.length; 37 | prefixSum = new int[n + 1]; 38 | 39 | // Precompute the prefix sum array 40 | for (int i = 1; i <= n; i++) { 41 | prefixSum[i] = prefixSum[i - 1] + nums[i - 1]; 42 | } 43 | } 44 | 45 | public int sumRange(int i, int j) { 46 | // Return the sum using the prefix sum array 47 | return prefixSum[j + 1] - prefixSum[i]; 48 | } 49 | 50 | public static void main(String[] args) { 51 | // Test case 1: 52 | // Array: [-2, 0, 3, -5, 2, -1] 53 | // sumRange(0, 2) = 1 54 | int[] nums1 = {-2, 0, 3, -5, 2, -1}; 55 | NumArray numArray1 = new NumArray(nums1); 56 | System.out.println("Test case 1: " + numArray1.sumRange(0, 2)); // Output: 1 57 | 58 | // Test case 2: 59 | // Array: [1, 2, 3, 4, 5] 60 | // sumRange(1, 3) = 9 61 | int[] nums2 = {1, 2, 3, 4, 5}; 62 | NumArray numArray2 = new NumArray(nums2); 63 | System.out.println("Test case 2: " + numArray2.sumRange(1, 3)); // Output: 9 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00344/ReverseString.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * 344. Reverse String 5 | * Easy 6 | * 7 | * Write a function that reverses a string using recursion. 8 | * 9 | * Example 1: 10 | * Input: s = ["h","e","l","l","o"] 11 | * Output: ["o","l","l","e","h"] 12 | * 13 | * Example 2: 14 | * Input: s = ["H","a","n","n","a","h"] 15 | * Output: ["h","a","n","n","a","H"] 16 | * 17 | * Constraints: 18 | * 1 <= s.length <= 105 19 | * s[i] is a printable ascii character. 20 | */ 21 | 22 | public class ReverseString { 23 | 24 | public static void main(String[] args) { 25 | // Test cases for checking Reverse String using recursion 26 | testReverseString(new char[]{'h','e','l','l','o'}, new char[]{'o','l','l','e','h'}); 27 | testReverseString(new char[]{'H','a','n','n','a','h'}, new char[]{'h','a','n','n','a','H'}); 28 | testReverseString(new char[]{'a', 'b', 'c', 'd', 'e'}, new char[]{'e', 'd', 'c', 'b', 'a'}); 29 | } 30 | 31 | /** 32 | * Method to test the Reverse String function. 33 | * 34 | * @param s The input character array. 35 | * @param expected The expected reversed character array. 36 | */ 37 | public static void testReverseString(char[] s, char[] expected) { 38 | reverseString(s, 0, s.length - 1); 39 | System.out.println("Input: " + String.valueOf(s)); 40 | System.out.println("Expected: " + String.valueOf(expected)); 41 | System.out.println("Result: " + String.valueOf(s)); 42 | System.out.println("Test passed: " + (Arrays.equals(s, expected))); 43 | System.out.println(); 44 | } 45 | 46 | /** 47 | * Method to reverse the string in place using recursion. 48 | * 49 | * @param s The character array to reverse. 50 | * @param left The left pointer. 51 | * @param right The right pointer. 52 | */ 53 | public static void reverseString(char[] s, int left, int right) { 54 | // Base case: if left is greater than or equal to right, stop recursion 55 | if (left >= right) { 56 | return; 57 | } 58 | 59 | // Swap characters at left and right pointers 60 | char temp = s[left]; 61 | s[left] = s[right]; 62 | s[right] = temp; 63 | 64 | // Recur with the next pair of positions 65 | reverseString(s, left + 1, right - 1); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00392/IsSubsequence.java: -------------------------------------------------------------------------------- 1 | /*** 2 | 392. Is Subsequence 3 | 4 | Easy 5 | Given two strings s and t, return true if s is a subsequence of t, or false otherwise. 6 | 7 | A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not). 8 | 9 | 10 | Example 1: 11 | 12 | Input: s = "abc", t = "ahbgdc" 13 | Output: true 14 | Example 2: 15 | 16 | Input: s = "axc", t = "ahbgdc" 17 | Output: false 18 | 19 | Constraints: 20 | 21 | 0 <= s.length <= 100 22 | 0 <= t.length <= 104 23 | s and t consist only of lowercase English letters. 24 | 25 | 26 | Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code? 27 | */ 28 | 29 | public class IsSubsequence { 30 | 31 | public static void main(String[] args) { 32 | String s1 = "abc"; 33 | String t1 = "ahbgdc"; 34 | String s2 = "axc"; 35 | String t2 = "ahbgdc"; 36 | 37 | // Test Case 1 38 | System.out.println("Test Case 1:"); 39 | System.out.println("Is Subsequence (Solution): " + isSubsequence(s1, t1)); // Output: true 40 | System.out.println(); 41 | 42 | // Test Case 2 43 | System.out.println("Test Case 2:"); 44 | System.out.println("Is Subsequence (Solution): " + isSubsequence(s2, t2)); // Output: false 45 | } 46 | 47 | /** 48 | * Solution: Two Pointers Approach 49 | * Algorithm: 50 | * 1. Use two pointers, one for the string `s` and one for the string `t`. 51 | * 2. Traverse through `t` and try to match each character in `s`. 52 | * 3. If all characters of `s` are matched in order, return true. 53 | * 4. If we reach the end of `t` without matching all characters of `s`, return false. 54 | * 55 | * Time Complexity: O(n + m), where n is the length of `s` and m is the length of `t`. 56 | * Space Complexity: O(1), as we only use a constant amount of extra space. 57 | */ 58 | public static boolean isSubsequence(String s, String t) { 59 | int sPointer = 0, tPointer = 0; 60 | 61 | while (sPointer < s.length() && tPointer < t.length()) { 62 | if (s.charAt(sPointer) == t.charAt(tPointer)) { 63 | sPointer++; // Move the pointer on s if we have a match 64 | } 65 | tPointer++; // Always move the pointer on t 66 | } 67 | 68 | // If we have gone through all characters in s, then s is a subsequence of t 69 | return sPointer == s.length(); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00414/ThirdMaximumNumber.java: -------------------------------------------------------------------------------- 1 | /** 2 | 414. Third Maximum Number 3 | Easy 4 | Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number. 5 | 6 | Example 1: 7 | 8 | Input: nums = [3,2,1] 9 | Output: 1 10 | Explanation: 11 | The first distinct maximum is 3. 12 | The second distinct maximum is 2. 13 | The third distinct maximum is 1. 14 | Example 2: 15 | 16 | Input: nums = [1,2] 17 | Output: 2 18 | Explanation: 19 | The first distinct maximum is 2. 20 | The second distinct maximum is 1. 21 | The third distinct maximum does not exist, so the maximum (2) is returned instead. 22 | Example 3: 23 | 24 | Input: nums = [2,2,3,1] 25 | Output: 1 26 | Explanation: 27 | The first distinct maximum is 3. 28 | The second distinct maximum is 2 (both 2's are counted together since they have the same value). 29 | The third distinct maximum is 1. 30 | 31 | 32 | Constraints: 33 | 34 | 1 <= nums.length <= 104 35 | -231 <= nums[i] <= 231 - 1 36 | 37 | */ 38 | 39 | 40 | import java.util.Arrays; 41 | 42 | public class ThirdMaximumNumber { 43 | public static void main(String[] args) { 44 | 45 | // Test case 1 - Third maximum number exists 46 | int[] nums1 = {3, 2, 1}; 47 | int expected1 = 1; 48 | int result1 = thirdMax(nums1); 49 | System.out.println("Test Case 1 - Expected: " + expected1); 50 | System.out.println("Test Case 1 - Actual: " + result1); 51 | 52 | // Test case 2 - Only two distinct numbers, return the max 53 | int[] nums2 = {1, 2}; 54 | int expected2 = 2; 55 | int result2 = thirdMax(nums2); 56 | System.out.println("Test Case 2 - Expected: " + expected2); 57 | System.out.println("Test Case 2 - Actual: " + result2); 58 | 59 | // Test case 3 - Third maximum number doesn't exist, return the max 60 | int[] nums3 = {2, 2, 3, 1}; 61 | int expected3 = 1; 62 | int result3 = thirdMax(nums3); 63 | System.out.println("Test Case 3 - Expected: " + expected3); 64 | System.out.println("Test Case 3 - Actual: " + result3); 65 | } 66 | 67 | /** 68 | * Returns the third maximum number in the array, or the maximum if third does not exist. 69 | * 70 | * @param nums The integer array to check. 71 | * @return The third maximum number or the maximum number. 72 | */ 73 | public static int thirdMax(int[] nums) { 74 | int n = nums.length; 75 | 76 | // Sort the array 77 | Arrays.sort(nums); 78 | 79 | // Count distinct numbers 80 | int count = 1; 81 | 82 | // Iterate from the second last element 83 | for (int i = n - 1; i > 0; i--) { 84 | if (nums[i] != nums[i - 1]) { 85 | count++; 86 | } 87 | 88 | // If we have found 3 distinct numbers, return the third largest 89 | if (count == 3) { 90 | return nums[i - 1]; 91 | } 92 | } 93 | 94 | // If there are less than 3 distinct numbers, return the largest 95 | return nums[n - 1]; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00441/arrangeCoins.java: -------------------------------------------------------------------------------- 1 | /* 2 | 441. Arranging Coins 3 | Easy 4 | You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith 5 | row has exactly i coins. The last row of the staircase may be incomplete. 6 | 7 | Given the integer n, return the number of complete rows of the staircase you will build. 8 | 9 | Example 1: 10 | 11 | Input: n = 5 12 | Output: 2 13 | Explanation: Because the 3rd row is incomplete, we return 2. 14 | Example 2: 15 | 16 | Input: n = 8 17 | Output: 3 18 | Explanation: Because the 4th row is incomplete, we return 3. 19 | 20 | Constraints: 21 | 22 | 1 <= n <= 231 - 1 23 | */ 24 | 25 | 26 | class ArrangeCoins { 27 | public static void main(String[] args) { 28 | // Test cases 29 | testArrangeCoins(5, 2); 30 | testArrangeCoins(8, 3); 31 | testArrangeCoins(0, 0); 32 | testArrangeCoins(15, 4); 33 | } 34 | 35 | public static void testArrangeCoins(int n, int expected) { 36 | int result = arrangeCoins(n); 37 | System.out.println("Input: " + n + ", Expected: " + expected + ", Result: " + result); 38 | System.out.println("Test passed: " + (result == expected)); 39 | System.out.println(); 40 | } 41 | 42 | 43 | /** 44 | * Algorithm: 45 | * 1. Initialize remainingCoins with the given value n and rows to 0. 46 | * 2. Iterate through rows using a for loop: 47 | * a. Check if remainingCoins is greater than or equal to the current row index i. 48 | * b. If true, subtract i from remainingCoins, and increment rows. 49 | * c. Continue the loop until remainingCoins is no longer greater than or equal to i. 50 | * 3. Return the total number of complete rows formed, which is the value of rows. 51 | * 52 | * Time Complexity: O(sqrt(n)) 53 | * - The loop iterates until remainingCoins is less than the current row index i. 54 | * - In the worst case, it takes approximately sqrt(n) iterations to reach this condition. 55 | * 56 | * Space Complexity: O(1) 57 | * - Constant space is used since only a few variables (remainingCoins and rows) are used. 58 | */ 59 | public static int arrangeCoins(int n) { 60 | int remainingCoins = n; 61 | int rows = 0; 62 | 63 | // Iterate through rows 64 | for (int i = 1; remainingCoins >= i; i++) { 65 | remainingCoins -= i; 66 | rows++; 67 | } 68 | 69 | return rows; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00455/AssignCookies.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * 455. Assign Cookies 5 | * Easy 6 | * 7 | * You are given two integer arrays `g` and `s` representing the greed factor of children and the size of cookies respectively. 8 | * 9 | * Your goal is to assign cookies to children such that each child gets exactly one cookie, and the cookie size is greater than or equal 10 | * to the child's greed factor. Return the maximum number of children that can be content with the cookies. 11 | * 12 | * Example 1: 13 | * Input: g = [1,2,3], s = [1,1] 14 | * Output: 1 15 | * Explanation: You have 2 cookies, and you can only content 1 child. 16 | * 17 | * Example 2: 18 | * Input: g = [1,2], s = [1,2,3] 19 | * Output: 2 20 | * Explanation: You have 3 cookies, and you can content both children. 21 | */ 22 | public class AssignCookies { 23 | public static void main(String[] args) { 24 | 25 | // Test case 1 - Only 1 child can be content 26 | int[] greed1 = {1, 2, 3}; 27 | int[] cookies1 = {1, 1}; 28 | int expected1 = 1; 29 | int result1 = findContentChildren(greed1, cookies1); 30 | System.out.println("Test Case 1 - Expected: " + expected1); 31 | System.out.println("Test Case 1 - Actual: " + result1); 32 | 33 | // Test case 2 - All children can be content 34 | int[] greed2 = {1, 2}; 35 | int[] cookies2 = {1, 2, 3}; 36 | int expected2 = 2; 37 | int result2 = findContentChildren(greed2, cookies2); 38 | System.out.println("Test Case 2 - Expected: " + expected2); 39 | System.out.println("Test Case 2 - Actual: " + result2); 40 | 41 | // Test case 3 - No child can be content 42 | int[] greed3 = {2, 3, 4}; 43 | int[] cookies3 = {1}; 44 | int expected3 = 0; 45 | int result3 = findContentChildren(greed3, cookies3); 46 | System.out.println("Test Case 3 - Expected: " + expected3); 47 | System.out.println("Test Case 3 - Actual: " + result3); 48 | } 49 | 50 | /** 51 | * Finds the maximum number of children that can be content with the available cookies. 52 | * 53 | * @param g The integer array representing the greed factors of the children. 54 | * @param s The integer array representing the sizes of the cookies. 55 | * @return The maximum number of children that can be content. 56 | */ 57 | public static int findContentChildren(int[] g, int[] s) { 58 | // Sort the greed factors and cookie sizes 59 | Arrays.sort(g); 60 | Arrays.sort(s); 61 | 62 | int i = 0, j = 0; 63 | int count = 0; 64 | 65 | 66 | while (i < g.length && j < s.length) { 67 | if (s[j] >= g[i]) { 68 | count++; 69 | i++; 70 | } 71 | j++; 72 | } 73 | 74 | return count; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00485/MaxConsecutiveOnes.java: -------------------------------------------------------------------------------- 1 | /** 2 | 485. Max Consecutive Ones 3 | Easy 4 | 5 | Given a binary array nums, return the maximum number of consecutive 1's in the array. 6 | 7 | Example 1: 8 | Input: nums = [1,1,0,1,1,1] 9 | Output: 3 10 | Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. 11 | 12 | Example 2: 13 | Input: nums = [1,0,1,1,0,1] 14 | Output: 2 15 | */ 16 | 17 | public class MaxConsecutiveOnes { 18 | 19 | public static void main(String[] args) { 20 | testMaxConsecutiveOnesFunction(); 21 | } 22 | 23 | public static void testMaxConsecutiveOnesFunction() { 24 | // Test case 1: General case with multiple consecutive ones 25 | int[] nums1 = {1, 1, 0, 1, 1, 1}; 26 | int expected1 = 3; 27 | int result1 = findMaxConsecutiveOnes(nums1); 28 | System.out.println("Test Case 1 - Input: [1, 1, 0, 1, 1, 1]"); 29 | System.out.println("Test Case 1 - Expected result: " + expected1); 30 | System.out.println("Test Case 1 - Actual result: " + result1); 31 | System.out.println("Test Case 1 - Result matches expected: " + (result1 == expected1)); 32 | 33 | // Test case 2: Single 1 and 0s 34 | int[] nums2 = {1, 0, 1, 1, 0, 1}; 35 | int expected2 = 2; 36 | int result2 = findMaxConsecutiveOnes(nums2); 37 | System.out.println("Test Case 2 - Input: [1, 0, 1, 1, 0, 1]"); 38 | System.out.println("Test Case 2 - Expected result: " + expected2); 39 | System.out.println("Test Case 2 - Actual result: " + result2); 40 | System.out.println("Test Case 2 - Result matches expected: " + (result2 == expected2)); 41 | 42 | // Test case 3: All 1s 43 | int[] nums3 = {1, 1, 1, 1}; 44 | int expected3 = 4; 45 | int result3 = findMaxConsecutiveOnes(nums3); 46 | System.out.println("Test Case 3 - Input: [1, 1, 1, 1]"); 47 | System.out.println("Test Case 3 - Expected result: " + expected3); 48 | System.out.println("Test Case 3 - Actual result: " + result3); 49 | System.out.println("Test Case 3 - Result matches expected: " + (result3 == expected3)); 50 | 51 | // Test case 4: No 1s 52 | int[] nums4 = {0, 0, 0, 0}; 53 | int expected4 = 0; 54 | int result4 = findMaxConsecutiveOnes(nums4); 55 | System.out.println("Test Case 4 - Input: [0, 0, 0, 0]"); 56 | System.out.println("Test Case 4 - Expected result: " + expected4); 57 | System.out.println("Test Case 4 - Actual result: " + result4); 58 | System.out.println("Test Case 4 - Result matches expected: " + (result4 == expected4)); 59 | } 60 | 61 | public static int findMaxConsecutiveOnes(int[] nums) { 62 | int maxCount = 0; 63 | int currentCount = 0; 64 | 65 | for (int num : nums) { 66 | if (num == 1) { 67 | currentCount++; 68 | maxCount = Math.max(maxCount, currentCount); 69 | } else { 70 | currentCount = 0; 71 | } 72 | } 73 | 74 | return maxCount; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00561/ArrayPartition.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * 561. Array Partition 5 | * 6 | * Given an integer array nums of 2n integers, your task is to group these integers into n pairs 7 | * (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. 8 | * Return the maximized sum. 9 | * 10 | * Example 1: 11 | * Input: nums = [1,4,3,2] 12 | * Output: 4 13 | * Explanation: All possible pairings (ignoring the order of elements) are: 14 | * 1. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4 15 | * 2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3 16 | * 3. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3 17 | * So the maximum possible sum is 4. 18 | * 19 | * Example 2: 20 | * Input: nums = [6,2,6,5,1,2] 21 | * Output: 9 22 | * Explanation: The optimal pairing is (1, 2), (2, 5), (6, 6). The sum of min values is 1 + 2 + 6 = 9. 23 | */ 24 | public class ArrayPartition { 25 | public static void main(String[] args) { 26 | 27 | // Test case 1 28 | int[] nums1 = {1, 4, 3, 2}; 29 | int expected1 = 4; 30 | int result1 = arrayPairSum(nums1); 31 | System.out.println("Test Case 1 - Expected: " + expected1); 32 | System.out.println("Test Case 1 - Actual: " + result1); 33 | 34 | // Test case 2 35 | int[] nums2 = {6, 2, 6, 5, 1, 2}; 36 | int expected2 = 9; 37 | int result2 = arrayPairSum(nums2); 38 | System.out.println("Test Case 2 - Expected: " + expected2); 39 | System.out.println("Test Case 2 - Actual: " + result2); 40 | } 41 | 42 | /** 43 | * Returns the maximum sum of the min value of pairs. 44 | * 45 | * @param nums The integer array. 46 | * @return The maximum sum of min(ai, bi) for all pairs. 47 | */ 48 | public static int arrayPairSum(int[] nums) { 49 | // Sort the array to pair up the smallest numbers 50 | Arrays.sort(nums); 51 | int sum = 0; 52 | 53 | // Sum every second element (which will be the smaller element of each pair) 54 | for (int i = 0; i < nums.length; i += 2) { 55 | sum += nums[i]; 56 | } 57 | 58 | return sum; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00628/628. Maximum Product of Three Numbers.java: -------------------------------------------------------------------------------- 1 | /* 2 | 628. Maximum Product of Three Numbers 3 | Easy 4 | Given an integer array nums, find three numbers whose product is maximum and return the maximum product. 5 | 6 | Example 1: 7 | 8 | Input: nums = [1,2,3] 9 | Output: 6 10 | Example 2: 11 | 12 | Input: nums = [1,2,3,4] 13 | Output: 24 14 | Example 3: 15 | 16 | Input: nums = [-1,-2,-3] 17 | Output: -6 18 | 19 | 20 | Constraints: 21 | 22 | 3 <= nums.length <= 104 23 | -1000 <= nums[i] <= 1000 24 | */ 25 | 26 | 27 | import java.util.Arrays; 28 | public class MaximumProduct { 29 | public static int maximumProduct(int[] nums) { 30 | Arrays.sort(nums); 31 | int n = nums.length; 32 | 33 | int sumWithNegativeNumber = nums[0] * nums[1] * nums[n - 1]; 34 | int positiveNumSum = nums[n - 1] * nums[n - 2] * nums[n - 3]; 35 | int overAllSum = Math.max(sumWithNegativeNumber, positiveNumSum); 36 | return overAllSum; 37 | } 38 | 39 | public static void main(String[] args) { 40 | int[] nums1 = {1, 2, 3}; 41 | int maxProduct1 = maximumProduct(nums1); 42 | System.out.println("The maximum product of Three Numbers in " + Arrays.toString(nums1) + " is " + maxProduct1); // 43 | // Expected result is 6 44 | 45 | int[] nums2 = {2, 3, 0, 4}; 46 | int maxProduct2 = maximumProduct(nums2); 47 | System.out.println("The maximum product of Three Numbers in " + Arrays.toString(nums2) + " is " + maxProduct2); // 48 | // Expected result is 24 49 | 50 | int[] nums3 = {-100, -98, -1, 2, 3, 4}; 51 | int maxProduct3 = maximumProduct(nums3); 52 | System.out.println("The maximum product of Three Numbers in " + Arrays.toString(nums3) + " is " + maxProduct3); // 53 | // Expected result is 39200 54 | 55 | 56 | int[] nums4 = {-1, -2, -3}; 57 | int maxProduct4 = maximumProduct(nums4); 58 | System.out.println("The maximum product of Three Numbers in " + Arrays.toString(nums4) + " is " + maxProduct4); // 59 | // Expected result is -6 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00643/Solution.java: -------------------------------------------------------------------------------- 1 | /*** 2 | 643. Maximum Average Subarray I 3 | 4 | Given an integer array nums and an integer k, find the maximum average of a subarray of size k. 5 | 6 | Implement the solution using a sliding window approach: 7 | 8 | 1. Initialize a variable to store the sum of the first k elements. 9 | 2. Slide the window by adding the next element and removing the first element from the window. 10 | 3. Track the maximum sum during each window slide, and divide by k to get the average. 11 | 12 | Example 1: 13 | Input: 14 | [1,12,-5,-6,50,3], k = 4 15 | Output: 16 | 12.75 17 | Explanation: 18 | When k = 4, the subarray with the maximum average is [12,-5,-6,50], which has an average of 12.75. 19 | 20 | Constraints: 21 | 1 <= nums.length <= 10^5 22 | -10^4 <= nums[i] <= 10^4 23 | 1 <= k <= nums.length 24 | */ 25 | 26 | public class Solution { 27 | public double findMaxAverage(int[] nums, int k) { 28 | int sum = 0; 29 | 30 | // Calculate the sum of the first 'k' elements 31 | for (int i = 0; i < k; i++) { 32 | sum += nums[i]; 33 | } 34 | 35 | int maxSum = sum; 36 | 37 | // Use the sliding window technique to find the maximum sum of any subarray of size 'k' 38 | for (int i = k; i < nums.length; i++) { 39 | sum += nums[i] - nums[i - k]; // Slide the window by adding the new element and removing the old one 40 | maxSum = Math.max(maxSum, sum); // Track the maximum sum 41 | } 42 | 43 | // Return the maximum average by dividing the sum by 'k' 44 | return (double) maxSum / k; 45 | } 46 | 47 | public static void main(String[] args) { 48 | // Test case 1: 49 | // Array: [1,12,-5,-6,50,3], k = 4 50 | // The maximum average is 12.75 51 | int[] nums1 = {1, 12, -5, -6, 50, 3}; 52 | Solution solution1 = new Solution(); 53 | System.out.println("Test case 1: " + solution1.findMaxAverage(nums1, 4)); // Output: 12.75 54 | 55 | // Test case 2: 56 | // Array: [5, -2, 3, 7], k = 2 57 | // The maximum average is 5 58 | int[] nums2 = {5, -2, 3, 7}; 59 | Solution solution2 = new Solution(); 60 | System.out.println("Test case 2: " + solution2.findMaxAverage(nums2, 2)); // Output: 5.0 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00709/ToLowerCase.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 709. To Lower Case 3 | * Easy 4 | * 5 | * Given a string s, return the string after replacing every uppercase letter with the same lowercase letter. 6 | * 7 | * Example 1: 8 | * Input: s = "Hello" 9 | * Output: "hello" 10 | * 11 | * Example 2: 12 | * Input: s = "here" 13 | * Output: "here" 14 | * 15 | * Example 3: 16 | * Input: s = "LOVELY" 17 | * Output: "lovely" 18 | * 19 | * Constraints: 20 | * 1 <= s.length <= 100 21 | * s consists of printable ASCII characters. 22 | */ 23 | 24 | public class ToLowerCase { 25 | 26 | public static void main(String[] args) { 27 | // Test cases for checking ToLowerCase method 28 | testToLowerCase("Hello", "hello"); 29 | testToLowerCase("here", "here"); 30 | testToLowerCase("LOVELY", "lovely"); 31 | testToLowerCase("JavaIsFun", "javaisfun"); 32 | testToLowerCase("123ABC", "123abc"); 33 | } 34 | 35 | /** 36 | * Method to test the ToLowerCase function. 37 | * 38 | * @param input The input string. 39 | * @param expected The expected lowercase string. 40 | */ 41 | public static void testToLowerCase(String input, String expected) { 42 | String result = toLowerCase(input); 43 | System.out.println("Input: " + input); 44 | System.out.println("Expected: " + expected); 45 | System.out.println("Result: " + result); 46 | System.out.println("Test passed: " + result.equals(expected)); 47 | System.out.println(); 48 | } 49 | 50 | /** 51 | * Method to convert the input string to lowercase. 52 | * 53 | * @param s The input string. 54 | * @return The lowercase version of the string. 55 | */ 56 | public static String toLowerCase(String s) { 57 | StringBuilder result = new StringBuilder(); 58 | 59 | // Iterate through each character in the string 60 | for (char c : s.toCharArray()) { 61 | // If the character is uppercase, convert it to lowercase 62 | if (c >= 'A' && c <= 'Z') { 63 | result.append((char)(c + 32)); // Convert to lowercase by adding 32 to ASCII value 64 | } else { 65 | result.append(c); // Append the character as is if it's not uppercase 66 | } 67 | } 68 | 69 | return result.toString(); // Return the result as a string 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00854/854. Maximum Population Year.java: -------------------------------------------------------------------------------- 1 | /* 2 | 854. Maximum Population Year 3 | Easy 4 | Companies 5 | You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. 6 | 7 | The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die. 8 | 9 | Return the earliest year with the maximum population. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: logs = [[1993,1999],[2000,2010]] 16 | Output: 1993 17 | Explanation: The maximum population is 1, and 1993 is the earliest year with this population. 18 | Example 2: 19 | 20 | Input: logs = [[1950,1961],[1960,1971],[1970,1981]] 21 | Output: 1960 22 | Explanation: 23 | The maximum population is 2, and it had happened in years 1960 and 1970. 24 | The earlier year between them is 1960. 25 | 26 | 27 | Constraints: 28 | 29 | 1 <= logs.length <= 100 30 | 1950 <= birthi < deathi <= 2050 31 | */ 32 | 33 | public class PopulationAnalyzer { 34 | public static void main(String[] args) { 35 | // Example 1 36 | int[][] logs1 = {{1950, 1961}, {1960, 1971}, {1970, 1981}}; 37 | int earliestYear1 = maximumPopulation(logs1); 38 | System.out.println("Earliest year with maximum population for Example 1: " + earliestYear1); 39 | 40 | // Output: Earliest year with maximum population for Example 1: 1960 41 | 42 | // Example 2 43 | int[][] logs2 = {{1950, 1960}, {1960, 1970}, {1970, 1980}, {1980, 1990}}; 44 | int earliestYear2 = maximumPopulation(logs2); 45 | System.out.println("Earliest year with maximum population for Example 2: " + earliestYear2); 46 | 47 | // Output: Earliest year with maximum population for Example 2: 1960 48 | 49 | // Example 3 50 | int[][] logs3 = {{1990, 2000}, {1995, 2005}, {2000, 2010}, {2005, 2015}}; 51 | int earliestYear3 = maximumPopulation(logs3); 52 | System.out.println("Earliest year with maximum population for Example 3: " + earliestYear3); 53 | 54 | // Output: Earliest year with maximum population for Example 3: 1995 55 | } 56 | 57 | public static int maximumPopulation(int[][] logs) { 58 | int[] population = new int[101]; 59 | int earliestYear = 1950; 60 | int maxPopulation = 0; 61 | 62 | // Step 2: Increment population count for each year between birth and death year 63 | for (int i = 0; i < logs.length; i++) { 64 | int birthYear = logs[i][0]; 65 | int deathYear = logs[i][1]; 66 | for (int j = birthYear - earliestYear; j < deathYear - earliestYear; j++) { 67 | population[j]++; 68 | } 69 | } 70 | 71 | // Find earliest year with maximum population count 72 | for (int i = 0; i < population.length; i++) { 73 | if (population[i] > maxPopulation) { 74 | maxPopulation = population[i]; 75 | earliestYear = i + 1950; 76 | } 77 | } 78 | 79 | return earliestYear; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00867/MatrixTranspose.java: -------------------------------------------------------------------------------- 1 | /** 2 | 867. Transpose Matrix 3 | Easy 4 | Given a 2D integer array matrix, return the transpose of matrix. 5 | 6 | The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. 7 | 8 | 9 | Example 1: 10 | 11 | Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] 12 | Output: [[1,4,7],[2,5,8],[3,6,9]] 13 | Example 2: 14 | 15 | Input: matrix = [[1,2,3],[4,5,6]] 16 | Output: [[1,4],[2,5],[3,6]] 17 | 18 | 19 | Constraints: 20 | 21 | m == matrix.length 22 | n == matrix[i].length 23 | 1 <= m, n <= 1000 24 | 1 <= m * n <= 105 25 | -109 <= matrix[i][j] <= 109 26 | */ 27 | 28 | import java.util.Arrays; 29 | 30 | public class MatrixTranspose { 31 | public static void main(String[] args) { 32 | int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; 33 | int[][] matrix2 = {{1, 2, 3}, {4, 5, 6}}; 34 | 35 | // Test cases 36 | int[][] result1 = transpose(matrix1); 37 | int[][] result2 = transpose(matrix2); 38 | 39 | // Print results 40 | printMatrix(matrix1,result1); // Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]] 41 | printMatrix(matrix2, result2); // Output: [[1, 4], [2, 5], [3, 6]] 42 | } 43 | 44 | 45 | /** 46 | * Algorithm Steps: 47 | * 1. Initialize variables for the number of rows (m) and columns (n) in the input matrix. 48 | * 2. Create a new matrix 'result' with dimensions n x m to store the transpose. 49 | * 3. Iterate over each element in the input matrix using nested loops. 50 | * a. Place the element at matrix[i][j] in the result matrix at result[j][i]. 51 | * 4. Return the transposed matrix 'result'. 52 | * 53 | * Time Complexity: O(m * n), where m is the number of rows and n is the number of columns. 54 | * - We visit each element once while iterating over the input matrix. 55 | * Space Complexity: O(m * n), as we create a new matrix to store the transposed result. 56 | * - The space required is proportional to the number of elements in the input matrix. 57 | */ 58 | public static int[][] transpose(int[][] matrix) { 59 | int numRows = matrix.length; 60 | int numCols = matrix[0].length; 61 | int[][] transposedMatrix = new int[numCols][numRows]; 62 | 63 | // Iterate through each element in the matrix and place it in the correct position in the transposed matrix 64 | for (int row = 0; row < numCols; row++) { 65 | for (int col = 0; col < numRows; col++) { 66 | transposedMatrix[row][col] = matrix[col][row]; 67 | } 68 | } 69 | 70 | return transposedMatrix; 71 | } 72 | 73 | /** 74 | * Helper method to print test results for the transposeMatrix function. 75 | */ 76 | public static void printMatrix(int[][] matrix, int[][] result) { 77 | System.out.println("Input Matrix: " + Arrays.deepToString(matrix)); 78 | System.out.println("Transposed Matrix: " + Arrays.deepToString(result)); 79 | System.out.println(); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00876/MiddleOfLinkedList.java: -------------------------------------------------------------------------------- 1 | /** 2 | 876. Middle of the Linked List 3 | Solved 4 | Given the head of a singly linked list, return the middle node of the linked list. 5 | 6 | If there are two middle nodes, return the second middle node. 7 | */ 8 | 9 | public class MiddleOfLinkedList { 10 | public static void main(String[] args) { 11 | // Test case 1: 12 | ListNode list1 = new ListNode(1); 13 | list1.next = new ListNode(2); 14 | list1.next.next = new ListNode(3); 15 | list1.next.next.next = new ListNode(4); 16 | list1.next.next.next.next = new ListNode(5); 17 | 18 | ListNode result1 = middleNode(list1); 19 | System.out.println("Test Case 1 - Input list: " + listToString(list1)); 20 | System.out.println("Test Case 1 - Middle node: " + result1.val); 21 | 22 | // Test case 2: even number of nodes 23 | ListNode list2 = new ListNode(1); 24 | list2.next = new ListNode(2); 25 | list2.next.next = new ListNode(3); 26 | list2.next.next.next = new ListNode(4); 27 | 28 | ListNode result2 = middleNode(list2); 29 | System.out.println("Test Case 2 - Input list: " + listToString(list2)); 30 | System.out.println("Test Case 2 - Middle node: " + result2.val); 31 | } 32 | 33 | /** 34 | * Middle of Linked List 35 | * Given the head of a singly linked list, return the middle node of the linked list. 36 | * If there are two middle nodes, return the second one. 37 | * Algorithm Steps: 38 | * 1. Use two pointers: slow and fast. 39 | * 2. The fast pointer moves two steps at a time, while the slow pointer moves one step at a time. 40 | * 3. When the fast pointer reaches the end of the list, the slow pointer will be at the middle. 41 | * 4. Return the slow pointer. 42 | * Time Complexity: O(n) where n is the length of the linked list. 43 | * Space Complexity: O(1) since we only use two pointers. 44 | */ 45 | 46 | public static ListNode middleNode(ListNode head) { 47 | // Initialize slow and fast pointers 48 | ListNode slow = head; 49 | ListNode fast = head; 50 | 51 | // Move slow by 1 step and fast by 2 steps until fast reaches the end 52 | while (fast != null && fast.next != null) { 53 | slow = slow.next; 54 | fast = fast.next.next; 55 | } 56 | 57 | // Return the middle node (slow pointer) 58 | return slow; 59 | } 60 | 61 | // Helper method to convert a linked list to a string for easy display 62 | public static String listToString(ListNode head) { 63 | if (head == null) return "NULL"; 64 | StringBuilder sb = new StringBuilder(); 65 | ListNode current = head; 66 | while (current != null) { 67 | sb.append(current.val).append(" -> "); 68 | current = current.next; 69 | } 70 | return sb.append("NULL").toString(); 71 | } 72 | } 73 | 74 | // Definition for singly-linked list. 75 | class ListNode { 76 | int val; 77 | ListNode next; 78 | ListNode() {} 79 | ListNode(int val) { this.val = val; } 80 | ListNode(int val, ListNode next) { this.val = val; this.next = next; } 81 | } 82 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00922/SortArrayByParityII.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * 922. Sort Array By Parity II 5 | * 6 | * Given an array of integers `nums` with half even and half odd numbers, 7 | * rearrange the array so that every even index has an even number and every 8 | * odd index has an odd number. 9 | * 10 | * Example 1: 11 | * Input: nums = [4,2,5,7] 12 | * Output: [4,5,2,7] 13 | * Explanation: [4, 5, 2, 7] is a valid answer. Other valid answers include [2, 7, 4, 5], [2, 5, 4, 7], etc. 14 | * 15 | * Example 2: 16 | * Input: nums = [2,3] 17 | * Output: [2,3] 18 | * 19 | * Constraints: 20 | * - 2 <= nums.length <= 2 * 10^4 21 | * - nums.length is even. 22 | * - Half of the integers in nums are even. 23 | * - 0 <= nums[i] <= 1000 24 | */ 25 | public class SortArrayByParityII { 26 | public static void main(String[] args) { 27 | 28 | // Test case 1 - Typical case with even and odd numbers 29 | int[] nums1 = {4, 2, 5, 7}; 30 | int[] expected1 = {4, 5, 2, 7}; // Other valid outputs possible 31 | int[] result1 = sortArrayByParityII(nums1); 32 | System.out.println("Test Case 1 - Expected: " + Arrays.toString(expected1)); 33 | System.out.println("Test Case 1 - Actual: " + Arrays.toString(result1)); 34 | 35 | // Test case 2 - Small input case 36 | int[] nums2 = {2, 3}; 37 | int[] expected2 = {2, 3}; 38 | int[] result2 = sortArrayByParityII(nums2); 39 | System.out.println("Test Case 2 - Expected: " + Arrays.toString(expected2)); 40 | System.out.println("Test Case 2 - Actual: " + Arrays.toString(result2)); 41 | } 42 | 43 | /** 44 | * Returns an array where even indices hold even numbers and odd indices hold odd numbers. 45 | * 46 | * @param nums The integer array to sort by parity. 47 | * @return The sorted array with even and odd numbers at the correct indices. 48 | */ 49 | public static int[] sortArrayByParityII(int[] nums) { 50 | int evenIndex = 0; 51 | int oddIndex = 1; 52 | int n = nums.length; 53 | 54 | // Iterate through the array, sorting even and odd numbers into the correct places 55 | while (evenIndex < n && oddIndex < n) { 56 | // If nums[evenIndex] is odd and nums[oddIndex] is even, swap them 57 | if (nums[evenIndex] % 2 != 0 && nums[oddIndex] % 2 == 0) { 58 | swap(nums, evenIndex, oddIndex); 59 | } 60 | 61 | // If nums[evenIndex] is correct (even), move to the next even index 62 | if (nums[evenIndex] % 2 == 0) { 63 | evenIndex += 2; 64 | } 65 | 66 | // If nums[oddIndex] is correct (odd), move to the next odd index 67 | if (nums[oddIndex] % 2 != 0) { 68 | oddIndex += 2; 69 | } 70 | } 71 | 72 | return nums; 73 | } 74 | 75 | // Swap helper function 76 | private static void swap(int[] nums, int left, int right) { 77 | int temp = nums[left]; 78 | nums[left] = nums[right]; 79 | nums[right] = temp; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/LeetCode/easy/00989/989. Add to Array-Form of Integer.java: -------------------------------------------------------------------------------- 1 | /* 2 | 989. Add to Array-Form of Integer 3 | Easy 4 | Companies 5 | The array-form of an integer num is an array representing its digits in left to right order. 6 | 7 | For example, for num = 1321, the array form is [1,3,2,1]. 8 | Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k. 9 | 10 | 11 | Example 1: 12 | 13 | Input: num = [1,2,0,0], k = 34 14 | Output: [1,2,3,4] 15 | Explanation: 1200 + 34 = 1234 16 | Example 2: 17 | 18 | Input: num = [2,7,4], k = 181 19 | Output: [4,5,5] 20 | Explanation: 274 + 181 = 455 21 | Example 3: 22 | 23 | Input: num = [2,1,5], k = 806 24 | Output: [1,0,2,1] 25 | Explanation: 215 + 806 = 1021 26 | 27 | 28 | Constraints: 29 | 30 | 1 <= num.length <= 104 31 | 0 <= num[i] <= 9 32 | num does not contain any leading zeros except for the zero itself. 33 | 1 <= k <= 104 34 | */ 35 | 36 | 37 | import java.util.ArrayList; 38 | import java.util.List; 39 | 40 | public class AddToArrayForm { 41 | public static List addToArrayForm(int[] num, int k) { 42 | List result = new ArrayList<>(); 43 | int carry = 0; 44 | int n = num.length; 45 | 46 | // Iterate through num from right to left, adding corresponding digit of k to each digit of num 47 | for (int i = n - 1; i >= 0 || k > 0 || carry > 0; i--) { 48 | int sum = carry; 49 | 50 | if (i >= 0) { 51 | sum += num[i]; 52 | } 53 | 54 | if (k > 0) { 55 | sum += k % 10; 56 | k /= 10; 57 | } 58 | 59 | // Calculate carry-over digit and add current sum to result list 60 | carry = sum / 10; 61 | result.add(0, sum % 10); 62 | } 63 | 64 | // Return result list as the array-form of the sum of num and k 65 | return result; 66 | } 67 | 68 | public static void main(String[] args) { 69 | // Test case 1 70 | int[] num1 = {1, 2, 0, 0}; 71 | int k1 = 34; 72 | List result1 = addToArrayForm(num1, k1); 73 | System.out.println("Result 1: " + result1); // Expected output: [1, 2, 3, 4] 74 | 75 | // Test case 2 76 | int[] num2 = {2, 7, 4}; 77 | int k2 = 181; 78 | List result2 = addToArrayForm(num2, k2); 79 | System.out.println("Result 2: " + result2); // Expected output: [4, 5, 5] 80 | 81 | // Test case 3 82 | int[] num3 = {9, 9, 9, 9}; 83 | int k3 = 1; 84 | List result3 = addToArrayForm(num3, k3); 85 | System.out.println("Result 3: " + result3); // Expected output: [1, 0, 0, 0, 0] 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/LeetCode/easy/01137/TribonacciNumber.java: -------------------------------------------------------------------------------- 1 | /*** 2 | * 1137. N-th Tribonacci Number 3 | * 4 | * Easy 5 | * 6 | * The Tribonacci sequence T(n) is defined as follows: 7 | * 8 | * T(0) = 0, T(1) = 1, T(2) = 1, and T(n+3) = T(n) + T(n+1) + T(n+2) for n >= 0. 9 | * 10 | * Given `n`, return the value of T(n). 11 | * 12 | * Example: 13 | * Input: n = 4 14 | * Output: 4 15 | * Explanation: 16 | * T(3) = T(2) + T(1) + T(0) = 1 + 1 + 0 = 2 17 | * T(4) = T(3) + T(2) + T(1) = 2 + 1 + 1 = 4 18 | * 19 | * Constraints: 20 | * - 0 <= n <= 37 21 | * - The answer is guaranteed to fit within a 32-bit integer, i.e., return value will be <= 2^31 - 1. 22 | */ 23 | 24 | public class TribonacciNumber { 25 | 26 | // ================================================== 27 | // Solution 1: Recursive Approach (inefficient) 28 | // ================================================== 29 | public int tribonacci(int n) { 30 | if (n == 0) return 0; 31 | if (n == 1 || n == 2) return 1; 32 | return tribonacci(n - 1) + tribonacci(n - 2) + tribonacci(n - 3); 33 | } 34 | 35 | // ================================================== 36 | // Solution 2: Iterative Approach (efficient) 37 | // ================================================== 38 | public int tribonacciIterative(int n) { 39 | if (n == 0) return 0; 40 | if (n == 1 || n == 2) return 1; 41 | 42 | int a = 0, b = 1, c = 1; 43 | for (int i = 3; i <= n; i++) { 44 | int temp = a + b + c; 45 | a = b; 46 | b = c; 47 | c = temp; 48 | } 49 | return c; 50 | } 51 | 52 | // ================================================== 53 | // Main method to test the solution 54 | // ================================================== 55 | public static void main(String[] args) { 56 | TribonacciNumber solution = new TribonacciNumber(); 57 | 58 | // Test case 1: 59 | int n = 4; 60 | System.out.println("Test case 1: " + solution.tribonacci(n)); // Output: 4 61 | System.out.println("Test case 1 (iterative): " + solution.tribonacciIterative(n)); // Output: 4 62 | 63 | // Test case 2: 64 | n = 25; 65 | System.out.println("Test case 2: " + solution.tribonacci(n)); // Output: 1389537 66 | System.out.println("Test case 2 (iterative): " + solution.tribonacciIterative(n)); // Output: 1389537 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/LeetCode/easy/01200/MinimumAbsoluteDifference.java: -------------------------------------------------------------------------------- 1 | /** 2 | 1200. Minimum Absolute Difference 3 | 4 | Easy 5 | Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. 6 | 7 | Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows 8 | 9 | a, b are from arr 10 | a < b 11 | b - a equals to the minimum absolute difference of any two elements in arr 12 | 13 | Example 1: 14 | 15 | Input: arr = [4,2,1,3] 16 | Output: [[1,2],[2,3],[3,4]] 17 | Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. 18 | Example 2: 19 | 20 | Input: arr = [1,3,6,10,15] 21 | Output: [[1,3]] 22 | Example 3: 23 | 24 | Input: arr = [3,8,-10,23,19,-4,-14,27] 25 | Output: [[-14,-10],[19,23],[23,27]] 26 | 27 | */ 28 | 29 | import java.util.*; 30 | 31 | public class MinimumAbsoluteDifference { 32 | public static void main(String[] args) { 33 | 34 | // Test case 1 35 | int[] arr1 = {4, 2, 1, 3}; 36 | List> expected1 = Arrays.asList(Arrays.asList(1, 2), Arrays.asList(2, 3), Arrays.asList(3, 4)); 37 | List> result1 = minimumAbsDifference(arr1); 38 | System.out.println("Test Case 1 - Expected: " + expected1); 39 | System.out.println("Test Case 1 - Actual: " + result1); 40 | 41 | // Test case 2 42 | int[] arr2 = {1, 3, 6, 10, 15}; 43 | List> expected2 = Arrays.asList(Arrays.asList(1, 3)); 44 | List> result2 =minimumAbsDifference(arr2); 45 | System.out.println("Test Case 2 - Expected: " + expected2); 46 | System.out.println("Test Case 2 - Actual: " + result2); 47 | } 48 | 49 | /** 50 | * Finds all pairs with the minimum absolute difference. 51 | * 52 | * @param arr The array of distinct integers. 53 | * @return A list of pairs with the minimum absolute difference. 54 | */ 55 | public static List> minimumAbsDifference(int[] arr) { 56 | Arrays.sort(arr); 57 | List> res = new ArrayList(); 58 | int min = Integer.MAX_VALUE; 59 | 60 | for(int i = 1; i < arr.length; i++){ 61 | min = Math.min(min, arr[i] - arr[i - 1]); 62 | } 63 | 64 | 65 | for(int i = 1; i < arr.length; i++){ 66 | if(arr[i] - arr[i - 1] == min){ 67 | List temp = new ArrayList(); 68 | temp.add(arr[i - 1]); 69 | temp.add(arr[i]); 70 | res.add(temp); 71 | } 72 | } 73 | return res; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/LeetCode/easy/01281/1281. Subtract the Product and Sum of Digits of an Integer.java: -------------------------------------------------------------------------------- 1 | /* 2 | 1281. Subtract the Product and Sum of Digits of an Integer 3 | Given an integer number n, return the difference between the product of its digits and the sum of its digits. 4 | 5 | Example 1: 6 | Input: n = 234 7 | Output: 15 8 | Explanation: 9 | Product of digits = 2 * 3 * 4 = 24 10 | Sum of digits = 2 + 3 + 4 = 9 11 | Result = 24 - 9 = 15 12 | 13 | Example 2: 14 | Input: n = 4421 15 | Output: 21 16 | Explanation: 17 | Product of digits = 4 * 4 * 2 * 1 = 32 18 | Sum of digits = 4 + 4 + 2 + 1 = 11 19 | Result = 32 - 11 = 21 20 | */ 21 | 22 | import java.util.Scanner; 23 | 24 | class Main { 25 | public static int subtractProductAndSum(int n) { 26 | int sum = 0; 27 | int product = 1; 28 | 29 | while (n > 0) { 30 | int digit = n % 10; 31 | sum += digit; 32 | product *= digit; 33 | n /= 10; 34 | } 35 | 36 | return product - sum; 37 | } 38 | 39 | public static void main(String[] args) { 40 | Scanner scanner = new Scanner(System.in); 41 | System.out.print("Enter an integer: "); 42 | int n = scanner.nextInt(); 43 | 44 | int result = subtractProductAndSum(n); 45 | System.out.println("Result: " + result); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/LeetCode/easy/01295/FindNumbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | 1295. Find Numbers with Even Number of Digits 3 | Easy 4 | 5 | Given an array nums of integers, return how many of them contain an even number of digits. 6 | 7 | Example 1: 8 | 9 | Input: nums = [12,345,2,6,7896] 10 | Output: 2 11 | Explanation: 12 | 12 contains 2 digits (even number of digits). 13 | 345 contains 3 digits (odd number of digits). 14 | 2 contains 1 digit (odd number of digits). 15 | 6 contains 1 digit (odd number of digits). 16 | 7896 contains 4 digits (even number of digits). 17 | Therefore only 12 and 7896 contain an even number of digits. 18 | Example 2: 19 | 20 | Input: nums = [555,901,482,1771] 21 | Output: 1 22 | Explanation: 23 | Only 1771 contains an even number of digits. 24 | 25 | Constraints: 26 | 27 | 1 <= nums.length <= 500 28 | 1 <= nums[i] <= 105 29 | */ 30 | 31 | import java.util.Arrays; 32 | 33 | public class FindNumbers { 34 | public static void main(String[] args) { 35 | int[] nums1 = {12, 345, 2, 6, 7896}; 36 | int[] nums2 = {555, 901, 482, 1771}; 37 | 38 | // Test cases 39 | int result1 = findNumbers(nums1); 40 | printResult(nums1, result1, 2); 41 | 42 | int result2 = findNumbers(nums2); 43 | printResult(nums2, result2, 1); 44 | } 45 | 46 | public static int findNumbers(int[] nums) { 47 | int count = 0; 48 | 49 | // Iterate through each number in the array 50 | for (int num : nums) { 51 | // Check if the number has an even number of digits 52 | if (hasEvenDigits(num)) { 53 | count++; 54 | } 55 | } 56 | 57 | // Return the count of numbers with an even number of digits 58 | return count; 59 | } 60 | 61 | private static boolean hasEvenDigits(int num) { 62 | // Convert the number to a string and check the length 63 | return Integer.toString(num).length() % 2 == 0; 64 | } 65 | 66 | private static void printResult(int[] nums, int result, int expected) { 67 | System.out.println("Input: " + Arrays.toString(nums)); 68 | System.out.println("Expected result: " + expected); 69 | System.out.println("Actual result: " + result); 70 | System.out.println("Result matches expected: " + (result == expected)); 71 | System.out.println(); 72 | } 73 | } -------------------------------------------------------------------------------- /src/LeetCode/easy/01304/UniqueIntegersSumZero.java: -------------------------------------------------------------------------------- 1 | /** 2 | 1304. Find N Unique Integers Sum up to Zero 3 | Easy 4 | Companies 5 | Given an integer n, return any array containing n unique integers such that they add up to 0. 6 | 7 | Example 1: 8 | 9 | Input: n = 5 10 | Output: [-7,-1,1,3,4] 11 | Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4]. 12 | Example 2: 13 | 14 | Input: n = 3 15 | Output: [-1,0,1] 16 | Example 3: 17 | 18 | Input: n = 1 19 | Output: [0] 20 | 21 | Constraints: 22 | 23 | 1 <= n <= 1000 24 | */ 25 | 26 | import java.util.Arrays; 27 | 28 | public class UniqueIntegersSumZero { 29 | 30 | public static void main(String[] args) { 31 | int n1 = 5; 32 | int[] result1 = sumZero(n1); 33 | printResult(n1, result1); // Output: [1, 2, 3, 4, 5] 34 | 35 | int n2 = 3; 36 | int[] result2 = sumZero(n2); 37 | printResult(n2, result2); // Output: [1, 2, 3] 38 | 39 | int n3 = 1; 40 | int[] result3 = sumZero(n3); 41 | printResult(n3, result3); // Output: [1] 42 | } 43 | 44 | 45 | /** 46 | * Algorithm Steps: 47 | * 1. Create an array of length n to store the unique integers. 48 | * 2. Fill the first half of the array with positive integers starting from 1. 49 | * 3. Fill the second half of the array with corresponding negative integers. 50 | * 4. Return the resulting array with n unique integers that sum up to zero. 51 | * 52 | * Time Complexity: 53 | * - The time complexity is O(n) as the algorithm iterates through the array once. 54 | * 55 | * Space Complexity: 56 | * - The space complexity is O(n) as the algorithm uses an array of length n. 57 | */ 58 | public static int[] sumZero(int n) { 59 | int[] result = new int[n]; 60 | 61 | // Fill the first half of the array with positive integers 62 | for (int i = 0; i < n / 2; i++) { 63 | result[i] = i + 1; 64 | } 65 | 66 | // Fill the second half of the array with negative integers 67 | for (int i = n / 2, j = -n / 2; i < n; i++, j++) { 68 | result[i] = j; 69 | } 70 | 71 | return result; 72 | } 73 | 74 | // Helper method to print test results 75 | private static void printResult(int n, int[] result) { 76 | System.out.println("Input n: " + n); 77 | System.out.println("Output: " + Arrays.toString(result)); 78 | System.out.println(); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/LeetCode/easy/01331/RankTransform.java: -------------------------------------------------------------------------------- 1 | /*** 2 | 1331. Rank Transform of an Array 3 | 4 | Easy 5 | Given an array of integers arr, replace each element with its rank. 6 | 7 | The rank represents how large the element is. The rank has the following rules: 8 | 9 | Rank is an integer starting from 1. 10 | The larger the element, the larger the rank. If two elements are equal, their rank must be the same. 11 | Rank should be as small as possible. 12 | 13 | 14 | Example 1: 15 | 16 | Input: arr = [40,10,20,30] 17 | Output: [4,1,2,3] 18 | Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest. 19 | Example 2: 20 | 21 | Input: arr = [100,100,100] 22 | Output: [1,1,1] 23 | Explanation: Same elements share the same rank. 24 | Example 3: 25 | 26 | Input: arr = [37,12,28,9,100,56,80,5,12] 27 | Output: [5,3,4,2,8,6,7,1,3] 28 | 29 | 30 | Constraints: 31 | 32 | 0 <= arr.length <= 105 33 | -109 <= arr[i] <= 109 34 | */ 35 | 36 | import java.util.*; 37 | 38 | public class RankTransform { 39 | public static void main(String[] args) { 40 | // Test case 1 41 | int[] arr1 = {40, 10, 20, 30}; 42 | System.out.println("Test Case 1 - Output: " + Arrays.toString(arrayRankTransform(arr1))); 43 | 44 | // Test case 2 45 | int[] arr2 = {100, 100, 100}; 46 | System.out.println("Test Case 2 - Output: " + Arrays.toString(arrayRankTransform(arr2))); 47 | 48 | // Test case 3 49 | int[] arr3 = {37, 12, 28, 9, 100, 56, 80, 5, 12}; 50 | System.out.println("Test Case 3 - Output: " + Arrays.toString(arrayRankTransform(arr3))); 51 | } 52 | 53 | /** 54 | * Replaces each element in the array with its rank. 55 | * 56 | * @param arr The input array. 57 | * @return The array with ranks replacing the original elements. 58 | */ 59 | public static int[] arrayRankTransform(int[] arr) { 60 | int n = arr.length; 61 | 62 | // Step 1: Create a sorted version of the array 63 | int[] sortedArr = arr.clone(); 64 | Arrays.sort(sortedArr); 65 | 66 | // Step 2: Create a map to store the rank of each unique element 67 | Map rankMap = new HashMap<>(); 68 | int rank = 1; 69 | 70 | for (int num : sortedArr) { 71 | // Only assign rank to unique elements 72 | if (!rankMap.containsKey(num)) { 73 | rankMap.put(num, rank++); 74 | } 75 | } 76 | 77 | // Step 3: Replace elements in the original array with their rank 78 | for (int i = 0; i < n; i++) { 79 | arr[i] = rankMap.get(arr[i]); 80 | } 81 | 82 | return arr; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/LeetCode/easy/01460/MakeTwoArraysEqual.java: -------------------------------------------------------------------------------- 1 | /* 2 | 1460. Make Two Arrays Equal by Reversing Subarrays 3 | Easy 4 | You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any non-empty subarray of arr and reverse it. You are allowed to make any number of steps. 5 | 6 | Return true if you can make arr equal to target, or false otherwise. 7 | 8 | Example 1: 9 | 10 | Input: target = [1,2,3,4], arr = [2,4,1,3] 11 | Output: true 12 | Explanation: You can reverse subarrays in arr to match target. 13 | 14 | Example 2: 15 | 16 | Input: target = [7], arr = [7] 17 | Output: true 18 | Explanation: arr is already equal to target, no need to reverse any subarrays. 19 | 20 | Example 3: 21 | 22 | Input: target = [3,7,9], arr = [3,7,11] 23 | Output: false 24 | Explanation: arr does not have the same elements as target, so we cannot make them equal. 25 | 26 | Constraints: 27 | 28 | - target.length == arr.length 29 | - 1 <= target.length <= 1000 30 | - 1 <= target[i] <= 1000 31 | - 1 <= arr[i] <= 1000 32 | */ 33 | 34 | import java.util.*; 35 | 36 | public class MakeTwoArraysEqual { 37 | public static void main(String[] args) { 38 | // Test cases 39 | testMakeTwoArraysEqual(new int[]{1, 2, 3, 4}, new int[]{2, 4, 1, 3}, true); 40 | testMakeTwoArraysEqual(new int[]{7}, new int[]{7}, true); 41 | testMakeTwoArraysEqual(new int[]{3, 7, 9}, new int[]{3, 7, 11}, false); 42 | testMakeTwoArraysEqual(new int[]{1, 1, 1, 2}, new int[]{2, 1, 1, 1}, true); 43 | } 44 | 45 | public static void testMakeTwoArraysEqual(int[] target, int[] arr, boolean expected) { 46 | boolean result = canBeEqual(target, arr); 47 | System.out.println("Target: " + Arrays.toString(target) + ", Arr: " + Arrays.toString(arr) + ", Expected: " + expected + ", Result: " + result); 48 | System.out.println("Test passed: " + (result == expected)); 49 | System.out.println(); 50 | } 51 | 52 | /** 53 | * Algorithm: 54 | * 1. Sort both `target` and `arr`. 55 | * 2. Check if the sorted arrays are equal. If they are, return true; otherwise, return false. 56 | * 57 | * The logic behind this is that reversing a subarray will not change the multiset of elements in the array. 58 | * Therefore, if two arrays have the same elements in the same frequency, they can be made equal. 59 | * 60 | * Time Complexity: O(n log n) due to sorting. 61 | * Space Complexity: O(n) - Space used to store the sorted arrays. 62 | */ 63 | public static boolean canBeEqual(int[] target, int[] arr) { 64 | // Sort both arrays 65 | Arrays.sort(target); 66 | Arrays.sort(arr); 67 | 68 | 69 | // for(int i = 0; i < arr.length; i++){ 70 | // if(arr[i] != target[i]){ 71 | // return false; 72 | // } 73 | // } 74 | 75 | // return true; 76 | 77 | 78 | // Check if sorted arrays are equal 79 | return Arrays.equals(target, arr); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/LeetCode/easy/01464/MaximumProductOfTwoElements.java: -------------------------------------------------------------------------------- 1 | /*** 2 | 1464. Maximum Product of Two Elements in an Array 3 | Easy 4 | Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). 5 | 6 | Example 1: 7 | 8 | Input: nums = [3,4,5,2] 9 | Output: 12 10 | Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. 11 | Example 2: 12 | 13 | Input: nums = [1,5,4,5] 14 | Output: 16 15 | Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16. 16 | Example 3: 17 | 18 | Input: nums = [3,7] 19 | Output: 12 20 | 21 | Constraints: 22 | 23 | 2 <= nums.length <= 500 24 | 1 <= nums[i] <= 10^3 25 | */ 26 | 27 | import java.util.*; 28 | 29 | public class MaximumProductOfTwoElements { 30 | public static void main(String[] args) { 31 | 32 | // Test case 1 33 | int[] nums1 = {3, 4, 5, 2}; 34 | int expected1 = 12; // (4 - 1) * (5 - 1) = 12 35 | int result1 = maxProduct(nums1); 36 | System.out.println("Test Case 1 - Expected: " + expected1); 37 | System.out.println("Test Case 1 - Actual: " + result1); 38 | 39 | // Test case 2 40 | int[] nums2 = {1, 5, 4, 5}; 41 | int expected2 = 16; // (5 - 1) * (5 - 1) = 16 42 | int result2 = maxProduct(nums2); 43 | System.out.println("Test Case 2 - Expected: " + expected2); 44 | System.out.println("Test Case 2 - Actual: " + result2); 45 | 46 | // Test case 3 47 | int[] nums3 = {10, 2, 5, 2}; 48 | int expected3 = 36; // (10 - 1) * (5 - 1) = 36 49 | int result3 = maxProduct(nums3); 50 | System.out.println("Test Case 3 - Expected: " + expected3); 51 | System.out.println("Test Case 3 - Actual: " + result3); 52 | } 53 | 54 | 55 | 56 | public static int maxProduct(int[] nums) { 57 | int largest =Integer.MIN_VALUE; 58 | int secondLargest =Integer.MIN_VALUE; 59 | 60 | for(int i = 0; i < nums.length; i++){ 61 | int n = nums[i]; 62 | if(n >= largest){ 63 | secondLargest =largest; 64 | largest = n; 65 | } 66 | 67 | if(n > secondLargest && n != largest) 68 | secondLargest = n; 69 | } 70 | 71 | 72 | 73 | // System.out.println(num1 + " " + num2); 74 | return (secondLargest - 1)* (largest - 1); 75 | } 76 | 77 | /** 78 | * Finds the maximum product of (nums[i] - 1) * (nums[j] - 1) where 0 <= i, j < nums.length. 79 | * 80 | * @param nums The array of integers. 81 | * @return The maximum product of two elements minus 1. 82 | */ 83 | public static int maxProduct2(int[] nums) { 84 | // Sort the array 85 | Arrays.sort(nums); 86 | 87 | // Take the last two elements and apply the formula (nums[i] - 1) * (nums[j] - 1) 88 | int n = nums.length; 89 | return (nums[n - 1] - 1) * (nums[n - 2] - 1); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/LeetCode/easy/01480/480_Running_Sum_of_1d_Array: -------------------------------------------------------------------------------- 1 | /* 2 | 1480. Running Sum of 1d Array 3 | Easy 4 | Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). 5 | 6 | Return the running sum of nums. 7 | 8 | Example 1: 9 | 10 | Input: nums = [1,2,3,4] 11 | Output: [1,3,6,10] 12 | Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. 13 | Example 2: 14 | 15 | Input: nums = [1,1,1,1,1] 16 | Output: [1,2,3,4,5] 17 | Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]. 18 | Example 3: 19 | 20 | Input: nums = [3,1,2,10,1] 21 | Output: [3,4,6,16,17] 22 | 23 | 24 | Constraints: 25 | 26 | 1 <= nums.length <= 1000 27 | -10^6 <= nums[i] <= 10^6 28 | */ 29 | 30 | public class RunningSum { 31 | 32 | public static int[] runningSum(int[] nums) { 33 | int n = nums.length; 34 | int[] result = new int[n]; 35 | int sum = 0; 36 | 37 | // Calculate the running sum at each index and store it in the result array 38 | for (int i = 0; i < n; i++) { 39 | sum += nums[i]; 40 | result[i] = sum; 41 | } 42 | 43 | return result; 44 | } 45 | 46 | 47 | public static int[] optimizeRunningSum(int[] nums) { 48 | int sum = 0; 49 | for (int i = 0; i < nums.length; i++) { 50 | sum += nums[i]; 51 | nums[i] = sum; 52 | } 53 | return nums; 54 | } 55 | 56 | public static void main(String[] args) { 57 | // Define the input array 58 | int[] nums = {1, 2, 3, 4, 5}; 59 | 60 | // Compute the running sum of the input array 61 | int[] result = runningSum(nums); 62 | 63 | // Print the result array 64 | System.out.println("Running Sum of the Array: " + Arrays.toString(result)); 65 | // Expected output: [1, 3, 6, 10, 15] 66 | 67 | int[] optimizeResult = optimizeRunningSum(nums); 68 | System.out.println("Optimize Running Sum of the Array: " + Arrays.toString(result)); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/LeetCode/easy/01502/CanMakeArithmeticProgression.java: -------------------------------------------------------------------------------- 1 | /** 2 | 1502. Can Make Arithmetic Progression From Sequence 3 | 4 | Easy 5 | 6 | A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. 7 | 8 | Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false. 9 | 10 | Example 1: 11 | 12 | Input: arr = [3,5,1] 13 | Output: true 14 | Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements. 15 | Example 2: 16 | 17 | Input: arr = [1,2,4] 18 | Output: false 19 | Explanation: There is no way to reorder the elements to obtain an arithmetic progression. 20 | 21 | 22 | Constraints: 23 | 24 | 2 <= arr.length <= 1000 25 | -106 <= arr[i] <= 106 26 | */ 27 | 28 | import java.util.Arrays; 29 | 30 | public class CanMakeArithmeticProgression { 31 | public static void main(String[] args) { 32 | // Test cases 33 | testCanMakeArithmeticProgression(new int[]{3, 5, 1}, true); 34 | testCanMakeArithmeticProgression(new int[]{1, 2, 4}, false); 35 | testCanMakeArithmeticProgression(new int[]{7, 7, 7}, true); 36 | testCanMakeArithmeticProgression(new int[]{-1, -5, -3}, true); 37 | } 38 | 39 | public static void testCanMakeArithmeticProgression(int[] arr, boolean expected) { 40 | boolean result = canMakeArithmeticProgression(arr); 41 | System.out.println("Input: " + Arrays.toString(arr) + ", Expected: " + expected + ", Result: " + result); 42 | System.out.println("Test passed: " + (result == expected)); 43 | System.out.println(); 44 | } 45 | 46 | /** 47 | * Check if an array can be rearranged to form an arithmetic progression. 48 | * 49 | * An arithmetic progression is a sequence of numbers such that the difference between consecutive elements is the same. 50 | * 51 | * @param arr The array of numbers. 52 | * @return True if the array can be rearranged to form an arithmetic progression, otherwise false. 53 | */ 54 | public static boolean canMakeArithmeticProgression(int[] arr) { 55 | Arrays.sort(arr); // Sort the array to check differences between consecutive elements 56 | 57 | int difference = arr[1] - arr[0]; // Calculate the difference of the first two elements 58 | 59 | // Check if the difference remains constant throughout the array 60 | for (int i = 2; i < arr.length; i++) { 61 | if (arr[i] - arr[i - 1] != difference) { 62 | return false; 63 | } 64 | } 65 | 66 | return true; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/LeetCode/easy/01512/GoodPairs.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | 1512. Number of Good Pairs 4 | Easy 5 | Given an array of integers nums, return the number of good pairs. 6 | 7 | A pair (i, j) is called good if nums[i] == nums[j] and i < j. 8 | 9 | Example 1: 10 | 11 | Input: nums = [1,2,3,1,1,3] 12 | Output: 4 13 | Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. 14 | Example 2: 15 | 16 | Input: nums = [1,1,1,1] 17 | Output: 6 18 | Explanation: Each pair in the array are good. 19 | Example 3: 20 | 21 | Input: nums = [1,2,3] 22 | Output: 0 23 | 24 | Constraints: 25 | 26 | 1 <= nums.length <= 100 27 | 1 <= nums[i] <= 100 28 | 29 | */ 30 | 31 | import java.util.Arrays; 32 | 33 | public class GoodPairs { 34 | public static void main(String[] args) { 35 | // Example usage 36 | int[] nums1 = {1, 2, 3, 1, 1, 3}; 37 | int result1 = numIdenticalPairs(nums1); 38 | int expected1 = 4; 39 | printResult(nums1, result1, expected1); 40 | 41 | int[] nums2 = {1, 1, 1, 1}; 42 | int result2 = numIdenticalPairs(nums2); 43 | int expected2 = 6; 44 | printResult(nums2, result2, expected2); 45 | 46 | int[] nums3 = {1, 2, 3}; 47 | int result3 = numIdenticalPairs(nums3); 48 | int expected3 = 0; 49 | printResult(nums3, result3, expected3); 50 | } 51 | 52 | /** 53 | * Algorithm Steps: 54 | * 1. Initialize a variable `numPairs` to 0. 55 | * 2. Iterate through each element in the array using a loop with index `i` from 0 to `n - 2`. 56 | * a. Initialize a counter variable `count` to 0. 57 | * b. Iterate through the remaining elements using a loop with index `j` from `i + 1` to `n - 1`. 58 | * c. If the element at index `i` is equal to the element at index `j`, increment the `count`. 59 | * d. After the inner loop, add the value of `count` to `numPairs`. 60 | * 3. After completing the outer loop, return the final value of `numPairs`. 61 | * 62 | * Time Complexity: O(n^2) - Two nested loops iterate over the array. 63 | * Space Complexity: O(1) - Constant space is used (no extra data structures). 64 | */ 65 | public static int numIdenticalPairs(int[] nums) { 66 | int numPairs = 0; 67 | int n = nums.length; 68 | 69 | for (int i = 0; i < n - 1; i++) { 70 | 71 | for (int j = i + 1; j < n; j++) { 72 | if (nums[i] == nums[j] && i < j) { 73 | numPairs++; 74 | } 75 | } 76 | } 77 | 78 | return numPairs; 79 | } 80 | 81 | /** 82 | * Print the result of a test case. 83 | */ 84 | public static void printResult(int[] nums, int result, int expected) { 85 | System.out.println("Input: " + Arrays.toString(nums)); 86 | System.out.println("Expected result: " + expected); 87 | System.out.println("Actual result: " + result); 88 | System.out.println("Result matches expected: " + (result == expected)); 89 | System.out.println(); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/LeetCode/easy/01672/1672. Richest Customer Wealth.java: -------------------------------------------------------------------------------- 1 | /* 2 | 1672. Richest Customer Wealth 3 | Easy 4 | 5 | You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has. 6 | 7 | A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth. 8 | 9 | Example 1: 10 | 11 | Input: accounts = [[1,2,3],[3,2,1]] 12 | Output: 6 13 | Explanation: 14 | 1st customer has wealth = 1 + 2 + 3 = 6 15 | 2nd customer has wealth = 3 + 2 + 1 = 6 16 | Both customers are considered the richest with a wealth of 6 each, so return 6. 17 | Example 2: 18 | 19 | Input: accounts = [[1,5],[7,3],[3,5]] 20 | Output: 10 21 | Explanation: 22 | 1st customer has wealth = 6 23 | 2nd customer has wealth = 10 24 | 3rd customer has wealth = 8 25 | The 2nd customer is the richest with a wealth of 10. 26 | Example 3: 27 | 28 | Input: accounts = [[2,8,7],[7,1,3],[1,9,5]] 29 | Output: 17 30 | 31 | Constraints: 32 | 33 | m == accounts.length 34 | n == accounts[i].length 35 | 1 <= m, n <= 50 36 | 1 <= accounts[i][j] <= 100 37 | */ 38 | 39 | public class RichestCustomerWealth { 40 | public static int maximumWealth(int[][] accounts) { 41 | int maxWealth = 0; 42 | 43 | for (int[] customerAccounts : accounts) { 44 | int wealth = 0; 45 | for (int accountBalance : customerAccounts) { 46 | wealth += accountBalance; 47 | } 48 | maxWealth = Math.max(maxWealth, wealth); 49 | } 50 | 51 | return maxWealth; 52 | } 53 | 54 | public static void main(String[] args) { 55 | // Define the input matrix 56 | int[][] accounts = {{1,2,3}, {3,2,1}}; 57 | 58 | // Compute the maximum wealth of the customers 59 | int maxWealth = maximumWealth(accounts); 60 | 61 | // Print the result 62 | System.out.println("Maximum Wealth of Customers: " + maxWealth); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/LeetCode/easy/01732/1732. Find the Highest Altitude.java: -------------------------------------------------------------------------------- 1 | /* 2 | 1732. Find the Highest Altitude 3 | Easy 4 | Companies 5 | There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0. 6 | 7 | You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i​​​​​​ and i + 1 for all (0 <= i < n). Return the highest altitude of a point. 8 | 9 | 10 | Example 1: 11 | 12 | Input: gain = [-5,1,5,0,-7] 13 | Output: 1 14 | Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. 15 | Example 2: 16 | 17 | Input: gain = [-4,-3,-2,-1,4,3,2] 18 | Output: 0 19 | Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0. 20 | 21 | Constraints: 22 | 23 | n == gain.length 24 | 1 <= n <= 100 25 | -100 <= gain[i] <= 100 26 | 27 | */ 28 | 29 | public class HighestAltitudeFinder { 30 | public static void main(String[] args) { 31 | int[] gain1 = {-5,1,5,0,-7}; 32 | int[] gain2 = {-4,-3,-2,-1,4,3,2}; 33 | System.out.println("Highest altitude for gain1: " + findHighestAltitude(gain1)); // Output: 1 34 | System.out.println("Highest altitude for gain2: " + findHighestAltitude(gain2)); // Output: 0 35 | } 36 | 37 | public static int findHighestAltitude(int[] gain) { 38 | int n = gain.length; 39 | int maxAltitude = 0; 40 | int currentAltitude = 0; 41 | for (int i = 0; i < n; i++) { 42 | currentAltitude += gain[i]; 43 | if (currentAltitude > maxAltitude) { 44 | maxAltitude = currentAltitude; 45 | } 46 | } 47 | return maxAltitude; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/LeetCode/easy/01773/CountMatchingItems.java: -------------------------------------------------------------------------------- 1 | /* 2 | 1773. Count Items Matching a Rule 3 | Easy 4 | You are given an array items, where each items[i] = [typei, colori, namei] describes the type, color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and ruleValue. 5 | 6 | The ith item is said to match the rule if one of the following is true: 7 | 8 | ruleKey == "type" and ruleValue == typei. 9 | ruleKey == "color" and ruleValue == colori. 10 | ruleKey == "name" and ruleValue == namei. 11 | Return the number of items that match the given rule. 12 | 13 | Example 1: 14 | 15 | Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver" 16 | Output: 1 17 | Explanation: There is only one item matching the given rule, which is ["computer","silver","lenovo"]. 18 | Example 2: 19 | 20 | Input: items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone" 21 | Output: 2 22 | Explanation: There are only two items matching the given rule, which are ["phone","blue","pixel"] and ["phone","gold","iphone"]. Note that the item ["computer","silver","phone"] does not match. 23 | 24 | Constraints: 25 | 26 | 1 <= items.length <= 104 27 | 1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10 28 | ruleKey is equal to either "type", "color", or "name". 29 | All strings consist only of lowercase letters. 30 | */ 31 | 32 | import java.util.List; 33 | 34 | public class CountMatchingItems { 35 | /** 36 | * Returns the number of items in the given list that match the given rule. 37 | */ 38 | public static int countMatches(List> items, String ruleKey, String ruleValue) { 39 | int count = 0; 40 | 41 | for (List item : items) { 42 | String type = item.get(0); 43 | String color = item.get(1); 44 | String name = item.get(2); 45 | 46 | if ((ruleKey.equals("color") && ruleValue.equals(color)) 47 | || (ruleKey.equals("type") && ruleValue.equals(type)) 48 | || (ruleKey.equals("name") && ruleValue.equals(name))) { 49 | count++; 50 | } 51 | } 52 | 53 | return count; 54 | } 55 | 56 | public static void main(String[] args) { 57 | List> items = List.of( 58 | List.of("phone", "blue", "pixel"), 59 | List.of("computer", "silver", "lenovo"), 60 | List.of("phone", "gold", "iphone"), 61 | List.of("laptop", "silver", "macbook"), 62 | List.of("watch", "black", "fitbit") 63 | ); 64 | String ruleKey = "silver"; 65 | String ruleValue = "silver"; 66 | 67 | int count = countMatches(items, ruleKey, ruleValue); 68 | 69 | // Print the number of items that match the given rule 70 | System.out.println("Number of items matching the rule: " + count); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/LeetCode/easy/01800/MaximumAscendingSubarraySum.java: -------------------------------------------------------------------------------- 1 | /*** 2 | * 1800. Maximum Ascending Subarray Sum 3 | * 4 | * Easy 5 | * 6 | * Given an array of positive integers `nums`, return the maximum possible sum of an ascending subarray in `nums`. 7 | * A subarray is defined as a contiguous sequence of elements in the array. 8 | * A subarray [nums_l, nums_l+1, ..., nums_r-1, nums_r] is ascending if for all i where l <= i < r, nums[i] < nums[i + 1]. 9 | * 10 | * Example: 11 | * Input: nums = [10,20,30,5,10,50] 12 | * Output: 65 13 | * Explanation: The ascending subarray [10,20,30] has the maximum sum 60, while [5,10,50] has the maximum sum 65. 14 | * 15 | * Constraints: 16 | * - 1 <= nums.length <= 100 17 | * - 1 <= nums[i] <= 1000 18 | */ 19 | 20 | public class MaximumAscendingSubarraySum { 21 | 22 | // ================================================== 23 | // Solution 1: Iterative Approach 24 | // ================================================== 25 | public int maxAscendingSum(int[] nums) { 26 | int maxSum = nums[0]; 27 | int currentSum = nums[0]; 28 | 29 | for (int i = 1; i < nums.length; i++) { 30 | if (nums[i] > nums[i - 1]) { 31 | currentSum += nums[i]; // continue summing ascending subarray 32 | } else { 33 | currentSum = nums[i]; // reset sum when the ascending condition breaks 34 | } 35 | maxSum = Math.max(maxSum, currentSum); // keep track of maximum sum 36 | } 37 | 38 | return maxSum; 39 | } 40 | 41 | // ================================================== 42 | // Main method to test the solution 43 | // ================================================== 44 | public static void main(String[] args) { 45 | MaximumAscendingSubarraySum solution = new MaximumAscendingSubarraySum(); 46 | 47 | // Test case 1: 48 | int[] nums1 = {10, 20, 30, 5, 10, 50}; 49 | System.out.println("Test case 1: " + solution.maxAscendingSum(nums1)); // Output: 65 50 | 51 | // Test case 2: 52 | int[] nums2 = {12, 17, 15, 13, 10, 11, 12}; 53 | System.out.println("Test case 2: " + solution.maxAscendingSum(nums2)); // Output: 33 54 | 55 | // Test case 3: 56 | int[] nums3 = {100, 10, 1}; 57 | System.out.println("Test case 3: " + solution.maxAscendingSum(nums3)); // Output: 100 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/LeetCode/easy/01832/1832. Check if the Sentence Is Pangram.java: -------------------------------------------------------------------------------- 1 | /* 2 | 1832. Check if the Sentence Is Pangram 3 | Easy 4 | Companies 5 | A pangram is a sentence where every letter of the English alphabet appears at least once. 6 | 7 | Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise. 8 | 9 | Example 1: 10 | 11 | Input: sentence = "thequickbrownfoxjumpsoverthelazydog" 12 | Output: true 13 | Explanation: sentence contains at least one of every letter of the English alphabet. 14 | Example 2: 15 | 16 | Input: sentence = "leetcode" 17 | Output: false 18 | 19 | 20 | Constraints: 21 | 22 | 1 <= sentence.length <= 1000 23 | sentence consists of lowercase English letters. 24 | */ 25 | 26 | public class PangramChecker { 27 | 28 | public static boolean checkIfPangram(String sentence) { 29 | boolean[] letters = new boolean[26]; // initialize boolean array to track presence of each letter 30 | 31 | for (char c : sentence.toCharArray()) { 32 | if (c >= 'a' && c <= 'z') { // check if character is a lowercase letter 33 | letters[c - 'a'] = true; // mark letter as seen 34 | } 35 | } 36 | 37 | for (boolean present : letters) { 38 | if (!present) { // check if any letter is missing 39 | return false; // sentence is not a pangram 40 | } 41 | } 42 | 43 | return true; // sentence is a pangram 44 | } 45 | 46 | public static void main(String[] args) { 47 | String sentence1 = "the quick brown fox jumps over the lazy dog"; 48 | String sentence2 = "the quick brown fox jumps over the lazy cat"; 49 | 50 | System.out.println("Sentence 1 is a pangram: " + checkIfPangram(sentence1)); // true 51 | System.out.println("Sentence 2 is a pangram: " + checkIfPangram(sentence2)); // false 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/LeetCode/easy/01929/1929. Concatenation of Array.java: -------------------------------------------------------------------------------- 1 | /* 2 | 1929. Concatenation of Array 3 | Easy 4 | 5 | Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed). 6 | 7 | Specifically, ans is the concatenation of two nums arrays. 8 | 9 | Return the array ans. 10 | 11 | 12 | Example 1: 13 | 14 | Input: nums = [1,2,1] 15 | Output: [1,2,1,1,2,1] 16 | Explanation: The array ans is formed as follows: 17 | - ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]] 18 | - ans = [1,2,1,1,2,1] 19 | Example 2: 20 | 21 | Input: nums = [1,3,2,1] 22 | Output: [1,3,2,1,1,3,2,1] 23 | Explanation: The array ans is formed as follows: 24 | - ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]] 25 | - ans = [1,3,2,1,1,3,2,1] 26 | 27 | 28 | Constraints: 29 | 30 | n == nums.length 31 | 1 <= n <= 1000 32 | 1 <= nums[i] <= 1000 33 | 34 | */ 35 | 36 | 37 | public class ConcatenateArray { 38 | public static void main(String[] args) { 39 | int[] nums = {1, 2, 3}; 40 | int[] concatenatedArray = getConcatenation(nums); 41 | 42 | // Print the concatenated array 43 | for (int num : concatenatedArray) { 44 | System.out.print(num + " "); 45 | } 46 | // Output: 1 2 3 1 2 3 47 | } 48 | 49 | public static int[] getConcatenation(int[] nums) { 50 | int originalLength = nums.length; 51 | int[] concatenatedArray = new int[2 * originalLength]; 52 | 53 | // Iterate through the first half of the concatenated array 54 | for (int i = 0; i < originalLength; i++) { 55 | int currentNum = nums[i]; 56 | // Set the corresponding values in the second half of the concatenated array 57 | concatenatedArray[i] = currentNum; 58 | concatenatedArray[i + originalLength] = currentNum; 59 | } 60 | 61 | return concatenatedArray; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/LeetCode/easy/02057/SmallestIndexWithEqualValue.java: -------------------------------------------------------------------------------- 1 | /** 2 | 2057. Smallest Index With Equal Value 3 | Easy 4 | Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does not exist. 5 | 6 | x mod y denotes the remainder when x is divided by y. 7 | 8 | Example 1: 9 | 10 | Input: nums = [0,1,2] 11 | Output: 0 12 | Explanation: 13 | i=0: 0 mod 10 = 0 == nums[0]. 14 | i=1: 1 mod 10 = 1 == nums[1]. 15 | i=2: 2 mod 10 = 2 == nums[2]. 16 | All indices have i mod 10 == nums[i], so we return the smallest index 0. 17 | Example 2: 18 | 19 | Input: nums = [4,3,2,1] 20 | Output: 2 21 | Explanation: 22 | i=0: 0 mod 10 = 0 != nums[0]. 23 | i=1: 1 mod 10 = 1 != nums[1]. 24 | i=2: 2 mod 10 = 2 == nums[2]. 25 | i=3: 3 mod 10 = 3 != nums[3]. 26 | 2 is the only index which has i mod 10 == nums[i]. 27 | Example 3: 28 | 29 | Input: nums = [1,2,3,4,5,6,7,8,9,0] 30 | Output: -1 31 | Explanation: No index satisfies i mod 10 == nums[i]. 32 | 33 | 34 | Constraints: 35 | 36 | 1 <= nums.length <= 100 37 | 0 <= nums[i] <= 9 38 | */ 39 | 40 | import java.util.Arrays; 41 | 42 | public class SmallestIndexWithEqualValue { 43 | 44 | public static void main(String[] args) { 45 | // Test Case 1 46 | int[] nums1 = {0, 1, 2}; 47 | int expected1 = 0; 48 | int result1 = smallestEqual(nums1); 49 | printResult(nums1, expected1, result1); 50 | 51 | // Test Case 2 52 | int[] nums2 = {4, 3, 2, 1}; 53 | int expected2 = 2; 54 | int result2 = smallestEqual(nums2); 55 | printResult(nums2, expected2, result2); 56 | 57 | // Test Case 3 58 | int[] nums3 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; 59 | int expected3 = -1; 60 | int result3 = smallestEqual(nums3); 61 | printResult(nums3, expected3, result3); 62 | } 63 | 64 | /** 65 | * Find the smallest index i of nums such that i mod 10 == nums[i]. 66 | * If no such index exists, return -1. 67 | */ 68 | public static int smallestEqual(int[] nums) { 69 | for (int i = 0; i < nums.length; i++) { 70 | if (i % 10 == nums[i]) { 71 | return i; 72 | } 73 | } 74 | return -1; 75 | } 76 | 77 | /** 78 | * Print the result of a test case. 79 | */ 80 | public static void printResult(int[] nums, int expected, int result) { 81 | System.out.println("Input: " + Arrays.toString(nums)); 82 | System.out.println("Expected result: " + expected); 83 | System.out.println("Actual result: " + result); 84 | System.out.println("Result matches expected: " + (result == expected)); 85 | System.out.println(); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/LeetCode/easy/02089/FindTargetIndices.java: -------------------------------------------------------------------------------- 1 | /*** 2 | 2089. Find Target Indices After Sorting Array 3 | 4 | Easy 5 | 6 | You are given a 0-indexed integer array nums and a target element target. 7 | 8 | A target index is an index i such that nums[i] == target. 9 | 10 | Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: nums = [1,2,5,2,3], target = 2 17 | Output: [1,2] 18 | Explanation: After sorting, nums is [1,2,2,3,5]. 19 | The indices where nums[i] == 2 are 1 and 2. 20 | Example 2: 21 | 22 | Input: nums = [1,2,5,2,3], target = 3 23 | Output: [3] 24 | Explanation: After sorting, nums is [1,2,2,3,5]. 25 | The index where nums[i] == 3 is 3. 26 | Example 3: 27 | 28 | Input: nums = [1,2,5,2,3], target = 5 29 | Output: [4] 30 | Explanation: After sorting, nums is [1,2,2,3,5]. 31 | The index where nums[i] == 5 is 4. 32 | 33 | 34 | Constraints: 35 | 36 | 1 <= nums.length <= 100 37 | 1 <= nums[i], target <= 100 38 | */ 39 | 40 | import java.util.*; 41 | 42 | public class FindTargetIndices { 43 | public static void main(String[] args) { 44 | 45 | // Test case 1 46 | int[] nums1 = {1, 2, 5, 2, 3}; 47 | int target1 = 2; 48 | List expected1 = Arrays.asList(1, 2); 49 | List result1 = targetIndices(nums1, target1); 50 | System.out.println("Test Case 1 - Expected: " + expected1); 51 | System.out.println("Test Case 1 - Actual: " + result1); 52 | 53 | // Test case 2 54 | int[] nums2 = {1, 2, 3, 4}; 55 | int target2 = 5; 56 | List expected2 = new ArrayList<>(); 57 | List result2 = targetIndices(nums2, target2); 58 | System.out.println("Test Case 2 - Expected: " + expected2); 59 | System.out.println("Test Case 2 - Actual: " + result2); 60 | } 61 | 62 | /** 63 | * Finds the indices of the target element in a sorted array. 64 | * 65 | * @param nums The array of integers. 66 | * @param target The target integer to find. 67 | * @return The indices of the target in the sorted array. 68 | */ 69 | public static List targetIndices(int[] nums, int target) { 70 | List result = new ArrayList<>(); 71 | 72 | // Sort the array 73 | Arrays.sort(nums); 74 | 75 | // Find indices where target exists, and break early if the current element is greater than the target 76 | for (int i = 0; i < nums.length; i++) { 77 | if (nums[i] == target) { 78 | result.add(i); // Add the index of target 79 | } else if (nums[i] > target) { 80 | break; // No need to check further elements as the array is sorted 81 | } 82 | } 83 | 84 | return result; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/LeetCode/easy/02133/2133. Check if Every Row and Column Contains All Numbers.java: -------------------------------------------------------------------------------- 1 | /* 2 | 2133. Check if Every Row and Column Contains All Numbers 3 | Easy 4 | 5 | Companies 6 | An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). 7 | 8 | Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false. 9 | 10 | Example 1: 11 | 12 | Input: matrix = [[1,2,3],[3,1,2],[2,3,1]] 13 | Output: true 14 | Explanation: In this case, n = 3, and every row and column contains the numbers 1, 2, and 3. 15 | Hence, we return true. 16 | Example 2: 17 | 18 | 19 | Input: matrix = [[1,1,1],[1,2,3],[1,2,3]] 20 | Output: false 21 | Explanation: In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3. 22 | Hence, we return false. 23 | 24 | 25 | Constraints: 26 | 27 | n == matrix.length == matrix[i].length 28 | 1 <= n <= 100 29 | 1 <= matrix[i][j] <= n 30 | */ 31 | 32 | public class MatrixChecker { 33 | public static void main(String[] args) { 34 | int[][] matrix = { 35 | {1, 2, 3}, 36 | {2, 3, 1}, 37 | {3, 1, 2} 38 | }; 39 | 40 | boolean isValid = checkValid(matrix); 41 | 42 | if (isValid) { 43 | System.out.println("The matrix is valid."); 44 | } else { 45 | System.out.println("The matrix is not valid."); 46 | } 47 | } 48 | 49 | public static boolean checkValid(int[][] matrix) { 50 | int n = matrix.length; 51 | for (int i = 0; i < n; i++) { 52 | // check rows 53 | int[] row = matrix[i]; 54 | if (!containsAllNumbers(row, n)) { 55 | return false; 56 | } 57 | 58 | // check columns 59 | int[] col = new int[n]; 60 | for (int j = 0; j < n; j++) { 61 | col[j] = matrix[j][i]; 62 | } 63 | if (!containsAllNumbers(col, n)) { 64 | return false; 65 | } 66 | } 67 | return true; 68 | } 69 | 70 | private static boolean containsAllNumbers(int[] arr, int n) { 71 | boolean[] found = new boolean[n]; 72 | for (int i = 0; i < arr.length; i++) { 73 | int num = arr[i]; 74 | if (num < 1 || num > n || found[num-1]) { 75 | return false; 76 | } 77 | found[num-1] = true; 78 | } 79 | return true; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/LeetCode/easy/02239/FindclosestNumber.java: -------------------------------------------------------------------------------- 1 | /** 2 | 2239. Find Closest Number to Zero 3 | Easy 4 | 5 | Example 1: 6 | 7 | Input: nums = [-4,-2,1,4,8] 8 | Output: 1 9 | Explanation: 10 | The distance from -4 to 0 is |-4| = 4. 11 | The distance from -2 to 0 is |-2| = 2. 12 | The distance from 1 to 0 is |1| = 1. 13 | The distance from 4 to 0 is |4| = 4. 14 | The distance from 8 to 0 is |8| = 8. 15 | Thus, the closest number to 0 in the array is 1. 16 | Example 2: 17 | 18 | Input: nums = [2,-1,1] 19 | Output: 1 20 | Explanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned. 21 | 22 | 23 | Constraints: 24 | 25 | 1 <= n <= 1000 26 | -105 <= nums[i] <= 105 27 | */ 28 | 29 | 30 | public class FindclosestNumber { 31 | 32 | 33 | public static boolean isContain(int [] nums, int toFind){ 34 | boolean found = false; 35 | for (int n : nums) { 36 | if (n == toFind) { 37 | found = true; 38 | break; 39 | } 40 | } 41 | 42 | return found; 43 | 44 | } 45 | 46 | public static int findClosestNumber(int[] nums) { 47 | 48 | int closest = nums[0]; 49 | for (int num : nums) { 50 | if (Math.abs(num) < Math.abs(closest)) { 51 | closest = num; 52 | } 53 | } 54 | 55 | if (closest < 0 && isContain(nums, Math.abs(closest))) { 56 | return Math.abs(closest); 57 | } else { 58 | return closest; 59 | } 60 | } 61 | 62 | public static void main(String[] args) { 63 | int[] nums = { -4, -2, 1, 4, 8 }; 64 | System.out.println(findClosestNumber(nums)); 65 | 66 | } 67 | } -------------------------------------------------------------------------------- /src/LeetCode/easy/02455/AverageOfEvenNumbersDivisibleByThree.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * 2455. Average Value of Even Numbers That Are Divisible by Three 5 | * 6 | * Easy 7 | * 8 | * Given an integer array nums of positive integers, return the average value of all even numbers that are divisible by three. 9 | * 10 | * Example 1: 11 | * Input: nums = [1,3,6,10,12,15] 12 | * Output: 9 13 | * Explanation: 6 and 12 are even numbers divisible by three. Their average is (6 + 12) / 2 = 9. 14 | * 15 | * Example 2: 16 | * Input: nums = [1,2,4,7,10] 17 | * Output: 0 18 | * Explanation: There is no even number divisible by three, so the average is 0. 19 | * 20 | * Constraints: 21 | * - 1 <= nums.length <= 1000 22 | * - 1 <= nums[i] <= 1000 23 | */ 24 | 25 | public class AverageOfEvenNumbersDivisibleByThree { 26 | 27 | public static void main(String[] args) { 28 | // Test Case 1 29 | int[] nums1 = {1, 3, 6, 10, 12, 15}; 30 | int result1 = averageValue(nums1); 31 | System.out.println("Test Case 1 - Output: " + result1); // Expected output: 9 32 | 33 | // Test Case 2 34 | int[] nums2 = {1, 2, 4, 7, 10}; 35 | int result2 = averageValue(nums2); 36 | System.out.println("Test Case 2 - Output: " + result2); // Expected output: 0 37 | 38 | // Test Case 3 39 | int[] nums3 = {6, 18, 24, 5, 9, 2}; 40 | int result3 = averageValue(nums3); 41 | System.out.println("Test Case 3 - Output: " + result3); // Expected output: 16 42 | } 43 | 44 | /** 45 | * Finds the average value of even numbers that are divisible by three in the array. 46 | * 47 | * Algorithm: 48 | * 1. Loop through the array to check for even numbers divisible by three. 49 | * 2. Calculate the sum of those numbers. 50 | * 3. Track the count of such numbers. 51 | * 4. Return the average, or return 0 if no numbers meet the criteria. 52 | * 53 | * Time Complexity: O(n), where n is the length of the array. 54 | * Space Complexity: O(1), constant space. 55 | * 56 | * @param nums - The input array of integers. 57 | * @return The average value of even numbers divisible by three, or 0 if none found. 58 | */ 59 | public static int averageValue(int[] nums) { 60 | int sum = 0; 61 | int count = 0; 62 | 63 | for (int num : nums) { 64 | if (num % 2 == 0 && num % 3 == 0) { 65 | sum += num; 66 | count++; 67 | } 68 | } 69 | 70 | return count == 0 ? 0 : sum / count; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/LeetCode/easy/03206/AlternatingGroupsI.java: -------------------------------------------------------------------------------- 1 | /*** 2 | 3206. Alternating Groups I 3 | Solved 4 | Easy 5 | Topics 6 | Companies 7 | Hint 8 | There is a circle of red and blue tiles. You are given an array of integers colors. The color of tile i is represented by colors[i]: 9 | 10 | colors[i] == 0 means that tile i is red. 11 | colors[i] == 1 means that tile i is blue. 12 | Every 3 contiguous tiles in the circle with alternating colors (the middle tile has a different color from its left and right tiles) is called an alternating group. 13 | 14 | Return the number of alternating groups. 15 | 16 | Note that since colors represents a circle, the first and the last tiles are considered to be next to each other. 17 | 18 | 19 | 20 | Example 1: 21 | 22 | Input: colors = [1,1,1] 23 | 24 | Output: 0 25 | 26 | Explanation: 27 | */ 28 | 29 | import java.util.Arrays; 30 | 31 | public class AlternatingGroupsI { 32 | 33 | public static void main(String[] args) { 34 | // Test Case 1 35 | int[] colors1 = {0, 1, 0, 1}; 36 | int expected1 = 2; 37 | runTestCase(colors1, expected1); 38 | 39 | // Test Case 2 40 | int[] colors2 = {0, 1, 0, 0}; 41 | int expected2 = 1; 42 | runTestCase(colors2, expected2); 43 | 44 | // Additional Test Case 45 | int[] colors3 = {1, 0, 1, 0, 1}; 46 | int expected3 = 3; 47 | runTestCase(colors3, expected3); 48 | } 49 | 50 | private static void runTestCase(int[] colors, int expected) { 51 | int result = countAlternatingGroups(colors); 52 | System.out.println("Input: colors = " + Arrays.toString(colors)); 53 | System.out.println("Expected result: " + expected); 54 | System.out.println("Result: " + result); 55 | System.out.println("All results match expected: " + (result == expected)); 56 | System.out.println(); 57 | } 58 | 59 | /** 60 | * Approach: Sliding Window of size 3 61 | * 62 | * Algorithm Steps: 63 | * 1. Use a sliding window of size 3 to check every group of 3 contiguous elements in the array. 64 | * 2. Verify if the middle element is different from its left and right neighbors. 65 | * 3. Handle the circular nature of the array using modulo arithmetic. 66 | * 4. Count the number of valid alternating groups. 67 | * 68 | * Time Complexity: O(n), where n is the length of the `colors` array. 69 | * Space Complexity: O(1), for constant space usage. 70 | */ 71 | public static int countAlternatingGroups(int[] colors) { 72 | int n = colors.length; 73 | int alternatingGroups = 0; 74 | 75 | for (int i = 0; i < n; i++) { 76 | // Get the 3 contiguous elements using modulo for circular indexing 77 | int left = colors[i % n]; 78 | int middle = colors[(i + 1) % n]; 79 | int right = colors[(i + 2) % n]; 80 | 81 | // Check if the middle element is different from both left and right 82 | if (middle != left && middle != right) { 83 | alternatingGroups++; 84 | } 85 | } 86 | 87 | return alternatingGroups; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/LeetCode/medium/00039/CombinationSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * 39. Combination Sum 5 | * 6 | * Medium 7 | * 8 | * Given an array of distinct integers candidates and a target integer target, return a list of all unique 9 | * combinations of candidates where the chosen numbers sum to target. 10 | * 11 | * Example 1: 12 | * Input: candidates = [2,3,6,7], target = 7 13 | * Output: [[2,2,3],[7]] 14 | * 15 | * Example 2: 16 | * Input: candidates = [2,3,5], target = 8 17 | * Output: [[2,2,2,2],[2,3,3],[3,5]] 18 | * 19 | * Constraints: 20 | * - 1 <= candidates.length <= 30 21 | * - 2 <= candidates[i] <= 40 22 | * - All elements of candidates are distinct. 23 | * - 1 <= target <= 500 24 | */ 25 | 26 | public class CombinationSum { 27 | 28 | public static void main(String[] args) { 29 | // Test Case 1 30 | int[] candidates1 = {2, 3, 6, 7}; 31 | int target1 = 7; 32 | List> result1 = combinationSum(candidates1, target1); 33 | System.out.println("Test Case 1 - Output: " + result1); 34 | 35 | // Test Case 2 36 | int[] candidates2 = {2, 3, 5}; 37 | int target2 = 8; 38 | List> result2 = combinationSum(candidates2, target2); 39 | System.out.println("Test Case 2 - Output: " + result2); 40 | } 41 | 42 | /** 43 | * Returns all unique combinations where the numbers sum to the target. 44 | * 45 | * Algorithm: 46 | * 1. Use backtracking to find all possible combinations. 47 | * 2. At each step, try to include the current candidate and continue exploring. 48 | * 3. Allow the same candidate to be chosen multiple times by not moving to the next candidate. 49 | * 4. Skip the candidate if it causes the sum to exceed the target. 50 | * 51 | * Time Complexity: O(2^t * k), where t is the target and k is the average length of each combination. 52 | * Space Complexity: O(t), where t is the target. 53 | * 54 | * @param candidates - The input array of candidates. 55 | * @param target - The target sum. 56 | * @return The list of unique combinations. 57 | */ 58 | public static List> combinationSum(int[] candidates, int target) { 59 | List> result = new ArrayList<>(); 60 | List currentCombination = new ArrayList<>(); 61 | backtrack(candidates, target, 0, currentCombination, result); 62 | return result; 63 | } 64 | 65 | private static void backtrack(int[] candidates, int target, int start, List currentCombination, List> result) { 66 | if (target == 0) { 67 | result.add(new ArrayList<>(currentCombination)); // Found a valid combination 68 | return; 69 | } 70 | 71 | for (int i = start; i < candidates.length; i++) { 72 | if (candidates[i] > target) continue; // Skip if the candidate exceeds the remaining target 73 | 74 | currentCombination.add(candidates[i]); 75 | backtrack(candidates, target - candidates[i], i, currentCombination, result); // Same element can be used 76 | currentCombination.remove(currentCombination.size() - 1); // Backtrack 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/LeetCode/medium/00046/ Permutations.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 46. Permutations 3 | * Medium 4 | * 5 | * Given an array nums of distinct integers, return all the possible permutations. 6 | * You can return the answer in any order. 7 | * 8 | * Example 1: 9 | * Input: nums = [1,2,3] 10 | * Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 11 | * 12 | * Example 2: 13 | * Input: nums = [0,1] 14 | * Output: [[0,1],[1,0]] 15 | * 16 | * Example 3: 17 | * Input: nums = [1] 18 | * Output: [[1]] 19 | * 20 | * Constraints: 21 | * - 1 <= nums.length <= 6 22 | * - -10 <= nums[i] <= 10 23 | * - All the integers of nums are unique. 24 | */ 25 | 26 | import java.util.ArrayList; 27 | import java.util.List; 28 | 29 | public class Permutations { 30 | 31 | public static void main(String[] args) { 32 | // Test cases for checking Permutations 33 | testPermutations(new int[]{1, 2, 3}); 34 | testPermutations(new int[]{0, 1}); 35 | testPermutations(new int[]{1}); 36 | testPermutations(new int[]{1, 2, 3, 4}); 37 | testPermutations(new int[]{-1, 0, 1}); 38 | } 39 | 40 | /** 41 | * Method to test the Permutations function. 42 | * 43 | * @param nums The input array. 44 | */ 45 | public static void testPermutations(int[] nums) { 46 | List> result = permute(nums); 47 | System.out.println("Input: " + java.util.Arrays.toString(nums)); 48 | System.out.println("Permutations: " + result); 49 | System.out.println(); 50 | } 51 | 52 | /** 53 | * Method to generate all permutations of the given array. 54 | * 55 | * @param nums The input array. 56 | * @return A list of lists where each inner list is a permutation. 57 | */ 58 | public static List> permute(int[] nums) { 59 | List> result = new ArrayList<>(); 60 | backtrack(result, new ArrayList<>(), nums); 61 | return result; 62 | } 63 | 64 | /** 65 | * Helper method to perform backtracking to generate permutations. 66 | * 67 | * @param result The list to store all the permutations. 68 | * @param tempList The current permutation being formed. 69 | * @param nums The input array. 70 | */ 71 | private static void backtrack(List> result, List tempList, int[] nums) { 72 | // If the current list is the same length as the input array, we found a valid permutation 73 | if (tempList.size() == nums.length) { 74 | result.add(new ArrayList<>(tempList)); // Add a copy of the current list to the result 75 | } else { 76 | // Explore all possibilities 77 | for (int num : nums) { 78 | if (tempList.contains(num)) continue; // Skip if num is already in the current list 79 | tempList.add(num); // Add the current num 80 | backtrack(result, tempList, nums); // Recurse 81 | tempList.remove(tempList.size() - 1); // Remove last element (backtrack) 82 | } 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/LeetCode/medium/00048/48 Rotate Image.java: -------------------------------------------------------------------------------- 1 | /* 2 | 48. Rotate Image 3 | Medium 4 | You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). 5 | 6 | You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. 7 | 8 | Example 1: 9 | 10 | Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] 11 | Output: [[7,4,1],[8,5,2],[9,6,3]] 12 | Example 2: 13 | Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] 14 | Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] 15 | 16 | 17 | Constraints: 18 | 19 | n == matrix.length == matrix[i].length 20 | 1 <= n <= 20 21 | -1000 <= matrix[i][j] <= 1000 22 | */ 23 | 24 | public class RotateMatrix { 25 | 26 | public static void main(String[] args) { 27 | // Test case 1: Rotate a 2x2 matrix 28 | int[][] matrix1 = {{1, 2}, {3, 4}}; 29 | rotate(matrix1); 30 | printMatrix(matrix1); 31 | // Expected output: {{3, 1}, {4, 2}} 32 | 33 | // Test case 2: Rotate a 3x3 matrix 34 | int[][] matrix2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; 35 | rotate(matrix2); 36 | printMatrix(matrix2); 37 | // Expected output: {{7, 4, 1}, {8, 5, 2}, {9, 6, 3}} 38 | 39 | // Test case 3: Rotate a 4x4 matrix 40 | int[][] matrix3 = {{ 5, 1, 9, 11}, 41 | { 2, 4, 8, 10}, 42 | {13, 3, 6, 7}, 43 | {15, 14, 12, 16}}; 44 | rotate(matrix3); 45 | printMatrix(matrix3); 46 | // Expected output: {{15, 13, 2, 5}, {14, 3, 4, 1}, 47 | // {12, 6, 8, 9}, {16, 7, 10, 11}} 48 | } 49 | 50 | public static void rotate(int[][] matrix) { 51 | int n = matrix.length; 52 | 53 | // Step 1: Transpose the matrix 54 | for (int i = 0; i < n; i++) { 55 | for (int j = i + 1; j < n; j++) { 56 | // Swap element at position (i, j) with (j, i) 57 | int temp = matrix[i][j]; 58 | matrix[i][j] = matrix[j][i]; 59 | matrix[j][i] = temp; 60 | } 61 | } 62 | 63 | // Step 2: Reverse each row of the transposed matrix 64 | for (int i = 0; i < n; i++) { 65 | int left = 0, right = n - 1; 66 | while (left < right) { 67 | // Swap element at position (i, left) with (i, right) 68 | int temp = matrix[i][left]; 69 | matrix[i][left] = matrix[i][right]; 70 | matrix[i][right] = temp; 71 | left++; 72 | right--; 73 | } 74 | } 75 | } 76 | 77 | public static void printMatrix(int[][] matrix) { 78 | for (int i = 0; i < matrix.length; i++) { 79 | for (int j = 0; j < matrix[i].length; j++) { 80 | System.out.print(matrix[i][j] + " "); 81 | } 82 | System.out.println(); 83 | } 84 | System.out.println(); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/LeetCode/medium/00162/findPeakElement.java: -------------------------------------------------------------------------------- 1 | /* 2 | 162. Find Peak Element 3 | Medium 4 | 5 | A peak element is an element that is strictly greater than its neighbors. 6 | 7 | Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple 8 | peaks, return the index to any of the peaks. 9 | 10 | You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater 11 | than a neighbor that is outside the array. 12 | 13 | You must write an algorithm that runs in O(log n) time. 14 | 15 | Example 1: 16 | 17 | Input: nums = [1,2,3,1] 18 | Output: 2 19 | Explanation: 3 is a peak element and your function should return the index number 2. 20 | Example 2: 21 | 22 | Input: nums = [1,2,1,3,5,6,4] 23 | Output: 5 24 | Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the 25 | peak element is 6. 26 | 27 | 28 | Constraints: 29 | 30 | 1 <= nums.length <= 1000 31 | -231 <= nums[i] <= 231 - 1 32 | nums[i] != nums[i + 1] for all valid i. 33 | */ 34 | 35 | 36 | import java.util.*; 37 | 38 | public class PeakElement { 39 | public static void main(String[] args) { 40 | 41 | // Test Case 3 - Peak at the end 42 | int[] arr3 = {1, 2, 1, 3, 5, 6, 4}; 43 | int expected3 = 5; 44 | int result3 = indPeakElement(arr3); 45 | System.out.println("Test Case 3 - Input: " + Arrays.toString(arr3)); 46 | System.out.println("Test Case 3 - Expected result: " + expected3); 47 | System.out.println("Test Case 3 - Actual result: " + result3); 48 | System.out.println("Test Case 3 - Result matches expected: " + (result3 == expected3)); 49 | } 50 | 51 | 52 | 53 | 54 | public static int indPeakElement(int[] arr) { 55 | int start = 0; 56 | int end = arr.length - 1; 57 | 58 | while (start < end) { 59 | int mid = start + (end - start) / 2; 60 | 61 | if (arr[mid] > arr[mid + 1]) { 62 | /* 63 | * If arr[mid] is greater than arr[mid+1], 64 | * we are in the descending part of the array. 65 | * This means that the peak, if it exists, is in the range from start to mid. 66 | * Therefore, we update the end index to mid. 67 | */ 68 | end = mid; 69 | } else { 70 | /* 71 | * If arr[mid] is less than or equal to arr[mid+1], 72 | * we are in the ascending part of the array. 73 | * Since we know that arr[mid+1] is greater than arr[mid], 74 | * the peak index, if it exists, must be in the range from mid+1 to end. 75 | * Therefore, we update the start index to mid+1. 76 | */ 77 | start = mid + 1; 78 | } 79 | } 80 | } 81 | } -------------------------------------------------------------------------------- /src/LeetCode/medium/00167/twoSum.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 167. Two Sum II - Input Array Is Sorted 4 | Medium 5 | Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. 6 | 7 | Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2. 8 | 9 | The tests are generated such that there is exactly one solution. You may not use the same element twice. 10 | 11 | Your solution must use only constant extra space. 12 | 13 | 14 | Example 1: 15 | 16 | Input: numbers = [2,7,11,15], target = 9 17 | Output: [1,2] 18 | Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]. 19 | Example 2: 20 | 21 | Input: numbers = [2,3,4], target = 6 22 | Output: [1,3] 23 | Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3]. 24 | Example 3: 25 | 26 | Input: numbers = [-1,0], target = -1 27 | Output: [1,2] 28 | Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2]. 29 | 30 | 31 | Constraints: 32 | 33 | 2 <= numbers.length <= 3 * 104 34 | -1000 <= numbers[i] <= 1000 35 | numbers is sorted in non-decreasing order. 36 | -1000 <= target <= 1000 37 | The tests are generated such that there is exactly one solution. 38 | */ 39 | 40 | class Solution { 41 | public int[] twoSum(int[] numbers, int target) { 42 | // Use two pointers to find the pair of elements that add up to the target 43 | int left = 0; 44 | int right = numbers.length - 1; 45 | while (left < right) { 46 | int sum = numbers[left] + numbers[right]; 47 | if (sum == target) { 48 | return new int[]{left + 1, right + 1}; 49 | } else if (sum < target) { 50 | left++; 51 | } else { 52 | right--; 53 | } 54 | } 55 | 56 | // We should never reach this point if there is a valid solution. 57 | // However, if we do, we can return null or throw an exception. 58 | return null; 59 | } 60 | } -------------------------------------------------------------------------------- /src/LeetCode/medium/00322/CoinChange.java: -------------------------------------------------------------------------------- 1 | /** 2 | 322. Coin Change 3 | 4 | Medium 5 | 6 | You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. 7 | 8 | Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. 9 | 10 | You may assume that you have an infinite number of each kind of coin. 11 | 12 | Example 1: 13 | Input: coins = [1, 2, 5], amount = 11 14 | Output: 3 15 | Explanation: 11 = 5 + 5 + 1 16 | 17 | Example 2: 18 | Input: coins = [2], amount = 3 19 | Output: -1 20 | 21 | Example 3: 22 | Input: coins = [1], amount = 0 23 | Output: 0 24 | 25 | Constraints: 26 | - 1 <= coins.length <= 12 27 | - 1 <= coins[i] <= 231 - 1 28 | - 0 <= amount <= 104 29 | */ 30 | 31 | import java.util.Arrays; 32 | 33 | public class CoinChange { 34 | 35 | // ================================================== 36 | // Solution: Dynamic Programming approach to find the minimum number of coins 37 | // ================================================== 38 | public int coinChange(int[] coins, int amount) { 39 | // Create an array to store the minimum coins needed for each amount 40 | int[] dp = new int[amount + 1]; 41 | 42 | // Fill dp array with a large number (greater than the possible max) 43 | Arrays.fill(dp, amount + 1); 44 | 45 | // Base case: The minimum coins needed to make amount 0 is 0 46 | dp[0] = 0; 47 | 48 | // Iterate through each coin and for each coin, update the dp array 49 | for (int coin : coins) { 50 | for (int i = coin; i <= amount; i++) { 51 | dp[i] = Math.min(dp[i], dp[i - coin] + 1); 52 | } 53 | } 54 | 55 | // If dp[amount] is still greater than amount, it means it's not possible to make the amount 56 | return dp[amount] > amount ? -1 : dp[amount]; 57 | } 58 | 59 | // ================================================== 60 | // Main method to test the solution 61 | // ================================================== 62 | public static void main(String[] args) { 63 | CoinChange solution = new CoinChange(); 64 | 65 | // Test case 1: coins = [1, 2, 5], amount = 11 66 | int[] coins1 = {1, 2, 5}; 67 | int amount1 = 11; 68 | System.out.println("Test case 1: " + solution.coinChange(coins1, amount1)); // Output: 3 (11 = 5 + 5 + 1) 69 | 70 | // Test case 2: coins = [2], amount = 3 71 | int[] coins2 = {2}; 72 | int amount2 = 3; 73 | System.out.println("Test case 2: " + solution.coinChange(coins2, amount2)); // Output: -1 74 | 75 | // Test case 3: coins = [1], amount = 0 76 | int[] coins3 = {1}; 77 | int amount3 = 0; 78 | System.out.println("Test case 3: " + solution.coinChange(coins3, amount3)); // Output: 0 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/LeetCode/medium/00347/TopKFrequentElements.java: -------------------------------------------------------------------------------- 1 | /*** 2 | 347. Top K Frequent Elements 3 | 4 | Medium 5 | 6 | Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. 7 | 8 | Example 1: 9 | 10 | Input: nums = [1,1,1,2,2,3], k = 2 11 | Output: [1,2] 12 | Example 2: 13 | 14 | Input: nums = [1], k = 1 15 | Output: [1] 16 | 17 | 18 | Constraints: 19 | 20 | 1 <= nums.length <= 105 21 | -104 <= nums[i] <= 104 22 | k is in the range [1, the number of unique elements in the array]. 23 | It is guaranteed that the answer is unique. 24 | 25 | 26 | Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size. 27 | */ 28 | 29 | import java.util.*; 30 | 31 | public class TopKFrequentElements { 32 | 33 | /** 34 | * Function to return the k most frequent elements. 35 | * 36 | * @param nums the input array of integers 37 | * @param k the number of top frequent elements to return 38 | * @return a list of the k most frequent elements 39 | */ 40 | public int[] topKFrequent(int[] nums, int k) { 41 | // Step 1: Count the frequency of each element in the array using a HashMap. 42 | Map frequencyMap = new HashMap<>(); 43 | for (int num : nums) { 44 | frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); 45 | } 46 | 47 | // Step 2: Use a priority queue (min-heap) to keep track of the top k frequent elements. 48 | // The heap stores entries in the form of (element, frequency), and it's ordered by frequency. 49 | PriorityQueue> heap = 50 | new PriorityQueue<>((a, b) -> a.getValue() - b.getValue()); 51 | 52 | // Step 3: Iterate over the frequency map, and for each entry, push it into the heap. 53 | for (Map.Entry entry : frequencyMap.entrySet()) { 54 | heap.offer(entry); 55 | // If the heap size exceeds k, remove the element with the lowest frequency. 56 | if (heap.size() > k) { 57 | heap.poll(); 58 | } 59 | } 60 | 61 | // Step 4: Extract the elements from the heap to form the result. 62 | int[] result = new int[k]; 63 | int index = 0; 64 | while (!heap.isEmpty()) { 65 | result[index++] = heap.poll().getKey(); 66 | } 67 | 68 | return result; 69 | } 70 | 71 | public static void main(String[] args) { 72 | TopKFrequentElements solution = new TopKFrequentElements(); 73 | 74 | int[] nums1 = {1, 1, 1, 2, 2, 3}; 75 | int k1 = 2; 76 | System.out.println(Arrays.toString(solution.topKFrequent(nums1, k1))); // Output: [1, 2] 77 | 78 | int[] nums2 = {1}; 79 | int k2 = 1; 80 | System.out.println(Arrays.toString(solution.topKFrequent(nums2, k2))); // Output: [1] 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/LeetCode/medium/01679/Solution.java: -------------------------------------------------------------------------------- 1 | /*** 2 | 1679. Max Number of K-Sum Pairs 3 | 4 | You are given an integer array nums and an integer k. 5 | 6 | In one operation, you can pick two numbers from the array whose sum is equal to k, and remove them from the array. 7 | 8 | Return the maximum number of operations you can perform on the array. 9 | 10 | Example 1: 11 | Input: nums = [1,2,3,4], k = 5 12 | Output: 2 13 | Explanation: (1, 4) and (2, 3) are valid pairs, so the maximum number of operations is 2. 14 | 15 | Example 2: 16 | Input: nums = [3,1,3,4,3], k = 6 17 | Output: 1 18 | Explanation: (3, 3) is the only valid pair, so the maximum number of operations is 1. 19 | 20 | Constraints: 21 | 1 <= nums.length <= 105 22 | 1 <= nums[i] <= 1000 23 | 1 <= k <= 1000 24 | */ 25 | 26 | import java.util.HashMap; 27 | 28 | public class Solution { 29 | public int maxOperations(int[] nums, int k) { 30 | HashMap countMap = new HashMap<>(); 31 | int operations = 0; 32 | 33 | // Count the occurrences of each number in the array 34 | for (int num : nums) { 35 | countMap.put(num, countMap.getOrDefault(num, 0) + 1); 36 | } 37 | 38 | // For each number, try to find its complement that sums up to k 39 | for (int num : nums) { 40 | int complement = k - num; 41 | 42 | // If the complement exists and there are remaining numbers to form a pair 43 | if (countMap.getOrDefault(num, 0) > 0 && countMap.getOrDefault(complement, 0) > 0) { 44 | // Handle the case where the number and its complement are the same 45 | if (num == complement && countMap.get(num) > 1) { 46 | operations++; 47 | countMap.put(num, countMap.get(num) - 2); // Decrease count by 2 (pair found) 48 | } 49 | // Handle the case where the number and complement are different 50 | else if (num != complement) { 51 | operations++; 52 | countMap.put(num, countMap.get(num) - 1); // Decrease count of the number 53 | countMap.put(complement, countMap.get(complement) - 1); // Decrease count of the complement 54 | } 55 | } 56 | } 57 | 58 | return operations; 59 | } 60 | 61 | public static void main(String[] args) { 62 | // Test case 1: 63 | // Array: [1,2,3,4], k = 5 64 | // Pairs (1,4) and (2,3) can be selected, so the maximum number of operations is 2. 65 | int[] nums1 = {1, 2, 3, 4}; 66 | Solution solution1 = new Solution(); 67 | System.out.println("Test case 1: " + solution1.maxOperations(nums1, 5)); // Output: 2 68 | 69 | // Test case 2: 70 | // Array: [3,1,3,4,3], k = 6 71 | // Only the pair (3,3) can be selected, so the maximum number of operations is 1. 72 | int[] nums2 = {3, 1, 3, 4, 3}; 73 | Solution solution2 = new Solution(); 74 | System.out.println("Test case 2: " + solution2.maxOperations(nums2, 6)); // Output: 1 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/LeetCode/medium/01749/MaximumAbsoluteSumSubarray.java: -------------------------------------------------------------------------------- 1 | /** 2 | 1749. Maximum Absolute Sum of Any Subarray 3 | 4 | Medium 5 | 6 | You are given an integer array nums. The absolute sum of a subarray [numsl, numsl+1, ..., numsr-1, numsr] is abs(numsl + numsl+1 + ... + numsr-1 + numsr). 7 | 8 | Return the maximum absolute sum of any (possibly empty) subarray of nums. 9 | 10 | Note that abs(x) is defined as follows: 11 | 12 | If x is a negative integer, then abs(x) = -x. 13 | If x is a non-negative integer, then abs(x) = x. 14 | 15 | Example 1: 16 | 17 | Input: nums = [1,-3,2,3,-4] 18 | Output: 5 19 | Explanation: The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5. 20 | Example 2: 21 | 22 | Input: nums = [2,-5,1,-4,3,-2] 23 | Output: 8 24 | Explanation: The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8. 25 | 26 | 27 | Constraints: 28 | 29 | 1 <= nums.length <= 105 30 | -104 <= nums[i] <= 104 31 | */ 32 | public class MaximumAbsoluteSumSubarray { 33 | 34 | public static void main(String[] args) { 35 | int[] nums1 = {1, -3, 2, 3, -4}; 36 | int[] nums2 = {2, -5, 1, -4, 3, -2}; 37 | 38 | // Test Case 1 39 | System.out.println("Test Case 1:"); 40 | System.out.println("Maximum Absolute Sum of Subarray (Solution 1): " + maxAbsoluteSum(nums1)); // Output: 5 41 | System.out.println(); 42 | 43 | // Test Case 2 44 | System.out.println("Test Case 2:"); 45 | System.out.println("Maximum Absolute Sum of Subarray (Solution 1): " + maxAbsoluteSum(nums2)); // Output: 8 46 | } 47 | 48 | /** 49 | * Solution: Kadane's Algorithm for Maximum and Minimum Subarray Sum 50 | * Algorithm: 51 | * 1. Traverse the array and keep track of two variables: `maxSum` and `minSum`. 52 | * 2. `maxSum` represents the largest sum of any subarray. 53 | * 3. `minSum` represents the smallest (most negative) sum of any subarray. 54 | * 4. The maximum absolute sum will be the maximum of the absolute values of `maxSum` and `minSum`. 55 | * 56 | * Time Complexity: O(n), where n is the length of the array. 57 | * Space Complexity: O(1), as we only use a constant amount of space. 58 | */ 59 | public static int maxAbsoluteSum(int[] nums) { 60 | int maxSum = 0, minSum = 0; 61 | int currentMax = 0, currentMin = 0; 62 | 63 | for (int num : nums) { 64 | currentMax = Math.max(currentMax + num, num); // Kadane's for max subarray 65 | maxSum = Math.max(maxSum, currentMax); 66 | 67 | currentMin = Math.min(currentMin + num, num); // Kadane's for min subarray 68 | minSum = Math.min(minSum, currentMin); 69 | } 70 | 71 | return Math.max(Math.abs(maxSum), Math.abs(minSum)); // Maximum absolute sum 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/LeetCode/medium/02401/LongestNiceSubarray.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * 2401. Longest Nice Subarray 4 | * Medium 5 | * 6 | * You are given an array nums consisting of positive integers. 7 | * We call a subarray of nums nice if the bitwise AND of every pair of elements 8 | * that are in different positions in the subarray is equal to 0. 9 | * 10 | * Return the length of the longest nice subarray. 11 | * A subarray is a contiguous part of an array. 12 | * 13 | * Example 1: 14 | * Input: nums = [1,3,8,48,10] 15 | * Output: 3 16 | * Explanation: The longest nice subarray is [3,8,48]. The subarray satisfies: 17 | * - 3 AND 8 = 0. 18 | * - 3 AND 48 = 0. 19 | * - 8 AND 48 = 0. 20 | * It can be proven that no longer nice subarray can be obtained, so we return 3. 21 | * 22 | * Example 2: 23 | * Input: nums = [3,1,5,11,13] 24 | * Output: 1 25 | * Explanation: The longest nice subarray is any subarray containing one element. 26 | * There are no subarrays with a size greater than 1 that satisfy the condition. 27 | * 28 | * Constraints: 29 | * - 1 <= nums.length <= 10^5 30 | * - 1 <= nums[i] <= 10^9 31 | */ 32 | public class LongestNiceSubarray { 33 | public static void main(String[] args) { 34 | // Test Cases 35 | runTestCase(new int[]{1, 3, 8, 48, 10}, 3); 36 | runTestCase(new int[]{3, 1, 5, 11, 13}, 1); 37 | runTestCase(new int[]{2, 4, 8, 16}, 4); 38 | runTestCase(new int[]{6, 2, 7, 11}, 2); 39 | runTestCase(new int[]{12, 15, 7, 3}, 2); 40 | runTestCase(new int[]{14, 15, 16, 17}, 1); 41 | } 42 | 43 | // Method to run each test case 44 | public static void runTestCase(int[] nums, int expected) { 45 | int result = longestNiceSubarray(nums); 46 | 47 | System.out.println("Test Case - Input: nums = " + java.util.Arrays.toString(nums)); 48 | System.out.println("Expected result: " + expected); 49 | System.out.println("Result: " + result); 50 | System.out.println("Result matches expected: " + (result == expected)); 51 | System.out.println(); 52 | } 53 | 54 | /** 55 | * Approach: Sliding Window + Bitwise AND 56 | * 57 | * Algorithm Steps: 58 | * 1. Use a sliding window approach, extending the right end of the window. 59 | * 2. Keep track of the bitwise OR of all numbers in the current window. 60 | * 3. If a number violates the condition (i.e., the AND result is not 0), 61 | * slide the left end of the window to the right. 62 | * 4. Return the maximum window size. 63 | * 64 | * Time Complexity: O(n), where n is the length of the array. 65 | * Space Complexity: O(1), as we use constant extra space. 66 | */ 67 | public static int longestNiceSubarray(int[] nums) { 68 | int maxLen = 0; 69 | int left = 0; 70 | int bitwiseAnd = 0; 71 | 72 | for (int right = 0; right < nums.length; right++) { 73 | while ((bitwiseAnd & nums[right]) != 0) { 74 | bitwiseAnd ^= nums[left]; 75 | left++; 76 | } 77 | bitwiseAnd |= nums[right]; 78 | maxLen = Math.max(maxLen, right - left + 1); 79 | } 80 | 81 | return maxLen; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/Other Algorithms/00 A Very Big Sum.js: -------------------------------------------------------------------------------- 1 | // HackerRank (A Very Big Sum problem) => Array Sum 2 | // https://www.hackerrank.com/challenges/a-very-big-sum/problem 3 | 4 | "use strict"; 5 | 6 | const fs = require("fs"); 7 | 8 | process.stdin.resume(); 9 | process.stdin.setEncoding("utf-8"); 10 | 11 | let inputString = ""; 12 | let currentLine = 0; 13 | 14 | process.stdin.on("data", (inputStdin) => { 15 | inputString += inputStdin; 16 | }); 17 | 18 | process.stdin.on("end", (_) => { 19 | inputString = inputString 20 | .replace(/\s*$/, "") 21 | .split("\n") 22 | .map((str) => str.replace(/\s*$/, "")); 23 | 24 | main(); 25 | }); 26 | 27 | function readLine() { 28 | return inputString[currentLine++]; 29 | } 30 | 31 | // Complete the aVeryBigSum function below. 32 | function aVeryBigSum(ar) { 33 | let result = 0; 34 | for (let i = 0; i < ar.length; i++) { 35 | result += ar[i]; 36 | // console.log(result) 37 | } 38 | // console.log(result) 39 | return result; 40 | } 41 | 42 | function main() { 43 | const ws = fs.createWriteStream(process.env.OUTPUT_PATH); 44 | 45 | const arCount = parseInt(readLine(), 10); 46 | 47 | const ar = readLine() 48 | .split(" ") 49 | .map((arTemp) => parseInt(arTemp, 10)); 50 | 51 | let result = aVeryBigSum(ar); 52 | 53 | ws.write(result + "\n"); 54 | 55 | ws.end(); 56 | } 57 | -------------------------------------------------------------------------------- /src/Other Algorithms/01 Diagonal Difference.js: -------------------------------------------------------------------------------- 1 | // HackerRank (Diagonal Difference problem) => 2D Array 2 | // https://www.hackerrank.com/challenges/diagonal-difference/problem 3 | 4 | "use strict"; 5 | 6 | const fs = require("fs"); 7 | 8 | process.stdin.resume(); 9 | process.stdin.setEncoding("utf-8"); 10 | 11 | let inputString = ""; 12 | let currentLine = 0; 13 | 14 | process.stdin.on("data", function (inputStdin) { 15 | inputString += inputStdin; 16 | }); 17 | 18 | process.stdin.on("end", function () { 19 | inputString = inputString.split("\n"); 20 | 21 | main(); 22 | }); 23 | 24 | function readLine() { 25 | return inputString[currentLine++]; 26 | } 27 | 28 | /* 29 | * Complete the 'diagonalDifference' function below. 30 | * 31 | * The function is expected to return an INTEGER. 32 | * The function accepts 2D_INTEGER_ARRAY arr as parameter. 33 | */ 34 | 35 | function diagonalDifference(arr) { 36 | // Write your code here 37 | let firstDiagonalSum = 0; 38 | let secondDiagonalSum = 0; 39 | let totalSum = 0; 40 | 41 | for (let i = 0, length = arr.length; i < length; i++) { 42 | firstDiagonalSum += arr[i][i]; 43 | secondDiagonalSum += arr[length - 1 - i][i]; 44 | } 45 | totalSum = Math.abs(firstDiagonalSum - secondDiagonalSum); 46 | return totalSum; 47 | } 48 | 49 | function main() { 50 | const ws = fs.createWriteStream(process.env.OUTPUT_PATH); 51 | 52 | const n = parseInt(readLine().trim(), 10); 53 | 54 | let arr = Array(n); 55 | 56 | for (let i = 0; i < n; i++) { 57 | arr[i] = readLine() 58 | .replace(/\s+$/g, "") 59 | .split(" ") 60 | .map((arrTemp) => parseInt(arrTemp, 10)); 61 | } 62 | 63 | const result = diagonalDifference(arr); 64 | 65 | ws.write(result + "\n"); 66 | 67 | ws.end(); 68 | } 69 | -------------------------------------------------------------------------------- /src/Other Algorithms/02 Area Of Circle.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | int radius; 6 | final double pi = 3.142; 7 | double area; 8 | 9 | Scanner input = new Scanner(System.in); 10 | System.out.print("Enter radius: "); 11 | radius = input.nextInt(); 12 | 13 | // calculating the area of the circle 14 | area = pi * radius * radius; 15 | 16 | // printing the area of the circle 17 | System.out.println("Area of circle is :" + area); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Other Algorithms/03 Area Of Triangle.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | //Area of triangle = 1/2 × base × height 4 | public class Main { 5 | public static void main(String[] args) { 6 | int base,height; 7 | double area; 8 | 9 | Scanner input = new Scanner(System.in); 10 | System.out.print("Enter base, height: "); 11 | base = input.nextInt(); 12 | height = input.nextInt(); 13 | area = 1/2.0 * base * height; 14 | 15 | 16 | System.out.println("Area of triangle is :" + area); 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Other Algorithms/04 Area Of Parallelogram.java.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Main { 4 | private static Scanner sc; 5 | 6 | public static void main(String[] args) { 7 | int base, height; 8 | double area; 9 | 10 | Scanner input = new Scanner(System.in); 11 | System.out.print("Enter base, height: "); 12 | base = input.nextInt(); 13 | height = input.nextInt(); 14 | 15 | area = ParallelogramArea(base, height); 16 | 17 | System.out.format("rea of Parallelogram is = %.1f", area); 18 | } 19 | 20 | public static double ParallelogramArea(double base, double height) { 21 | return (base * height); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Other Algorithms/05 Area Of Equilateral Triangle.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class EquilateralTriangleArea { 4 | 5 | public static double calculateArea(double side) { 6 | return (Math.sqrt(3) / 4) * (side * side); 7 | } 8 | 9 | public static void main(String[] args) { 10 | Scanner sc = new Scanner(System.in); 11 | System.out.print("Enter the length of the side of the equilateral triangle: "); 12 | double side = sc.nextDouble(); 13 | 14 | double area = calculateArea(side); 15 | System.out.println("The area of the equilateral triangle is: " + area); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Other Algorithms/06 Perimeter Of Circle.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class CirclePerimeter { 4 | public static final double PI = 3.14159; 5 | 6 | public static double calculateCircumference(double radius) { 7 | return 2 * PI * radius; 8 | } 9 | 10 | public static void main(String[] args) { 11 | Scanner scanner = new Scanner(System.in); 12 | System.out.print("Enter the radius of the circle: "); 13 | double radius = scanner.nextDouble(); 14 | double circumference = calculateCircumference(radius); 15 | System.out.println("The circumference of a circle with radius " + radius + " is " + circumference); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Other Algorithms/07 Prime.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | function isPrime(num) { 4 | for (let i = 2; i <= num / 2; i++) { 5 | if (num % i === 0) { 6 | return false; 7 | } 8 | } 9 | return true; 10 | } 11 | 12 | console.log(isPrime(5)); 13 | 14 | function isPrime(num) { 15 | for (let i = 2; i <= Math.sqrt(num); i++) { 16 | if (num % i === 0) { 17 | return false; 18 | } 19 | } 20 | return true; 21 | } 22 | 23 | console.log(isPrime(5)); 24 | 25 | 26 | 27 | 28 | 29 | function checkPrime(num) { 30 | // 1 is not a prime number 31 | if (num === 1) { 32 | return false; 33 | } 34 | // 2 and 3 are prime numbers 35 | if (num === 2 || num === 3) { 36 | return true; 37 | } 38 | // Any number divisible by 2 or 3 is not a prime number 39 | if (num % 2 === 0 || num % 3 === 0) { 40 | return false; 41 | } 42 | 43 | // Check for divisibility by numbers from 4 to the square root of the number 44 | for (let i = 4; i <= Math.sqrt(num); i++) { 45 | if (num % i === 0) { 46 | return false; 47 | } 48 | } 49 | 50 | // If the number is not divisible by any number, it is a prime number 51 | return true; 52 | } 53 | 54 | console.log(checkPrime(1)); // false 55 | console.log(checkPrime(2)); // true 56 | console.log(checkPrime(4)); // false 57 | console.log(checkPrime(5)); // true 58 | -------------------------------------------------------------------------------- /src/Other Algorithms/08 Fibonacci-Sequence.js: -------------------------------------------------------------------------------- 1 | function fib(num) { 2 | const numbers = [1, 1]; 3 | 4 | for (let i = 2; i < num + 1; ++i) { 5 | numbers.push(numbers[i - 2] + numbers[i - 1]); 6 | } 7 | 8 | return numbers; 9 | } 10 | 11 | console.log(fib(6)); 12 | -------------------------------------------------------------------------------- /src/Other Algorithms/10 Volume Of Cone.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class RhombusPerimeter { 4 | public static void main(String[] args) { 5 | Scanner scanner = new Scanner(System.in); 6 | System.out.print("Enter the side length of the rhombus: "); 7 | double sideLength = scanner.nextDouble(); 8 | double perimeter = 4 * sideLength; 9 | System.out.println("The perimeter of the rhombus is: " + perimeter); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/Other Algorithms/11 isPowerOfTwo.js: -------------------------------------------------------------------------------- 1 | // Program to find whether a no is power of two 2 | 3 | function isPowerOfTwo(number){ 4 | if(number < 1)return false; 5 | let dividedNumber = number; 6 | 7 | while(dividedNumber !== 1){ 8 | // console.log(dividedNumber); 9 | 10 | if(dividedNumber % 2 !== 0){ 11 | return false; 12 | } 13 | dividedNumber = dividedNumber / 2; 14 | } 15 | return true; 16 | } 17 | 18 | console.log(isPowerOfTwo(10)); 19 | console.log(isPowerOfTwo(8)); 20 | console.log(isPowerOfTwo(5)); 21 | console.log(isPowerOfTwo(20)); 22 | console.log(isPowerOfTwo(16)); 23 | -------------------------------------------------------------------------------- /src/Other Algorithms/12 Ncr and Npr.jav: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | 4 | public class Main { 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | 8 | System.out.print("Enter n: "); 9 | int n = sc.nextInt(); 10 | 11 | System.out.print("Enter r: "); 12 | int r = sc.nextInt(); 13 | 14 | BigInteger nPrResult = nPr(n, r); 15 | BigInteger nCrResult = nCr(n, r); 16 | 17 | System.out.println("nPr Result: " + nPrResult); 18 | System.out.println("nPr Result: " + nCrResult); 19 | } 20 | 21 | public static BigInteger nPr(int n, int r) { 22 | // nPr = n! / (n - r)! 23 | BigInteger nFactorial = calculateFactorial(n); 24 | BigInteger nMinusRFactorial = calculateFactorial(n - r); 25 | 26 | BigInteger result = nFactorial.divide(nMinusRFactorial); 27 | return result; 28 | } 29 | 30 | 31 | public static BigInteger nCr(int n, int r) { 32 | // nCr = n! / (r! * (n - r)!) 33 | BigInteger nFactorial = calculateFactorial(n); 34 | BigInteger rFactorial = calculateFactorial(r); 35 | BigInteger nMinusRFactorial = calculateFactorial(n - r); 36 | return nFactorial.divide(rFactorial.multiply(nMinusRFactorial)); 37 | } 38 | 39 | private static BigInteger calculateFactorial(int n) { 40 | BigInteger factorial = BigInteger.ONE; 41 | 42 | for (int i = 1; i <= n; i++) { 43 | BigInteger currentNumber = BigInteger.valueOf(i); 44 | 45 | factorial = factorial.multiply(currentNumber); 46 | } 47 | 48 | return factorial; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/Other Algorithms/13 HCF Of Two Numbers.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | 4 | public class Main { 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | System.out.print("Enter 2 number : "); 8 | int num1 = sc.nextInt(); 9 | int num2 = sc.nextInt(); 10 | 11 | int result = findHCF(num1, num2); 12 | System.out.println("The Highest Common Factor of " + num1 + " and " + num2 + " is " + result); 13 | 14 | } 15 | 16 | 17 | // GCD Or HCF 18 | public static int findHCF(int num1, int num2) { 19 | 20 | int min = Math.min(num1, num2); 21 | 22 | int result = 1; 23 | while (min != 0) { 24 | if (num1 % min == 0 && num2 % min == 0) { 25 | result = min; 26 | break; 27 | } 28 | min--; 29 | } 30 | return result; 31 | } 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/Other Algorithms/14 LCM Of Two Numbers.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | System.out.print("Enter 2 number : "); 7 | int num1 = sc.nextInt(); 8 | int num2 = sc.nextInt(); 9 | 10 | int result = findLCM(num1, num2); 11 | System.out.println("The The Minimum Common Factor of " + num1 + " and " + num2 + " is " + result); 12 | 13 | } 14 | 15 | 16 | // LCM 17 | public static int findLCM(int num1, int num2) { 18 | int min = Math.max(num1, num2); 19 | int result = min; 20 | 21 | while (!(result % num1 == 0 && result % num2 == 0)) { 22 | result += min; 23 | } 24 | 25 | return result; 26 | } 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/Other Algorithms/15 Prime.js: -------------------------------------------------------------------------------- 1 | function checkPrime(num) { 2 | // 1 is not a prime number 3 | // any number less than one is not prime 4 | if (num <= 1) { 5 | return false; 6 | } 7 | // 2 and 3 are prime numbers 8 | if (num === 2 || num === 3) { 9 | return true; 10 | } 11 | // Any number divisible by 2 or 3 is not a prime number 12 | if (num % 2 === 0 || num % 3 === 0) { 13 | return false; 14 | } 15 | 16 | // Check for divisibility by numbers from 4 to the square root of the number 17 | for (let i = 4; i <= Math.sqrt(num); i++) { 18 | if (num % i === 0) { 19 | return false; 20 | } 21 | } 22 | 23 | // If the number is not divisible by any number, it is a prime number 24 | return true; 25 | } 26 | 27 | console.log(checkPrime(-7)); // false 28 | console.log(checkPrime(1)); // false 29 | console.log(checkPrime(2)); // true 30 | console.log(checkPrime(4)); // false 31 | console.log(checkPrime(5)); // true 32 | -------------------------------------------------------------------------------- /src/Other Algorithms/16 prime numbers 1 to N.java: -------------------------------------------------------------------------------- 1 | // find all prime numbers between 1 and a given integer 'n' 2 | // using the Sieve of Eratosthenes algorithm 3 | 4 | // The time complexity of this algorithm is O(n log log n) and the space complexity is O(n). 5 | 6 | import java.util.Scanner; 7 | 8 | public class PrimeNumbers{ 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | System.out.print("Enter a value for n: "); 12 | int n = scanner.nextInt(); 13 | findPrimes(n); 14 | } 15 | 16 | private static void findPrimes(int n) { 17 | if (n < 2) { 18 | System.out.println("Invalid value for n. Please enter a value greater than or equal to 2."); 19 | return; 20 | } 21 | 22 | boolean[] isComposite = new boolean[n + 1]; 23 | isComposite[0] = true; 24 | isComposite[1] = true; 25 | 26 | // same as i<= Math.sqrt(n) 27 | for (int i = 2; (i * i) <= n; i++) { 28 | if (!isComposite[i]) { 29 | for (int j = i * i; j <= n; j += i) { 30 | isComposite[j] = true; 31 | } 32 | } 33 | } 34 | 35 | System.out.print("Prime numbers from 1 to " + n + ": "); 36 | 37 | 38 | int count = 0; 39 | for (int i = 0; i <= n; i++) { 40 | if (!isComposite[i]) { 41 | System.out.print(i + " "); 42 | count++; 43 | if (count % 10 == 0) { 44 | System.out.println(); 45 | } 46 | } 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/Recursion/SkipCharacters.java: -------------------------------------------------------------------------------- 1 | public class SkipCharacters { 2 | 3 | public static void main(String[] args) { 4 | String str1 = "AppleAndAardvark"; 5 | String str2 = "AnAappleAdmirer"; 6 | String str3 = "appetizer app applet apple appliance"; 7 | 8 | System.out.println("Skipping 'apple': " + skipApple(str2)); 9 | System.out.println("Skipping 'A': " + skipChar(str1, 'A')); 10 | System.out.println("Skipping 'a': " + skipChar(str2, 'a')); 11 | System.out.println("Skipping 'test': " + skipWord("this is a test string test test", "test")); 12 | System.out.println("Skipping 'app' but not 'apple': " + skipAppNotApple(str3)); 13 | } 14 | 15 | // Generalized function to skip a specific character 16 | public static String skipChar(String str, char skipChar) { 17 | if (str.isEmpty()) { 18 | return ""; 19 | } 20 | char currentChar = str.charAt(0); 21 | if (currentChar == skipChar) { 22 | return skipChar(str.substring(1), skipChar); // Skip the current character 23 | } 24 | return currentChar + skipChar(str.substring(1), skipChar); // Include the current character 25 | } 26 | 27 | // Function to skip the substring "apple" 28 | public static String skipApple(String str) { 29 | if (str.isEmpty()) { 30 | return ""; 31 | } 32 | if (str.startsWith("apple")) { 33 | return skipApple(str.substring(5)); // Skip the "apple" substring 34 | } 35 | return str.charAt(0) + skipApple(str.substring(1)); // Include the current character 36 | } 37 | 38 | // Function to skip any specific word 39 | public static String skipWord(String str, String wordToSkip) { 40 | if (str.isEmpty()) { 41 | return ""; 42 | } 43 | if (str.startsWith(wordToSkip)) { 44 | return skipWord(str.substring(wordToSkip.length()), wordToSkip); // Skip the specified word 45 | } 46 | return str.charAt(0) + skipWord(str.substring(1), wordToSkip); // Include the current character 47 | } 48 | 49 | // Function to skip any word that starts with "app" but not "apple" 50 | public static String skipAppNotApple(String str) { 51 | if (str.isEmpty()) { 52 | return ""; 53 | } 54 | if (str.startsWith("app") && !str.startsWith("apple")) { 55 | // Skip the word that starts with "app" but isn't "apple" 56 | int index = findFirstNonAlphabeticChar(str); 57 | return skipAppNotApple(str.substring(index)); 58 | } 59 | return str.charAt(0) + skipAppNotApple(str.substring(1)); // Include the current character 60 | } 61 | 62 | // Helper function to find the index of the first non-alphabetic character (like a space or punctuation) 63 | private static int findFirstNonAlphabeticChar(String str) { 64 | for (int i = 0; i < str.length(); i++) { 65 | if (!Character.isLetter(str.charAt(i))) { 66 | return i; // Return the index of the first non-alphabetic character 67 | } 68 | } 69 | return str.length(); // If no non-alphabetic character is found, return the string length 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/Recursion/Subsequence.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Subsequence { 4 | 5 | public static void main(String[] args) { 6 | String str = "abc"; 7 | printSubsequences( "",str); 8 | 9 | 10 | int count = countSubsequences(str); 11 | System.out.println("Total number of subsequences: " + count); 12 | 13 | ArrayList result= subsequencesList("",str); 14 | System.out.println(result); 15 | } 16 | 17 | private static ArrayList subsequencesList(String unprocess, String process) { 18 | if(process.isEmpty()){ 19 | ArrayListlist = new ArrayList<>(); 20 | list.add(unprocess); 21 | return list; 22 | } 23 | 24 | char ch = process.charAt(0); 25 | 26 | ArrayList left = subsequencesList((unprocess+ch), process.substring(1)); 27 | ArrayList right= subsequencesList(unprocess, process.substring(1)); 28 | left.addAll(right); 29 | return left; 30 | } 31 | 32 | private static void printSubsequences(String unprocess, String process) { 33 | if(process.isEmpty()){ 34 | System.out.println(unprocess); 35 | return; 36 | } 37 | char ch = process.charAt(0); 38 | 39 | printSubsequences((unprocess+ch), process.substring(1)); 40 | printSubsequences(unprocess, process.substring(1)); 41 | } 42 | 43 | 44 | 45 | // Method to count the total number of subsequences using recursive approach 46 | static int countSubsequences(String str) { 47 | return countSubsequencesHelper(str, 0); 48 | } 49 | 50 | // Helper method to count subsequences recursively 51 | static int countSubsequencesHelper(String str, int index) { 52 | // Base case: if we have reached the end of the string, return 1 (the empty subsequence) 53 | if (index == str.length()) { 54 | return 1; 55 | } 56 | 57 | // Recursive case: for each character, we have two choices - include or exclude 58 | int exclude = countSubsequencesHelper(str, index + 1); // Exclude the current character 59 | int include = countSubsequencesHelper(str, index + 1); // Include the current character 60 | 61 | // Total subsequences = subsequences excluding current character + subsequences including current character 62 | return exclude + include; 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/Searching/Binary search /Search Binary Search Iterative Method l: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saddamarbaa/data-structures-and-algorithms/616cf6c0db16952269034319b7da6b1e7ca8c20c/src/Searching/Binary search /Search Binary Search Iterative Method l -------------------------------------------------------------------------------- /src/Shortest Path/README.md: -------------------------------------------------------------------------------- 1 | # Todo 2 | 3 | -------------------------------------------------------------------------------- /src/Sorting/Bubble Sort/Sort Array Exercise ascending order.c: -------------------------------------------------------------------------------- 1 | /** 2 | [AUTHOR]: Saddam Arbaa 3 | [Email] : 4 | 5 | C Arrays Examples 6 | write Program that take array size from user and create array with 7 | the size given by user and ask user to enter all the array 8 | element and store them in an array. 9 | the lastly 10 | (1)Print all the element of array before sorting 11 | (2) sort array from smaller to bigger 12 | (1)Print all the element of array after sorting 13 | 14 | (the array(size must be bigger than 0) 15 | 16 | */ 17 | 18 | #include 19 | #include 20 | 21 | // the Driver Code 22 | int main() 23 | { 24 | // N size of the array ,i,j are counters 25 | // temp for swapping element in sorting process 26 | int N , temp ,i,j; 27 | 28 | // get valid size first 29 | do 30 | { 31 | // asking the length of array from user 32 | printf("Enter number of elements(size must be bigger than zero): "); 33 | scanf("%d",&N); 34 | 35 | } while (N <= 0); 36 | 37 | // Array declaration 38 | int vector [N]; 39 | 40 | printf("------------------------------\n"); 41 | printf("Enter %d numbers: \n",N); 42 | 43 | // taking input from user and storing it in an array 44 | for (i = 0; i <= N - 1; i++) 45 | { 46 | // The use of '&' before a variable name,mean user input will 47 | // be store in the address of variable. 48 | 49 | printf("Enter vector[ %d ]: ",(i+1) ); 50 | scanf("%d",&vector[i]); 51 | } 52 | 53 | printf("---------------------------\n"); 54 | printf("element of Array Before arrangement are : \n"); 55 | 56 | // printing elements of an array before sorting 57 | for (i = 0; i <= N - 1; i++) 58 | { 59 | printf("vector[ %d ] : %d\n", i +1 ,vector[i]); 60 | } 61 | 62 | // sorting the array 63 | // outer loop 64 | for ( i = 0; i <= N - 1; i++) 65 | { 66 | // inner loop 67 | for (j = i + 1; j <= N - 1; j++) 68 | { 69 | // if condition true 70 | if(vector[i] > vector[j]) 71 | { 72 | temp = vector[i]; // keep vector[i] in temp 73 | 74 | // swap between vector[j] and vector[i] 75 | vector[i] = vector[j]; // store vector[j] on vector[i] 76 | 77 | vector[j] = temp; // store vector[i] on vector[j] 78 | } 79 | } 80 | } 81 | 82 | printf("element of Array after arrangement are : \n"); 83 | 84 | // printing elements of an array after sorting 85 | for (i = 0; i <= N - 1; i++) 86 | { 87 | printf("vector[ %d ] : %d\n", i +1 ,vector[i]); 88 | } 89 | 90 | return 0;// signal to operating system everything works fine 91 | 92 | }/** End of main function */ 93 | -------------------------------------------------------------------------------- /src/Sorting/Bubble Sort/Sort Array Exercise names.c: -------------------------------------------------------------------------------- 1 | /** 2 | [PROGRAM] : Sort names in an alphabetical order 3 | [AUTHOR] : Saddam Arbaa 4 | [Email] : 5 | 6 | C program to read N names from user,store them in name array 7 | and sort them in alphabetical order. 8 | (1) : print the names before sort 9 | (2) : print the given names and the sorted 10 | names in two columns side by side. */ 11 | 12 | #include 13 | #include 14 | // include string.h 15 | #include 16 | 17 | // define the maximum Array size 18 | #define MAXSIZE 50 19 | 20 | // the Driver Code 21 | int main() 22 | { 23 | printf("C program to sort an array of N names in an alphabetical order :\n\n"); 24 | 25 | /* variables declaration */ 26 | int i, j, n; 27 | 28 | // 3 Array declaration 29 | char name[MAXSIZE][18], 30 | copy_name[MAXSIZE][18], 31 | temp[18]; 32 | 33 | // get valid size for Array 34 | do 35 | { 36 | // asking the length of array from user 37 | printf("Enter size for Array --> name " 38 | ":\n(size must be bigger than zero and las than or equal to %d): ", MAXSIZE); 39 | scanf("%d",&n); 40 | 41 | }while(n <= 0 || n > MAXSIZE); 42 | 43 | //taking input from user and storing it in name array 44 | printf("Enter %d names n \n", n); 45 | for (i = 0; i < n; i++) 46 | { 47 | printf("Enter name %d : ",i + 1); 48 | scanf("%s", name[i]); 49 | strcpy(copy_name[i], name[i]); // copy all the names in copy array 50 | 51 | } /* End of for loop */ 52 | 53 | /** sorting start from here*/ 54 | 55 | // outer loop 56 | for( i = 0; i <= n - 2; i++) 57 | { 58 | // inner loop 59 | for(j = i + 1; j <= n - 1; j++) 60 | { 61 | /* 62 | using string function strcmp() to compare the names 63 | by their ASCII value and sorted in an alphabetical order 64 | */ 65 | if(strcmp(name[i], name[j]) > 0) // if condition true 66 | { 67 | /* swap between name[j] and name[i] by using 68 | string function strcpy() */ 69 | strcpy(temp, name[i]); 70 | strcpy(name[i], name[j]); 71 | strcpy(name[j], temp); 72 | } 73 | } /** End of inner loop */ 74 | 75 | } /** End of outer loop */ 76 | 77 | // print the names befor sort 78 | printf("the names before sort are \n"); 79 | for (i = 0; i < n; i++) 80 | { 81 | printf("%s\t", copy_name[i]); 82 | 83 | } /* End of for loop */ 84 | printf("\n"); 85 | 86 | // print the names after sort 87 | printf("the names after sorted in alphabetical order are \n"); 88 | for (i = 0; i < n; i++) 89 | { 90 | printf("%s\t\t%s\n", copy_name[i], name[i]); 91 | 92 | }/* End of for loop */ 93 | 94 | return 0;// signal to operating system everything works fine 95 | 96 | }/** End of main function */ 97 | -------------------------------------------------------------------------------- /src/Sorting/cycle sort /CycleSort.java: -------------------------------------------------------------------------------- 1 | public class CycleSort { 2 | public static void main(String[] args) { 3 | // Example 1: Sorting in ascending order 4 | int[] array1 = {3, 2, 1, 5, 9, 7, 8, 4, 6}; 5 | System.out.println("Original Array 1:"); 6 | printArray(array1); 7 | cycleSort(array1, true); 8 | System.out.println("Sorted Array 1 (Ascending):"); 9 | printArray(array1); 10 | 11 | // Example 2: Sorting in descending order 12 | int[] array2 = {10, 5, 8, 2, 7, 1, 3, 6, 4, 9}; 13 | System.out.println("\nOriginal Array 2:"); 14 | printArray(array2); 15 | cycleSort(array2, false); 16 | System.out.println("Sorted Array 2 (Descending):"); 17 | printArray(array2); 18 | } 19 | 20 | 21 | /** 22 | * Cycle Sort Algorithm 23 | * Algorithm Steps: 24 | * 1. Traverse the array from the start. 25 | * 2. For each element, find its correct position (index) in the sorted array. 26 | * 3. Swap the current element with the element at its correct position. 27 | * 4. Continue this process until the entire array is sorted. 28 | * 29 | * Time Complexity: 30 | * - Worst Case Time Complexity: O(n). 31 | * - Best Case Time Complexity: O(n). 32 | * - Average Case Time Complexity: O(n). 33 | * 34 | * Space Complexity: 35 | * - Space Complexity: O(1) - constant space is used for variables. 36 | * 37 | * @param array The array to be sorted. 38 | */ 39 | public static void cycleSort(int[] array, boolean... ascending) { 40 | int size = array.length; 41 | int currentIndex = 0; 42 | boolean isAscending = ascending.length == 0 || ascending[0]; 43 | 44 | 45 | while (currentIndex < size) { 46 | // Find the correct index for the current element in the sorted array 47 | int correctIndex = array[currentIndex] - 1; 48 | 49 | // Perform cyclic swapping until the current element is at its correct position 50 | if (currentIndex != correctIndex) { 51 | swap(array, currentIndex, correctIndex); 52 | } else { 53 | currentIndex++; 54 | } 55 | } 56 | 57 | if(!isAscending) { 58 | // Reverse the array for descending order 59 | for (int i = 0; i < size / 2; i++) { 60 | swap(array, i, size - 1 - i); 61 | } 62 | } 63 | } 64 | 65 | 66 | 67 | 68 | public static void printArray(int[] arr) { 69 | for (int value : arr) { 70 | System.out.print(value + " "); 71 | } 72 | System.out.println(); 73 | } 74 | 75 | /** 76 | * Function to swap values of two variables (user should pass the array and 77 | * indices as parameters) 78 | */ 79 | private static void swap(int[] array, int a, int b) { 80 | int temp = array[a]; 81 | array[a] = array[b]; 82 | array[b] = temp; 83 | } 84 | } -------------------------------------------------------------------------------- /src/Spanning Tree/graph Minimum Spanning Tree.c: -------------------------------------------------------------------------------- 1 | /** 2 | * [PROG] : Implementation Minimum Spanning Tree 3 | using | Prim's Algorithm 4 | 5 | * [AUTHOR] : Saddam Arbaa 6 | 7 | C program for Prim's Algorithm to find Minimum Spanning Tree 8 | of a given connected, undirected and weighted graph 9 | 10 | 11 | reference 12 | (1) https://youtu.be/k9jemw3SZe0 13 | (2) https://youtu.be/7FtGk9yr66A 14 | 15 | */ 16 | 17 | 18 | #include 19 | 20 | #include 21 | 22 | // the Driver Code 23 | int main() 24 | { 25 | 26 | printf("code is not complete yet\n"); 27 | 28 | 29 | 30 | return 0; // signal to operating system program ran fine 31 | } 32 | -------------------------------------------------------------------------------- /src/Stacks/GenericStack.java: -------------------------------------------------------------------------------- 1 | public class Stack { // T is a generic type placeholder 2 | private int capacity; 3 | private int top; 4 | private T[] arr; 5 | 6 | @SuppressWarnings("unchecked") 7 | public Stack(int capacity) { 8 | this.capacity = capacity; 9 | arr = (T[]) new Object[capacity]; // Creating a generic array 10 | top = -1; 11 | } 12 | 13 | public void push(T value) { 14 | if (isFull()) { 15 | System.out.println("Stack is full! Cannot push " + value); 16 | } else { 17 | arr[++top] = value; 18 | System.out.println("Pushed " + value + " to the stack."); 19 | } 20 | } 21 | 22 | public T pop() { 23 | if (isEmpty()) { 24 | System.out.println("Stack is empty! Cannot pop."); 25 | return null; 26 | } else { 27 | T poppedValue = arr[top--]; 28 | System.out.println("Popped " + poppedValue + " from the stack."); 29 | return poppedValue; 30 | } 31 | } 32 | 33 | public T peek() { 34 | if (isEmpty()) { 35 | System.out.println("Stack is empty! Cannot peek."); 36 | return null; 37 | } else { 38 | return arr[top]; 39 | } 40 | } 41 | 42 | public int count() { 43 | return top + 1; 44 | } 45 | 46 | public void display() { 47 | if (isEmpty()) { 48 | System.out.println("Stack is empty!"); 49 | } else { 50 | System.out.print("Stack elements: "); 51 | for (int i = 0; i <= top; i++) { 52 | System.out.print(arr[i] + " "); 53 | } 54 | System.out.println(); 55 | } 56 | } 57 | 58 | public boolean isFull() { 59 | return top == capacity - 1; 60 | } 61 | 62 | public boolean isEmpty() { 63 | return top == -1; 64 | } 65 | 66 | public void change(int index, T newValue) { 67 | if (index >= 0 && index <= top) { 68 | arr[index] = newValue; 69 | System.out.println("Changed value at index " + index + " to " + newValue); 70 | } else { 71 | System.out.println("Invalid index! Cannot change value."); 72 | } 73 | } 74 | 75 | public static void main(String[] args) { 76 | Stack stack = new Stack<>(5); // Example with Integer 77 | 78 | stack.push(10); 79 | stack.push(20); 80 | stack.push(30); 81 | stack.push(40); 82 | stack.push(50); 83 | 84 | stack.display(); 85 | 86 | stack.push(60); // This should print that the stack is full. 87 | 88 | System.out.println("Peek top: " + stack.peek()); 89 | 90 | stack.pop(); 91 | stack.pop(); 92 | 93 | stack.display(); 94 | 95 | System.out.println("Is stack empty? " + stack.isEmpty()); 96 | System.out.println("Current stack size: " + stack.count()); 97 | 98 | // Change value at index 1 99 | stack.change(1, 100); 100 | 101 | stack.display(); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/String/README.md: -------------------------------------------------------------------------------- 1 | # Todo 2 | 3 | -------------------------------------------------------------------------------- /src/Trees/Tree B+ tree .c: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/Trees/Tree B-Tree.c: -------------------------------------------------------------------------------- 1 | 2 | --------------------------------------------------------------------------------