├── 35-Solve_Question3.4.java ├── Basic Banking System ├── Bank.java └── Readme.md ├── CONTRIBUTING.md ├── Calculator-using-Java-and-Javafx ├── .classpath ├── .project ├── .settings │ ├── org.eclipse.core.resources.prefs │ └── org.eclipse.jdt.core.prefs └── build.fxbuild ├── CodeforBanks ├── Criteria.txt ├── DSA ├── BuddyStrings.java ├── ChocolatePickup.java ├── FirstMissingPositive_LeetcodeHard.java ├── HareAndTortoise.java ├── LeafAndPath.java ├── MajorityElementII.java ├── MaxSumCircularArray.java ├── MethodOverriding.java ├── MinOperations.java ├── Overloading_1.java ├── Pattern132.java ├── Product Of All Except Self.java ├── QueueUsingStack.java ├── SlidingWindowMaximum.class ├── SlidingWindowMaximum.java ├── StackUsingQueue.java ├── TowerOfHanoi.java ├── TrappingRainWater.java ├── Trie.class ├── Trie.java ├── TrieNode.class ├── bfs.java ├── circualarqueue.java ├── dfs.java ├── dijkstra.java ├── dsa-recursion.java ├── fibonacciSeries.java ├── infixtopostfix.java ├── kadanesAlgo.java ├── kruskalExample.java ├── pattern.java └── primsAlgo.java ├── DiagonalSum.java ├── Java-Algorithm ├── Anagrammanipulatorr.java ├── ArrangingCoin.java ├── CycleDetectionPrt.java ├── Depth_First_Search.java ├── KadaneAlgorithm.java ├── Longest common prefix.java ├── Palindrom.java ├── PasswordGenerator.java ├── Prims_Algorithm_mst.java ├── Search-algorithm.java ├── TopologicalSort.java └── UniqueFloydAlgorithmpo.java ├── Java-Area ├── Area-of-circle.java ├── Area.java └── PrintAreaOfShape.java ├── Java-OOPS └── Inheritance │ ├── Inheritance-Examples │ ├── HierarchicalInheritanceExample.java │ ├── HybridInheritanceExample.java │ ├── InheritanceExample.java │ ├── MultilevelInheritanceExample.java │ ├── MultipleInheritanceExample.java │ └── SingleInheritanceExample.java │ ├── ReadMe.md │ ├── SubclassAndSuperClass │ └── Readme.md │ └── diagrams │ └── inheritance.png ├── Java-searching ├── BinarySearch.java ├── LinearSearch.java └── binarySearch.class ├── Java-sorting ├── CycleSort.java ├── DDsort.java ├── HarmonicSort.java ├── InsertSortTest.java ├── ShellSort.java ├── TimSort.java ├── bubble_sort.java ├── mergesort.java ├── quick_sort.cpp └── tree_sort.java ├── JavaTaskManager.java ├── LeetCode Questions ├── LeetCode Easy │ ├── 108. Convert Sorted Array to Binary Search Tree │ │ ├── README.md │ │ ├── Solution.cpp │ │ └── Solution.java │ ├── 1337. K Weakest Rows in a Matrix │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md │ ├── 141. Linked List Cycle │ │ ├── explanantion.md │ │ ├── sol.cpp │ │ └── sol.java │ ├── 1512. Number of Good Pairs │ │ ├── NoOfGP.java │ │ ├── explanation.md.txt │ │ └── sol.cpp │ ├── 389. Find the Difference │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md │ ├── 392. Is Subsequence │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md │ ├── 58. Length of Last Word │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md │ └── 905. Sort Array by Parity │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md ├── LeetCode Hard │ ├── 1095. Find In Mountain Array │ │ ├── sol.java │ │ └── sol.md │ ├── 1203. Sort Items by Groups Respecting Dependencies │ │ ├── sol.java │ │ └── sol.md │ ├── 1326. Min no of Taps to Open to Water a Garden │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md │ ├── 1359. Count All Valid Pickup and Delivery Options │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md │ ├── 1489. Find Critical and Pseudo-Critical Edges in Min Spanning Tree │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md │ ├── 2141. Maximum Running Time │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md │ ├── 2366. Min Replacements to Sort an Array │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md │ ├── 239. Sliding Window Max │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md │ ├── 332. Reconstruct Itinerary │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md │ ├── 4. Median of Two Sorted Arrays │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md │ ├── 41. First Missing Positive │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md │ ├── 664. Strange Printer │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md │ ├── 68. Test Justification │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md │ ├── 847. Shortest Path Visiting all Nodes │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md │ └── 920. Number of Music Playlists │ │ ├── sol.cpp │ │ ├── sol.java │ │ └── sol.md └── Medium │ ├── 1048. Longest String Chain │ ├── sol.cpp │ ├── sol.java │ └── sol.md │ ├── 1081. Smallest SubSequence of Distinct Characters │ ├── sol.java │ └── sol.md │ ├── 11. Container With Most Water │ ├── README.md │ ├── Solution.cpp │ └── Solution.java │ ├── 142. LinkedList Cycle II │ ├── sol.cpp │ ├── sol.java │ └── sol.md │ ├── 1448. Count Good Nodes in Binary Tree │ ├── README.md │ └── Solution.java │ ├── 153. Find Minimum in Rotated Sorted Array │ ├── sol.cpp │ ├── sol.java │ └── sol.md │ ├── 1584. Min Cost to Connect All Dots │ ├── sol.java │ └── sol.md │ ├── 1631. Path With Minimum Effort │ ├── sol.java │ └── sol.md │ ├── 1647. Min Deletions to Make Char Frequencies Unique │ ├── sol.java │ └── sol.md │ ├── 1658. Minimum Operations to Reduce X to Zero │ ├── sol.cpp │ ├── sol.java │ └── sol.md │ ├── 179. Largest Number │ ├── sol.cpp │ ├── sol.java │ └── sol.md │ ├── 19. Remove nth Node From the End │ ├── sol.cpp │ ├── sol.java │ └── sol.md │ ├── 1996. The Number of Weak Characters in the Game │ ├── README.md │ ├── Solution.cpp │ ├── Solution.java │ └── Solution.py │ ├── 2. Add Two Numbers │ ├── sol.cpp │ ├── sol.java │ └── sol.md │ ├── 200. Number of Islands │ ├── README.md │ ├── Solution.cpp │ └── Solution.java │ ├── 2038. Remove Colored Pieces if │ ├── sol.cpp │ ├── sol.java │ └── sol.md │ ├── 2707. Extra Chars in a String │ ├── sol.java │ └── sol.md │ ├── 287. Find Duplicate Number │ ├── sol.cpp │ ├── sol.java │ └── sol.md │ ├── 316. Remove Duplicate Letters │ ├── sol.java │ └── sol.md │ ├── 34. First and Last Position of Element in an Array │ ├── sol.cpp │ ├── sol.java │ └── sol.md │ ├── 36. Valid Sudoku │ ├── README.md │ └── Solution.java │ ├── 429. N-ary Tree Level Order Traversal │ └── README.md │ ├── 48. Rotate Image │ ├── README.md │ ├── Solution.cpp │ └── Solution.java │ ├── 61. Rotate List │ ├── sol.cpp │ ├── sol.java │ └── sol.md │ ├── 62. Unique Paths │ ├── sol.java │ └── sol.md │ ├── 63. Unique Paths II │ ├── README.md │ └── Solution.java │ ├── 7. Reverse Integer │ ├── sol.cpp │ ├── sol.java │ └── sol.md │ ├── 725. Split List in Parts │ ├── sol.java │ └── sol.md │ ├── 8. String to Integer (atoi) │ └── Solution.js │ ├── 814. Binary Tree Pruning │ └── README.md │ ├── 967. Numbers With Same Consecutive Differences │ ├── README.md │ ├── Solution.cpp │ ├── Solution.java │ └── Solution.py │ ├── 974. Subarray Sums Divisible by K │ ├── README.md │ ├── Solution.cpp │ ├── Solution.java │ └── Solution.py │ └── README.md ├── Other-code ├── Armstrong.cpp ├── Calculator.java ├── EquilibriumPoint.java ├── SizeOfLargest_BST.java ├── addNum.java ├── binaryToDecimalAndViceversa.cpp ├── currency.java ├── gcd.cpp ├── package.java ├── quadratic_equation.cpp ├── test.java └── voting-check.java ├── Question ├── Q3.1.java ├── Q3.2.java ├── Q3.4.java ├── Q3.5.java └── Question_3.3 │ ├── School.class │ ├── School.java │ └── Student.class ├── README.md ├── Solution.java ├── Student-Admission ├── Main │ ├── Main.class │ └── Main.java └── Student │ ├── Student.class │ └── Student.java ├── java-sorthing └── CountingSort.java ├── java-sorting └── SelecgtionSort.java ├── pattern └── HollowDiamond.java └── simple calculator using java with guitar /Calculator-using-Java-and-Javafx/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Calculator-using-Java-and-Javafx/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Assignment5_Calculator 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.xtext.ui.shared.xtextBuilder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.xtext.ui.shared.xtextNature 21 | org.eclipse.jdt.core.javanature 22 | 23 | 24 | 25 | 1728456763206 26 | 27 | 30 28 | 29 | org.eclipse.core.resources.regexFilterMatcher 30 | node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Calculator-using-Java-and-Javafx/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding/=UTF-8 3 | -------------------------------------------------------------------------------- /Calculator-using-Java-and-Javafx/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=18 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=18 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled 11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 12 | org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning 13 | org.eclipse.jdt.core.compiler.release=enabled 14 | org.eclipse.jdt.core.compiler.source=18 15 | -------------------------------------------------------------------------------- /Calculator-using-Java-and-Javafx/build.fxbuild: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /CodeforBanks: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class bankcustomer{ 3 | String name; 4 | int an; 5 | String at; 6 | String status; 7 | int balance; 8 | String ltd; 9 | int am; 10 | int res=0; 11 | void display(String name,int an) 12 | { 13 | System.out.print(name+"\n"+an+"\n"); 14 | } 15 | void withdraw(int balance, String status,int am) 16 | { 17 | if(balance<1000) 18 | { 19 | System.out.print("Transaction Failed.\n"+balance+"\n"); 20 | } 21 | else 22 | { 23 | res=balance-am; 24 | System.out.print("Transaction Success\n"+res+"\n"); 25 | if(res<1000) 26 | { 27 | System.out.print("Alert:Low Balance.\n"); 28 | } 29 | } 30 | String[] arrstr=ltd.split("/"); 31 | int m=Integer.parseInt(arrstr[2]); 32 | if(2023-m>1) 33 | { 34 | status="Passive"; 35 | } 36 | System.out.print(status); 37 | } 38 | public static void main(String args[]) 39 | { 40 | Scanner sc=new Scanner(System.in); 41 | bankcustomer b1=new bankcustomer(); 42 | b1.name=sc.nextLine(); 43 | b1.an=sc.nextInt(); 44 | sc.nextLine(); 45 | b1.at=sc.nextLine(); 46 | b1.status=sc.nextLine(); 47 | b1.balance=sc.nextInt(); 48 | sc.nextLine(); 49 | b1.ltd=sc.nextLine(); 50 | b1.am=sc.nextInt(); 51 | b1.display(b1.name, b1.an); 52 | b1.withdraw(b1.balance,b1.status,b1.am); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Criteria.txt: -------------------------------------------------------------------------------- 1 | All your Java pull requests will be considered but more weightage will be given to solving **issues** given in this repository. 2 | 3 | 1. Your PR/MRs must be within the bounds of Hacktoberfest. 4 | * Your PR/MRs must be created between October 1 and October 31 (in any time zone, UTC-12 thru UTC+14). 5 | * Your PR/MRs must be made to a public, unarchived repository. 6 | 7 | 2. Repos that go against Hacktoberfest’s values will be excluded from qualification and PR/MRs made to those repos won’t count. 8 | 9 | 3. Your PR/MRs must not be spammy. 10 | 11 | 4. Your PR/MRs must be in a repo tagged with the “hacktoberfest” topic, or have the “hacktoberfest-accepted” label. 12 | 13 | 5. Your PR/MRs must not be labeled as “invalid”. 14 | 15 | 6. Your PR/MRs must be merged, have the “hacktoberfest-accepted” label, or have an overall approving review. 16 | 17 | 7. Once your PR/MRs pass all the checks above, it will be accepted for Hacktoberfest after the seven day review period. 18 | 19 | # Make 4 succesful pull/merge requests and win swags. All the best! 20 | -------------------------------------------------------------------------------- /DSA/HareAndTortoise.java: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | int value; 3 | ListNode next; 4 | 5 | ListNode(int value) { 6 | this.value = value; 7 | this.next = null; 8 | } 9 | } 10 | 11 | public class HareAndTortoise { 12 | public static boolean hasCycle(ListNode head) { 13 | if (head == null || head.next == null) { 14 | return false; 15 | } 16 | 17 | ListNode slow = head; // Tortoise (moves 1 step) 18 | ListNode fast = head; // Hare (moves 2 steps) 19 | 20 | while (fast != null && fast.next != null) { 21 | slow = slow.next; // Move tortoise by 1 step 22 | fast = fast.next.next; // Move hare by 2 steps 23 | 24 | if (slow == fast) { // Cycle detected 25 | return true; 26 | } 27 | } 28 | 29 | return false; // No cycle 30 | } 31 | 32 | public static void main(String[] args) { 33 | // Example usage 34 | ListNode head = new ListNode(1); 35 | head.next = new ListNode(2); 36 | head.next.next = new ListNode(3); 37 | head.next.next.next = new ListNode(4); 38 | head.next.next.next.next = head.next; // Creating a cycle 39 | 40 | boolean result = hasCycle(head); 41 | System.out.println("Does the linked list have a cycle? " + result); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /DSA/MajorityElementII.java: -------------------------------------------------------------------------------- 1 | package DSA; 2 | 3 | /*Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. 4 | 5 | Test Case I: 6 | Input: nums = [3,2,3] 7 | Output: [3] 8 | 9 | Test Case II: 10 | Input: nums = [1] 11 | Output: [1] 12 | 13 | Test Case III: 14 | Input: nums = [1,2] 15 | Output: [1,2] */ 16 | 17 | 18 | import java.util.*; 19 | 20 | public class MajorityElementII { 21 | private static List majorityHelper(int[] nums) { 22 | int dec = nums.length / 3; 23 | List res = new ArrayList<>(); 24 | Map map = new HashMap<>(); 25 | for(int num : nums){ 26 | map.put(num, map.getOrDefault(num, 0) + 1); 27 | } 28 | for(int k: map.keySet()){ 29 | if(map.get(k) > dec){ 30 | res.add(k); 31 | } 32 | } 33 | return res; 34 | } 35 | 36 | public static void main(String[] args){ 37 | Scanner sc = new Scanner(System.in); 38 | int n; 39 | System.out.println("Enter the size of the array: "); 40 | n = sc.nextInt(); 41 | int[] nums = new int[n]; 42 | System.out.println("Enter the elements of the array: "); 43 | for(int i = 0; i < n; i++){ 44 | nums[i] = sc.nextInt(); 45 | } 46 | List res = majorityHelper(nums); 47 | System.out.println("List of elements appearing more than " + n/3 + " times is: " + res); 48 | sc.close(); 49 | } 50 | } 51 | 52 | -------------------------------------------------------------------------------- /DSA/MaxSumCircularArray.java: -------------------------------------------------------------------------------- 1 | class MaxSumCirArray { 2 | public static int maxSubarraySumCircular(int[] nums) { 3 | int total=0; 4 | 5 | int maxCheck=nums[0], temp1=0; 6 | int minCheck=nums[0], temp2=0; 7 | 8 | for(int i:nums) { 9 | total+=i; 10 | temp1=Math.max(i,temp1+i); 11 | maxCheck=Math.max(temp1,maxCheck); 12 | temp2=Math.min(i,temp2+i); 13 | minCheck=Math.min(temp2,minCheck); 14 | } 15 | return maxCheck>0 ? Math.max(total-minCheck,maxCheck):maxCheck; 16 | } 17 | 18 | public static void main(String[] args) { 19 | int []nums={1,-2,3,-2}; 20 | int sum=maxSubarraySumCircular(nums); 21 | System.out.println(sum); 22 | } 23 | } -------------------------------------------------------------------------------- /DSA/MethodOverriding.java: -------------------------------------------------------------------------------- 1 | class Bank{ 2 | int getRateOfInterest(){return 0;} 3 | } 4 | 5 | class SBI extends Bank{ 6 | int getRateOfInterest(){return 9;} 7 | } 8 | 9 | class ICICI extends Bank{ 10 | int getRateOfInterest(){return 10;} 11 | } 12 | class AXIS extends Bank{ 13 | int getRateOfInterest(){return 11;} 14 | } 15 | 16 | class MethodOverriding{ 17 | public static void main(String args[]){ 18 | SBI s=new SBI(); 19 | ICICI i=new ICICI(); 20 | AXIS a=new AXIS(); 21 | System.out.println("SBI Rate of Interest: "+s.getRateOfInterest()); 22 | System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest()); 23 | System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest()); 24 | } 25 | } -------------------------------------------------------------------------------- /DSA/Pattern132.java: -------------------------------------------------------------------------------- 1 | package DSA; 2 | 3 | /* 4 | Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j]. 5 | Return true if there is a 132 pattern in nums, otherwise, return false. 6 | 7 | Test Case I: 8 | Input: nums = [1,2,3,4] 9 | Output: false 10 | Explanation: There is no 132 pattern in the sequence. 11 | 12 | Test Case II: 13 | Input: nums = [3,1,4,2] 14 | Output: true 15 | Explanation: There is a 132 pattern in the sequence: [1, 4, 2]. 16 | */ 17 | 18 | import java.util.*; 19 | 20 | public class Pattern132{ 21 | private static boolean find132pattern(int[] nums) { 22 | int n = nums.length; 23 | if (n < 3) 24 | return false; 25 | Deque decreasingStack = new ArrayDeque<>(n); 26 | int maxThirdElement = Integer.MIN_VALUE; 27 | for (int i = n - 1; i >= 0; i--) { 28 | int currentNumber = nums[i]; 29 | if (currentNumber < maxThirdElement) 30 | return true; 31 | while (!decreasingStack.isEmpty() && decreasingStack.peek() < currentNumber) { 32 | maxThirdElement = decreasingStack.pop(); 33 | } 34 | decreasingStack.push(currentNumber); 35 | } 36 | return false; 37 | } 38 | public static void main(String[] args){ 39 | Scanner sc = new Scanner(System.in); 40 | int n; 41 | System.out.println("Enter the size of the array: "); 42 | n = sc.nextInt(); 43 | int[] nums = new int[n]; 44 | System.out.println("Enter the elements of the array: "); 45 | for(int i=0; i= 0; i--) //Suffix Prod 19 | { 20 | ans[i] *= curr; 21 | curr *= nums[i]; 22 | } 23 | return ans; 24 | } 25 | -------------------------------------------------------------------------------- /DSA/SlidingWindowMaximum.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chetannihith/Java-hacktoberfest23/9c654e54fd9cd5ebf518d8bb5098bc2734cd2364/DSA/SlidingWindowMaximum.class -------------------------------------------------------------------------------- /DSA/SlidingWindowMaximum.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Deque; 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | public class SlidingWindowMaximum { 7 | 8 | // Function to find maximum element in every sliding window of size k 9 | public static List maxSlidingWindow(int[] nums, int k) { 10 | List result = new ArrayList<>(); 11 | if (nums == null || nums.length == 0) { 12 | return result; 13 | } 14 | 15 | Deque deque = new LinkedList<>(); 16 | 17 | for (int i = 0; i < nums.length; i++) { 18 | if (!deque.isEmpty() && deque.peekFirst() < i - k + 1) { 19 | deque.pollFirst(); 20 | } 21 | while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) { 22 | deque.pollLast(); 23 | } 24 | deque.offerLast(i); 25 | if (i >= k - 1) { 26 | result.add(nums[deque.peekFirst()]); 27 | } 28 | } 29 | return result; 30 | } 31 | 32 | public static void main(String[] args) { 33 | int[] nums = { 1, 3, -1, -3, 5, 3, 6, 7 }; 34 | int k = 3; 35 | 36 | List result = maxSlidingWindow(nums, k); 37 | System.out.println("Maximum elements in each sliding window of size " + k + ": " + result); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /DSA/TowerOfHanoi.java: -------------------------------------------------------------------------------- 1 | package DSA; 2 | 3 | import java.util.Scanner; 4 | 5 | /* 6 | The tower of Hanoi is a famous puzzle where we have three rods and N disks. 7 | The objective of the puzzle is to move the entire stack to another rod. 8 | You are given the number of discs N. Initially, these discs are in the rod 1. 9 | You need to print all the steps of discs movement so that all the discs reach the 3rd rod. 10 | Note: The discs are arranged such that the top disc is numbered 1 and the bottom-most disc is numbered N. 11 | Also, all the discs have different sizes and a bigger disc cannot be put on the top of a smaller disc. 12 | */ 13 | public class TowerOfHanoi { 14 | int steps = 0; 15 | void TOH(int n, String source, String auxiliary, String destination) { 16 | if (n == 0) { 17 | return; 18 | } 19 | TOH(n - 1, source, destination, auxiliary); // swap auxiliary and destination 20 | System.out.println("Step " + (++steps) + ": Move disc from " + source + " to " + destination); 21 | TOH(n - 1, auxiliary, source, destination); // swap source and auxiliary 22 | } 23 | 24 | public static void main(String[] args) { 25 | Scanner scan = new Scanner(System.in); 26 | TowerOfHanoi toh = new TowerOfHanoi(); 27 | System.out.print("enter no of discs : "); 28 | int n = scan.nextInt(); 29 | scan.nextLine(); 30 | System.out.print("Enter Source : "); 31 | String source = scan.nextLine(); 32 | System.out.print("Enter Auxillary : "); 33 | String auxiliary = scan.nextLine(); 34 | System.out.print("Enter Destination : "); 35 | String destination = scan.nextLine(); 36 | toh.TOH(n, source, auxiliary, destination); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /DSA/TrappingRainWater.java: -------------------------------------------------------------------------------- 1 | package DSA; 2 | 3 | /** 4 | * Trapping Rainwater Problem - https://leetcode.com/problems/trapping-rain-water/ 5 | * Given n non-negative integers representing an elevation map where the width of 6 | * each bar is 1, compute how much water it can trap after raining. 7 | * Time Complexity - O(n) 8 | */ 9 | public class TrappingRainWater { 10 | 11 | public int trap(int[] height) { 12 | 13 | int l[] = new int[height.length]; 14 | int r[] = new int[height.length]; 15 | 16 | l[l.length-1] = height[height.length-1]; 17 | 18 | for(int i=l.length-2;i>=0;i--){ 19 | 20 | l[i] = Math.max(height[i], l[i+1]); 21 | } 22 | 23 | r[0] = height[0]; 24 | 25 | for(int i=1;i adj[]; //Adjacency Lists 10 | 11 | // Constructor 12 | Graph(int v) 13 | { 14 | V = v; 15 | adj = new LinkedList[v]; 16 | for (int i=0; i queue = new LinkedList(); 35 | 36 | // Mark the current node as visited and enqueue it 37 | visited[s]=true; 38 | queue.add(s); 39 | 40 | while (queue.size() != 0) 41 | { 42 | // Dequeue a vertex from queue and print it 43 | s = queue.poll(); 44 | System.out.print(s+" "); 45 | 46 | // Get all adjacent vertices of the dequeued vertex s 47 | // If a adjacent has not been visited, then mark it 48 | // visited and enqueue it 49 | Iterator i = adj[s].listIterator(); 50 | while (i.hasNext()) 51 | { 52 | int n = i.next(); 53 | if (!visited[n]) 54 | { 55 | visited[n] = true; 56 | queue.add(n); 57 | } 58 | } 59 | } 60 | } 61 | 62 | // Driver method to 63 | public static void main(String args[]) 64 | { 65 | Graph g = new Graph(4); 66 | 67 | g.addEdge(0, 1); 68 | g.addEdge(0, 2); 69 | g.addEdge(1, 2); 70 | g.addEdge(2, 0); 71 | g.addEdge(2, 3); 72 | g.addEdge(3, 3); 73 | 74 | System.out.println("Following is Breadth First Traversal "+ 75 | "(starting from vertex 2)"); 76 | 77 | g.BFS(2); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /DSA/dsa-recursion.java: -------------------------------------------------------------------------------- 1 | public class RecursionDemo { 2 | public static void main(String[] args){ 3 | RecursionDemo recursionDemo = new RecursionDemo(); 4 | int n = 5; 5 | System.out.println(Factorial of + n + 6 | + recursionDemo.factorial(n)); 7 | System.out.print(Fibbonacci of + n + ); 8 | for(int i=0;in;i++){ 9 | System.out.print(recursionDemo.fibbonacci(i) + ); 10 | } 11 | } 12 | 13 | private int factorial(int n){ 14 | base case 15 | if(n == 0){ 16 | return 1; 17 | }else{ 18 | return n factorial(n-1); 19 | } 20 | } 21 | 22 | private int fibbonacci(int n){ 23 | if(n ==0){ 24 | return 0; 25 | } 26 | else if(n==1){ 27 | return 1; 28 | } 29 | else { 30 | return (fibbonacci(n-1) + fibbonacci(n-2)); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /DSA/fibonacciSeries.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public interface fabanacciSeries { 4 | public static void main(String[] args) { 5 | Scanner s = new Scanner(System.in); 6 | 7 | int n1 = 0, n2 = 1, n3, i, count = 10; 8 | System.out.print(n1 + " " + n2);// printing 0 and 1 9 | 10 | for (i = 2; i < count; ++i)// loop starts from 2 because 0 and 1 are already printed 11 | { 12 | n3 = n1 + n2; 13 | System.out.print(" " + n3); 14 | n1 = n2; 15 | n2 = n3; 16 | } 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /DSA/kadanesAlgo.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class kadanesAlgo { 4 | 5 | public static int kadanes(int numbers[]){ 6 | int maximumSum = Integer.MIN_VALUE; 7 | int currentSum = 0; 8 | 9 | for(int i = 0; i < numbers.length; i++){ 10 | currentSum = currentSum + numbers[i]; 11 | if(currentSum < 0){ 12 | currentSum = 0; 13 | } 14 | maximumSum = Math.max(currentSum ,maximumSum); 15 | } 16 | return maximumSum; 17 | } 18 | 19 | public static void main(String args[]){ 20 | Scanner sc = new Scanner(System.in); 21 | 22 | int numbers[] = {-2, -3, 4, -1, -2, 1, 5, -3}; 23 | 24 | int maxSum = kadanes(numbers); 25 | System.out.println("Maximum Sum of Sub-Array is : " + maxSum); 26 | 27 | 28 | sc.close(); 29 | } 30 | } 31 | 32 | 33 | -------------------------------------------------------------------------------- /DSA/pattern.java: -------------------------------------------------------------------------------- 1 | //classwork 2 | public class class49 { 3 | public static void main(String args[]){ 4 | for(int i=1;i<=5;i++){ 5 | for(int j=1;j<=i;j++){ 6 | if(i==1||i==j||i==5||j==1){ 7 | System.out.print("*"); 8 | }else{ 9 | System.out.print(" "); 10 | } 11 | }System.out.println(); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /DiagonalSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | //Problem : Calculate Diagonal Sum 4 | 5 | public class DiagonalSum { 6 | public static int calcSum(int matrix[][]) { 7 | int sum = 0; 8 | // primary 9 | for (int i = 0, j = 0; i < matrix.length; i++, j++) { 10 | sum += matrix[i][j]; 11 | } 12 | 13 | // secondary 14 | for (int j = matrix.length - 1, i = 0; j >= 0; j--, i++) { 15 | if (i == j) { 16 | continue; 17 | } 18 | sum += matrix[i][j]; 19 | } 20 | 21 | return sum; 22 | } 23 | 24 | public static void main(String args[]) { 25 | int matrix[][] = { { 1, 2, 3, 4 }, 26 | { 5, 6, 7, 8 }, 27 | { 9, 10, 11, 12 }, 28 | { 13, 14, 15, 16 } }; 29 | calcSum(matrix); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Java-Algorithm/Anagrammanipulatorr.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Anagrammanipulatorr { 4 | 5 | public static boolean areAnagrams(String str1, String str2) { 6 | // Remove spaces,convert both strings to lowercase comparison 7 | str1 = str1.replaceAll("\\s", "").toLowerCase(); 8 | str2 = str2.replaceAll("\\s", "").toLowerCase(); 9 | 10 | // Check if lengths of two strings are different 11 | if (str1.length() != str2.length()) { 12 | return false; 13 | } 14 | 15 | // Convertstrings to char arrays and sort 16 | char[] charArray1 = str1.toCharArray(); 17 | char[] charArray2 = str2.toCharArray(); 18 | 19 | Arrays.sort(charArray1); 20 | Arrays.sort(charArray2); 21 | 22 | // Compare sorted arrays 23 | return Arrays.equals(charArray1, charArray2); 24 | } 25 | 26 | public static void main(String[] args) { 27 | String str1 = "abcd"; 28 | String str2 = "dabc"; 29 | 30 | if (areAnagrams(str1, str2)) { 31 | System.out.println(str1 + " and " + str2 + " are anagrams."); 32 | } else { 33 | System.out.println(str1 + " and " + str2 + " are not anagrams."); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Java-Algorithm/ArrangingCoin.java: -------------------------------------------------------------------------------- 1 | // You have n coins and you want to build a staircase with these coins. 2 | // The staircase consists of k rows where the ith row has exactly i coins. 3 | // The last row of the staircase may be incomplete. 4 | 5 | // Given the integer n, return the number of complete rows of the staircase you will build. 6 | 7 | // Example 1: 8 | 9 | // Input: n = 5 10 | // Output: 2 11 | // Explanation: Because the 3rd row is incomplete, we return 2. 12 | 13 | // Example 2: 14 | 15 | // Input: n = 8 16 | // Output: 3 17 | // Explanation: Because the 4th row is incomplete, we return 3. 18 | 19 | // problem: [link](https://leetcode.com/problems/arranging-coins/) 20 | 21 | 22 | /* first of all we will accept the no of coins from the users. 23 | Then we will pass into the arrangeCoins functions. 24 | We have to build a stair like the top most stair should only have one coin 25 | and the bottom most stair should have n coins. 26 | so first we will delete one coin from the user entered coins and we will build the first stair. 27 | for the second stair we will delete two coins and increase the stair no to two. 28 | we will continue like this till the user has less no of coins than no of stair required to build. 29 | */ 30 | import java.util.Scanner; 31 | 32 | class ArrangingCoin { 33 | 34 | public static void main(String[] args) { 35 | Scanner sn=new Scanner(System.in); 36 | System.out.println("Please enter the number of coins"); 37 | int n=sn.nextInt(); 38 | int ans= arrangeCoins(n); 39 | System.out.println("The stair obtained by arraning coins is :"+ ans); 40 | } 41 | 42 | public static int arrangeCoins(int n) 43 | { 44 | int stair=0; 45 | int count=1; 46 | while(n>=count) 47 | { 48 | n=n-count; 49 | stair++; 50 | count++; 51 | } 52 | return stair; 53 | 54 | } 55 | } 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /Java-Algorithm/Depth_First_Search.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> levelOrder(TreeNode root) { 3 | //using queues to implement bfs like pattern 4 | Queue q = new LinkedList<>(); 5 | List> res = new ArrayList<>(); 6 | if(root == null)return res; 7 | //add the root node to our q 8 | q.add(root); 9 | while(!q.isEmpty()){ 10 | //the size of the queue is all the nodes at that level 11 | int level = q.size(); 12 | List in = new ArrayList<>(); 13 | //we will go though all the levels of the tree and check the left and right of each node 14 | for(int i = 0; i 5 | */ 6 | public class KadaneAlgorithm 7 | { 8 | public static void main(String[] args) 9 | { 10 | Scanner sc=new Scanner(System.in); 11 | System.out.print("Enter the length of the array : "); 12 | int ar[]=new int[sc.nextInt()]; 13 | for(int i = 0; i < ar.length; i++) 14 | { 15 | System.out.print("Enter element "+(i+1)+" : "); 16 | ar[i]=sc.nextInt(); 17 | } 18 | int sum = ar[0],sumAlt = 0; 19 | for(int i = 1; i < ar.length; i++) 20 | { 21 | if(ar[i] > 0) 22 | { 23 | sum += ar[i]; 24 | continue; 25 | } 26 | else 27 | { 28 | for (int j = i+1; j < ar.length; j++) 29 | { 30 | sumAlt += ar[j]; 31 | } 32 | } 33 | if(sumAlt > -(ar[i])) 34 | { 35 | sum += sumAlt; 36 | } 37 | break; 38 | } 39 | System.out.println("Max subarray sum is "+sum); 40 | sc.close(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Java-Algorithm/Longest common prefix.java: -------------------------------------------------------------------------------- 1 | // Lexicographically sort Strings, check frst & last string 2 | public String longestCommonPrefix(String[] v) 3 | { 4 | StringBuilder ans = new StringBuilder(); 5 | Arrays.sort(v); 6 | String first = v[0]; 7 | String last = v[v.length-1]; 8 | for (int i=0; i0){ 8 | r=n%10; //getting remainder 9 | sum=(sum*10)+r; 10 | n=n/10; 11 | } 12 | if(temp==sum) 13 | System.out.println("palindrome number "); 14 | else 15 | System.out.println("not palindrome"); 16 | } 17 | } -------------------------------------------------------------------------------- /Java-Algorithm/PasswordGenerator.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | class PasswordGenerator { 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | 8 | String upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 9 | String lowerCase = upperCase.toLowerCase(); 10 | String numbers = "0123456789"; 11 | String specialCharacters = "/<>,.|!@#$%^&*"; 12 | String combinedChar = upperCase+lowerCase+numbers+specialCharacters; 13 | 14 | System.out.println("Reading the length of the password : "); 15 | int length = sc.nextInt(); 16 | char[] password = new char[length]; 17 | 18 | Random r = new Random(); 19 | 20 | for (int i=0; i> adj; 6 | 7 | public Graph(int vertices) { 8 | V = vertices; 9 | adj = new ArrayList<>(V); 10 | for (int i = 0; i < V; i++) { 11 | adj.add(new LinkedList<>()); 12 | } 13 | } 14 | 15 | public void addEdge(int v, int w) { 16 | adj.get(v).add(w); 17 | } 18 | 19 | private void topologicalSortUtil(int v, boolean[] visited, Stack stack) { 20 | visited[v] = true; 21 | for (Integer neighbor : adj.get(v)) { 22 | if (!visited[neighbor]) { 23 | topologicalSortUtil(neighbor, visited, stack); 24 | } 25 | } 26 | stack.push(v); 27 | } 28 | 29 | public void topologicalSort() { 30 | Stack stack = new Stack<>(); 31 | boolean[] visited = new boolean[V]; 32 | 33 | for (int i = 0; i < V; i++) { 34 | if (!visited[i]) { 35 | topologicalSortUtil(i, visited, stack); 36 | } 37 | } 38 | 39 | while (!stack.isEmpty()) { 40 | System.out.print(stack.pop() + " "); 41 | } 42 | } 43 | } 44 | 45 | public class TopologicalSort { 46 | public static void main(String[] args) { 47 | Graph g = new Graph(6); 48 | g.addEdge(5, 2); 49 | g.addEdge(5, 0); 50 | g.addEdge(4, 0); 51 | g.addEdge(4, 1); 52 | g.addEdge(2, 3); 53 | g.addEdge(3, 1); 54 | 55 | System.out.println("Topological Sort:"); 56 | g.topologicalSort(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Java-Algorithm/UniqueFloydAlgorithmpo.java: -------------------------------------------------------------------------------- 1 | 2 | public class UniqueFloydAlgorithm { 3 | 4 | public static void main(String[] args) { 5 | ListNode head = new ListNode(3); 6 | head.next = new ListNode(2); 7 | head.next.next = new ListNode(0); 8 | head.next.next.next = new ListNode(-4); 9 | // Create cycle 10 | head.next.next.next.next = head.next; 11 | boolean hasCycle = hasCycle(head); 12 | if (hasCycle) { 13 | System.out.println("The linked list has a cycle."); 14 | } else { 15 | System.out.println("The linked list does not have a cycle."); 16 | } 17 | } 18 | 19 | public static boolean hasCycle(ListNode head) { 20 | if (head == null || head.next == null) { 21 | return false; 22 | } 23 | ListNode slow = head; 24 | ListNode fast = head.next; 25 | while (slow != fast) { 26 | if (fast == null || fast.next == null) { 27 | return false; 28 | } 29 | slow = slow.next; 30 | fast = fast.next.next; 31 | } 32 | return true; 33 | } 34 | } 35 | class ListNode { 36 | int val; 37 | ListNode next; 38 | 39 | ListNode(int x) { 40 | val = x; 41 | next = null; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Java-Area/Area-of-circle.java: -------------------------------------------------------------------------------- 1 | package mypack; // Package declaration 2 | 3 | public class Circle { 4 | private double radius; 5 | 6 | public Circle(double radius) { 7 | this.radius = radius; 8 | } 9 | 10 | public double getArea() { 11 | return Math.PI * radius * radius; //Area of circle calculation 12 | } 13 | } 14 | 15 | public class Main { 16 | public static void main(String[] args) { 17 | Circle circle = new Circle(5.0); // Creating an instance of Circle 18 | System.out.println("Circle Area: " + circle.getArea()); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Java-Area/PrintAreaOfShape.java: -------------------------------------------------------------------------------- 1 | package hacktoberfest; 2 | import java.util.Scanner; 3 | 4 | public class PrintAreaOfShape { 5 | 6 | // Method to print the area of a square 7 | public static void printAreaOfSquare(double side) { 8 | double area = side * side; //Area of square calculation 9 | System.out.println("Area of square of side " + side + " units is = " + area + " sq. units."); 10 | } 11 | 12 | // Method to print the area of a rectangle 13 | public static void printAreaOfRectangle(double length, double breadth) { 14 | double area = length * breadth; //Area of rectangle calculation 15 | System.out.println("Area of rectangle of length " + length + " units and breadth " 16 | + breadth + " units is = " + area + " sq. units."); 17 | } 18 | 19 | // Driver code 20 | public static void main(String[] args) { 21 | Scanner sc = new Scanner(System.in); 22 | 23 | // User input for side of square 24 | System.out.print("Enter the side of the square = "); 25 | double sqSide = sc.nextDouble(); 26 | printAreaOfSquare(sqSide); 27 | System.out.println(); 28 | 29 | // User input for length and breadth of rectangle 30 | System.out.print("Enter the length of the rectangle = "); 31 | double rectLength = sc.nextDouble(); 32 | System.out.print("Enter the breadth of the rectangle = "); 33 | double rectBreadth = sc.nextDouble(); 34 | printAreaOfRectangle(rectLength, rectBreadth); 35 | 36 | // close the scanner 37 | sc.close(); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Java-OOPS/Inheritance/Inheritance-Examples/HybridInheritanceExample.java: -------------------------------------------------------------------------------- 1 | 2 | class Person { 3 | String name; 4 | 5 | Person(String name) { 6 | this.name = name; 7 | } 8 | 9 | void introduce() { 10 | System.out.println("My name is " + name); 11 | } 12 | } 13 | 14 | interface Employee { 15 | void work(); 16 | } 17 | 18 | class Teacher extends Person implements Employee { 19 | Teacher(String name) { 20 | super(name); 21 | } 22 | 23 | public void work() { 24 | System.out.println(name + " is teaching."); 25 | } 26 | } 27 | 28 | class Student extends Person { 29 | Student(String name) { 30 | super(name); 31 | } 32 | 33 | void study() { 34 | System.out.println(name + " is studying."); 35 | } 36 | } 37 | 38 | class AdministrativeStaff extends Person implements Employee { 39 | AdministrativeStaff(String name) { 40 | super(name); 41 | } 42 | 43 | public void work() { 44 | System.out.println(name + " is managing administrative tasks."); 45 | } 46 | } 47 | 48 | 49 | public class HybridInheritanceExample { 50 | public static void main(String[] args) { 51 | Teacher teacher = new Teacher("Mr. Smith"); 52 | Student student = new Student("Alice"); 53 | AdministrativeStaff staff = new AdministrativeStaff("John Doe"); 54 | 55 | teacher.introduce(); // Inherited from Person 56 | teacher.work(); // Defined in Teacher 57 | 58 | student.introduce(); // Inherited from Person 59 | student.study(); // Defined in Student 60 | 61 | staff.introduce(); // Inherited from Person 62 | staff.work(); // Defined in AdministrativeStaff 63 | } 64 | } -------------------------------------------------------------------------------- /Java-OOPS/Inheritance/Inheritance-Examples/InheritanceExample.java: -------------------------------------------------------------------------------- 1 | 2 | class Vehicle { 3 | String brand; 4 | 5 | Vehicle(String brand) { 6 | this.brand = brand; 7 | } 8 | 9 | void start() { 10 | System.out.println(brand + " is starting."); 11 | } 12 | 13 | void stop() { 14 | System.out.println(brand + " is stopping."); 15 | } 16 | } 17 | 18 | class Car extends Vehicle { 19 | Car(String brand) { 20 | super(brand); 21 | } 22 | 23 | void drive() { 24 | System.out.println(brand + " is driving."); 25 | } 26 | } 27 | 28 | public class InheritanceExample { 29 | public static void main(String[] args) { 30 | Car myCar = new Car("Toyota"); 31 | myCar.start(); // Inherited from Vehicle 32 | myCar.drive(); // Defined in Car 33 | myCar.stop(); // Inherited from Vehicle 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Java-OOPS/Inheritance/Inheritance-Examples/MultilevelInheritanceExample.java: -------------------------------------------------------------------------------- 1 | 2 | class Grandparent { 3 | void familyName() { 4 | System.out.println("Family name is Smith."); 5 | } 6 | } 7 | 8 | class Parent extends Grandparent { 9 | void parentName() { 10 | System.out.println("Parent's name is John."); 11 | } 12 | } 13 | 14 | class Child extends Parent { 15 | void childName() { 16 | System.out.println("Child's name is Alice."); 17 | } 18 | } 19 | 20 | 21 | public class MultilevelInheritanceExample { 22 | public static void main(String[] args) { 23 | Child alice = new Child(); 24 | alice.familyName(); // Inherited from Grandparent 25 | alice.parentName(); // Inherited from Parent 26 | alice.childName(); // Defined in Child 27 | } 28 | } -------------------------------------------------------------------------------- /Java-OOPS/Inheritance/Inheritance-Examples/MultipleInheritanceExample.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | interface Writer { 4 | void write(); 5 | } 6 | 7 | interface Speaker { 8 | void speak(); 9 | } 10 | 11 | class Author implements Writer, Speaker { 12 | public void write() { 13 | System.out.println("Author is writing a book."); 14 | } 15 | 16 | public void speak() { 17 | System.out.println("Author is giving a speech."); 18 | } 19 | } 20 | 21 | public class MultipleInheritanceExample { 22 | public static void main(String[] args) { 23 | Author author = new Author(); 24 | author.write(); // Defined in Writer 25 | author.speak(); // Defined in Speaker 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Java-OOPS/Inheritance/Inheritance-Examples/SingleInheritanceExample.java: -------------------------------------------------------------------------------- 1 | class Animal { 2 | String species; 3 | 4 | Animal(String species) { 5 | this.species = species; 6 | } 7 | 8 | void eat() { 9 | System.out.println(species + " is eating."); 10 | } 11 | } 12 | 13 | class Dog extends Animal { 14 | Dog(String species) { 15 | super(species); // Call the superclass constructor 16 | } 17 | 18 | void bark() { 19 | System.out.println(species + " is barking."); 20 | } 21 | } 22 | 23 | public class SingleInheritanceExample { 24 | public static void main(String[] args) { 25 | Dog myDog = new Dog("Tom"); 26 | myDog.eat(); // Inherited from Animal 27 | myDog.bark(); // Defined in Dog 28 | } 29 | } -------------------------------------------------------------------------------- /Java-OOPS/Inheritance/diagrams/inheritance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chetannihith/Java-hacktoberfest23/9c654e54fd9cd5ebf518d8bb5098bc2734cd2364/Java-OOPS/Inheritance/diagrams/inheritance.png -------------------------------------------------------------------------------- /Java-searching/BinarySearch.java: -------------------------------------------------------------------------------- 1 | import java.util.* ; 2 | class BinarySearch 3 | { 4 | public static void main(String args[]) 5 | { 6 | int counter, num, item, array[], first, last, middle; 7 | 8 | Scanner input = new Scanner(System.in); 9 | System.out.println("Enter number of elements:"); 10 | num = input.nextInt(); 11 | 12 | 13 | array = new int[num]; 14 | 15 | System.out.println("Enter " + num + " integers"); 16 | 17 | for (counter = 0; counter < num; counter++) 18 | array[counter] = input.nextInt(); 19 | 20 | System.out.println("Enter the search value:"); 21 | item = input.nextInt(); 22 | first = 0; 23 | last = num - 1; 24 | middle = (first + last)/2; 25 | 26 | while( first <= last ) 27 | { 28 | if ( array[middle] < item ) 29 | first = middle + 1; 30 | else if ( array[middle] == item ) 31 | { 32 | System.out.println(item + " found at location " + (middle + 1) + "."); 33 | break; 34 | } 35 | else 36 | { 37 | last = middle - 1; 38 | } 39 | middle = (first + last)/2; 40 | } 41 | if ( first > last ) 42 | System.out.println(item + " is not found.\n"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Java-searching/LinearSearch.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class LinearSearch 3 | { 4 | public static void main(String args[]) 5 | { 6 | int counter, num, item, array[]; 7 | 8 | Scanner input = new Scanner(System.in); 9 | System.out.println("Enter number of elements:"); 10 | num = input.nextInt(); 11 | 12 | array = new int[num]; 13 | System.out.println("Enter " + num + " integers"); 14 | 15 | for (counter = 0; counter < num; counter++) 16 | array[counter] = input.nextInt(); 17 | 18 | System.out.println("Enter the search value:"); 19 | item = input.nextInt(); 20 | 21 | for (counter = 0; counter < num; counter++) 22 | { 23 | if (array[counter] == item) 24 | { 25 | System.out.println(item+" is present at location "+(counter+1)); 26 | 27 | break; 28 | } 29 | } 30 | if (counter == num) 31 | System.out.println(item + " doesn't exist in array."); 32 | } 33 | } -------------------------------------------------------------------------------- /Java-searching/binarySearch.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chetannihith/Java-hacktoberfest23/9c654e54fd9cd5ebf518d8bb5098bc2734cd2364/Java-searching/binarySearch.class -------------------------------------------------------------------------------- /Java-sorting/InsertSortTest.java: -------------------------------------------------------------------------------- 1 | package com.test; 2 | 3 | import java.util.Scanner; 4 | 5 | public class InsertSortTest { 6 | final static int MaxNumbers = 10; 7 | 8 | public static void main(String[] args) { 9 | Scanner in = new Scanner(System.in); 10 | int[] num = new int[MaxNumbers]; 11 | System.out.printf("Type up to %d numbers followed by 0\n", MaxNumbers); 12 | int n = 0; 13 | int v = in.nextInt(); 14 | while (v != 0 && n < MaxNumbers) { 15 | num[n++] = v; 16 | v = in.nextInt(); 17 | } 18 | if (v != 0) { 19 | System.out.printf("\nMore than %d numbers entered\n", MaxNumbers); 20 | System.out.printf("First %d used\n", MaxNumbers); 21 | } 22 | if (n == 0) { 23 | System.out.printf("\nNo numbers supplied\n"); 24 | System.exit(1); 25 | } 26 | // n numbers are stored from num[0] to num[n-1] 27 | insertionSort(num, n); 28 | System.out.printf("\nThe sorted numbers are\n"); 29 | for (v = 0; v < n; v++) 30 | System.out.printf("%d ", num[v]); 31 | System.out.printf("\n"); 32 | } // end main 33 | 34 | public static void insertionSort(int list[], int n) { 35 | // sort list[0] to list[n-1] in ascending order 36 | for (int h = 1; h < n; h++) { 37 | int key = list[h]; 38 | int k = h - 1; // start comparing with previous item 39 | while (k >= 0 && key < list[k]) { 40 | list[k + 1] = list[k]; 41 | --k; 42 | } 43 | list[k + 1] = key; 44 | } // end for 45 | } // end insertionSort 46 | } // end class InsertSortTest 47 | -------------------------------------------------------------------------------- /Java-sorting/ShellSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class ShellSort { 4 | 5 | void shellSort(int array[], int n) { 6 | for (int interval = n / 2; interval > 0; interval /= 2) { 7 | for (int i = interval; i < n; i += 1) { 8 | int temp = array[i]; 9 | int j; 10 | for (j = i; j >= interval && array[j - interval] > temp; j -= interval) { 11 | array[j] = array[j - interval]; 12 | } 13 | array[j] = temp; 14 | } 15 | } 16 | } 17 | 18 | public static void main(String args[]) { 19 | int[] data = { 9, 8, 3, 7, 5, 6, 4, 1 }; 20 | int size = data.length; 21 | ShellSort ss = new ShellSort(); 22 | ss.shellSort(data, size); 23 | System.out.println("Sorted Array in Ascending Order: "); 24 | System.out.println(Arrays.toString(data)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Java-sorting/bubble_sort.java: -------------------------------------------------------------------------------- 1 | public class BubbleSort { 2 | public static void main(String[] args) { 3 | int[] arr = {64, 34, 25, 12, 22, 11, 90}; 4 | bubbleSort(arr); 5 | System.out.println("Sorted array:"); 6 | for (int num : arr) { 7 | System.out.print(num + " "); 8 | } 9 | } 10 | 11 | public static void bubbleSort(int[] arr) { 12 | int n = arr.length; 13 | boolean swapped; 14 | for (int i = 0; i < n - 1; i++) { 15 | swapped = false; 16 | for (int j = 0; j < n - i - 1; j++) { 17 | if (arr[j] > arr[j + 1]) { 18 | // Swap arr[j] and arr[j+1] 19 | int temp = arr[j]; 20 | arr[j] = arr[j + 1]; 21 | arr[j + 1] = temp; 22 | swapped = true; 23 | } 24 | } 25 | // If no two elements were swapped in inner loop, the array is already sorted 26 | if (!swapped) { 27 | break; 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Java-sorting/quick_sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ Implementation of the Quick Sort Algorithm. 2 | #include 3 | using namespace std; 4 | 5 | int partition(int arr[], int start, int end) 6 | { 7 | 8 | int pivot = arr[start]; 9 | 10 | int count = 0; 11 | for (int i = start + 1; i <= end; i++) { 12 | if (arr[i] <= pivot) 13 | count++; 14 | } 15 | 16 | // Giving pivot element its correct position 17 | int pivotIndex = start + count; 18 | swap(arr[pivotIndex], arr[start]); 19 | 20 | // Sorting left and right parts of the pivot element 21 | int i = start, j = end; 22 | 23 | while (i < pivotIndex && j > pivotIndex) { 24 | 25 | while (arr[i] <= pivot) { 26 | i++; 27 | } 28 | 29 | while (arr[j] > pivot) { 30 | j--; 31 | } 32 | 33 | if (i < pivotIndex && j > pivotIndex) { 34 | swap(arr[i++], arr[j--]); 35 | } 36 | } 37 | 38 | return pivotIndex; 39 | } 40 | 41 | void quickSort(int arr[], int start, int end) 42 | { 43 | 44 | // base case 45 | if (start >= end) 46 | return; 47 | 48 | // partitioning the array 49 | int p = partition(arr, start, end); 50 | 51 | // Sorting the left part 52 | quickSort(arr, start, p - 1); 53 | 54 | // Sorting the right part 55 | quickSort(arr, p + 1, end); 56 | } 57 | 58 | int main() 59 | { 60 | 61 | int arr[] = { 9, 8, 4, 2, 1, 3 }; 62 | int n = 6; 63 | 64 | quickSort(arr, 0, n - 1); 65 | 66 | for (int i = 0; i < n; i++) { 67 | cout << arr[i] << " "; 68 | } 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /Java-sorting/tree_sort.java: -------------------------------------------------------------------------------- 1 | 2 | class TreeSort 3 | { 4 | 5 | class Node 6 | { 7 | int key; 8 | Node left, right; 9 | 10 | public Node(int item) 11 | { 12 | key = item; 13 | left = right = null; 14 | } 15 | } 16 | 17 | // Root of BST 18 | Node root; 19 | 20 | // Constructor 21 | G() 22 | { 23 | root = null; 24 | } 25 | 26 | void insert(int key) 27 | { 28 | root = insertRec(root, key); 29 | } 30 | 31 | Node insertRec(Node root, int key) 32 | { 33 | 34 | if (root == null) 35 | { 36 | root = new Node(key); 37 | return root; 38 | } 39 | 40 | 41 | if (key < root.key) 42 | root.left = insertRec(root.left, key); 43 | else if (key > root.key) 44 | root.right = insertRec(root.right, key); 45 | 46 | return root; 47 | } 48 | 49 | 50 | void inorderRec(Node root) 51 | { 52 | if (root != null) 53 | { 54 | inorderRec(root.left); 55 | System.out.print(root.key + " "); 56 | inorderRec(root.right); 57 | } 58 | } 59 | void treeins(int arr[]) 60 | { 61 | for(int i = 0; i < arr.length; i++) 62 | { 63 | insert(arr[i]); 64 | } 65 | 66 | } 67 | 68 | public static void main(String[] args) 69 | { 70 | G tree = new G(); 71 | int arr[] = {5, 4, 7, 2, 11}; 72 | tree.treeins(arr); 73 | tree.inorderRec(tree.root); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/108. Convert Sorted Array to Binary Search Tree/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* createBST(vector nums, int s, int e) { 4 | if (s > e) return NULL; 5 | 6 | int mid = s + (e - s) / 2; 7 | 8 | TreeNode* root = new TreeNode(nums[mid]); 9 | root->left = createBST(nums, s, mid - 1); 10 | root->right = createBST(nums, mid + 1, e); 11 | return root; 12 | } 13 | 14 | TreeNode* sortedArrayToBST(vector& nums) { 15 | int s = 0; 16 | int e = nums.size() - 1; 17 | return createBST(nums, s, e); 18 | } 19 | }; -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/108. Convert Sorted Array to Binary Search Tree/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | public TreeNode sortedArrayToBST(int[] num) { 18 | if (num.length == 0) { 19 | return null; 20 | } 21 | TreeNode head = helper(num, 0, num.length - 1); 22 | return head; 23 | } 24 | 25 | public TreeNode helper(int[] num, int low, int high) { 26 | if (low > high) { 27 | return null; 28 | } 29 | int mid = low + (high-low)/2; 30 | TreeNode node = new TreeNode(num[mid]); 31 | node.left = helper(num, low, mid - 1); 32 | node.right = helper(num, mid + 1, high); 33 | return node; 34 | } 35 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/1337. K Weakest Rows in a Matrix/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector kWeakestRows(vector>& mat, int k) { 10 | 11 | priority_queue, vector>, greater>> minHeap; 12 | 13 | for(int row=0; row k) 26 | minHeap.pop(); 27 | } 28 | 29 | vector result; 30 | 31 | while(!minHeap.empty()) { 32 | result.push_back(minHeap.top().second); 33 | minHeap.pop(); 34 | } 35 | 36 | return result; 37 | } 38 | }; 39 | 40 | int main() { 41 | //in this we see the sol through an example and call the fn here itself 42 | vector> mat {{1,1,0,0,0}, 43 | {1,1,1,1,0}, 44 | {1,0,0,0,0}, 45 | {1,1,0,0,0}, 46 | {1,1,1,1,1}}; 47 | 48 | int k = 3; 49 | 50 | Solution sol; 51 | vector weakestRows = sol.kWeakestRows(mat, k); 52 | 53 | for(int row : weakestRows) 54 | cout << row << " "; 55 | 56 | return 0; 57 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/1337. K Weakest Rows in a Matrix/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class sol { 4 | public static void main(String[] args) { 5 | // call your fn here 6 | } 7 | } 8 | 9 | class Solution { 10 | public int[] kWeakestRows(int[][] matrix, int k) { 11 | PriorityQueue soldierSums = new PriorityQueue<>((a, b) -> { 12 | if (a[0] != b[0]) { 13 | return Integer.compare(a[0], b[0]); 14 | } else { 15 | return Integer.compare(a[1], b[1]); 16 | } 17 | }); 18 | 19 | for (int row = 0; row < matrix.length; row++) { 20 | int soldierCount = 0; 21 | for (int col = 0; col < matrix[row].length; col++) { 22 | soldierCount += matrix[row][col]; 23 | if (matrix[row][col] == 0) { 24 | break; 25 | } 26 | } 27 | soldierSums.offer(new int[] { soldierCount, row }); 28 | } 29 | 30 | int[] weakestRows = new int[k]; 31 | for (int i = 0; i < k; i++) { 32 | weakestRows[i] = soldierSums.poll()[1]; 33 | } 34 | 35 | return weakestRows; 36 | } 37 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/1337. K Weakest Rows in a Matrix/sol.md: -------------------------------------------------------------------------------- 1 | **Algorithm:** 2 | 3 | 1. Create a priority queue to store the sum of soldiers in each row. 4 | 2. Iterate over the matrix and for each row, calculate the sum of soldiers. 5 | 3. Add the row number and the sum of soldiers to the priority queue. 6 | 4. Create an array to store the weakest rows. 7 | 5. Iterate over the priority queue and add the row number of the weakest row to the array. 8 | 6. Return the array of weakest rows. 9 | 10 | **Time complexity:** O(n log n), where n is the number of rows in the matrix. This is because we need to sort the priority queue, which takes O(log n) time per operation. 11 | 12 | **Space complexity:** O(n), where n is the number of rows in the matrix. This is because we need to store the priority queue, which can hold up to n rows. 13 | 14 | For example, consider the following matrix: 15 | 16 | [[1, 1, 1, 1, 1], 17 | [1, 1, 1, 1, 0], 18 | [1, 1, 1, 0, 0], 19 | [1, 1, 0, 0, 0], 20 | [1, 0, 0, 0, 0]] 21 | 22 | 23 | The priority queue will be initialized as follows: 24 | 25 | [1, 5] 26 | [1, 4] 27 | [1, 3] 28 | [1, 2] 29 | [1, 1] 30 | 31 | The function will then return the following array: 32 | 33 | 34 | [0, 1, 2, 3, 4] 35 | 36 | 37 | This is because the first row has the most soldiers, followed by the second row, and so on. 38 | -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/141. Linked List Cycle/explanantion.md: -------------------------------------------------------------------------------- 1 | **Algorithm:** 2 | 3 | 1. Initialize two pointers, `slow` and `fast`, to the head of the linked list. 4 | 2. Iterate while `fast` is not null and `fast.next` is not null. 5 | 3. Move `slow` one node forward. 6 | 4. Move `fast` two nodes forward. 7 | 5. If `slow` and `fast` ever meet, then there is a cycle in the linked list. 8 | 6. Return `true` if there is a cycle, or `false` otherwise. 9 | 10 | **Time complexity:** O(n), where n is the length of the linked list. 11 | 12 | **Space complexity:** O(1), as we only use two pointers. 13 | 14 | **Explanation:** 15 | 16 | The `hasCycle()` function works by using two pointers, `slow` and `fast`, to traverse the linked list. The `slow` pointer moves one node forward at a time, while the `fast` pointer moves two nodes forward at a time. If there is a cycle in the linked list, then the `slow` and `fast` pointers will eventually meet at some point. This is because the `fast` pointer will eventually catch up to the `slow` pointer. 17 | 18 | For example, consider the following linked list: 19 | 20 | head -> 1 -> 2 -> 3 -> 4 -> 3 (4 points back to 3) 21 | 22 | There is a cycle in this linked list because the `next` pointer of the node with the value `4` points back to the node with the value `3`. 23 | 24 | If we call the `hasCycle()` function on this linked list, the `slow` and `fast` pointers will eventually meet at the node with the value `3`. This is because the `fast` pointer will eventually catch up to the `slow` pointer. 25 | 26 | Therefore, the `hasCycle()` function returns `true` in this case. -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/141. Linked List Cycle/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct ListNode { 5 | int val; 6 | ListNode *next; 7 | ListNode(int x) : val(x), next(NULL) {} 8 | }; 9 | 10 | class Solution { 11 | public: 12 | bool hasCycle(ListNode *head) { 13 | 14 | ListNode *slow = head; 15 | ListNode *fast = head; 16 | 17 | while (fast != NULL && fast->next != NULL) { 18 | slow = slow->next; 19 | fast = fast->next->next; 20 | 21 | if (fast == slow) { 22 | return true; 23 | } 24 | } 25 | 26 | return false; 27 | } 28 | }; 29 | 30 | int main() { 31 | // test Solution::hasCycle 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/141. Linked List Cycle/sol.java: -------------------------------------------------------------------------------- 1 | 2 | class ListNode { 3 | int val; 4 | ListNode next; 5 | 6 | ListNode(int x) { 7 | val = x; 8 | next = null; 9 | } 10 | } 11 | 12 | public class sol { 13 | public static void main(String[] args) { 14 | // call your fn here 15 | } 16 | } 17 | 18 | class Solution { 19 | public boolean hasCycle(ListNode head) { 20 | 21 | ListNode slow = head; 22 | ListNode fast = head; 23 | 24 | while (fast != null && fast.next != null) { 25 | slow = slow.next; 26 | fast = fast.next.next; 27 | 28 | if (fast == slow) { 29 | return true; 30 | } 31 | } 32 | return false; 33 | } 34 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/1512. Number of Good Pairs/NoOfGP.java: -------------------------------------------------------------------------------- 1 | public class NoOfGP{ 2 | public static void main(String[] args) { 3 | 4 | } 5 | 6 | class Solution { 7 | public int numIdenticalPairs(int[] nums) { 8 | int ans = 0; 9 | int count[] = new int[101]; 10 | 11 | for(int n:nums) 12 | { 13 | count[n]++; 14 | } 15 | for(int n:count) 16 | { 17 | ans+=(n*(n-1))/2; 18 | } 19 | return ans; 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/1512. Number of Good Pairs/explanation.md.txt: -------------------------------------------------------------------------------- 1 | Algorithm: 2 | 3 | 1)Use a count array to store the frequency of each number in the input array. 4 | 2)Iterate through the count array. 5 | 3)For each frequency n, calculate the number of identical pairs as n*(n-1)/2. 6 | 4)Keep adding this to the answer. 7 | 5)Return the answer. 8 | 9 | The reason we can calculate the number of identical pairs as n*(n-1)/2 is because we are counting each pair twice. For example, if we have two identical numbers, we can count them as a pair once for each index. But this means that we have counted them twice, so we need to divide by 2 to get the correct number of pairs. 10 | 11 | Time complexity: O(n) where n is the length of the input array. We traverse the input array only once to populate the count array. Then we traverse the count array which has size 101. So the overall time complexity is O(n). 12 | 13 | Space complexity: O(1) as we use a constant size count array. -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/1512. Number of Good Pairs/sol.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numIdenticalPairs(std::vector& nums) { 4 | int ans = 0; 5 | std::vector count(101, 0); 6 | 7 | for (int n : nums) { 8 | count[n]++; 9 | } 10 | 11 | for (int n : count) { 12 | ans += (n * (n - 1)) / 2; 13 | } 14 | 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/389. Find the Difference/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | char findTheDifference(string s, string t) { 9 | int sum1 = helper(s); 10 | int sum2 = helper(t); 11 | int diff = sum2 - sum1; 12 | return (char) diff; 13 | } 14 | 15 | private: 16 | int helper(string s) { 17 | int sum = 0; 18 | for(char c : s) { 19 | sum += c; 20 | } 21 | return sum; 22 | } 23 | }; 24 | 25 | int main() { 26 | // call the fn here 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/389. Find the Difference/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call your fn here 4 | } 5 | 6 | class Solution { 7 | public char findTheDifference(String s, String t) { 8 | int sum1 = helper(s); 9 | int sum2 = helper(t); 10 | int diff = sum2 - sum1; 11 | return (char) diff; 12 | } 13 | 14 | int helper(String s) { 15 | return s.chars().sum(); 16 | } 17 | 18 | } 19 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/389. Find the Difference/sol.md: -------------------------------------------------------------------------------- 1 | **Algorithm:** 2 | 3 | 1. Calculate the sum of the ASCII codes of all the characters in the first string, `s`. 4 | 2. Calculate the sum of the ASCII codes of all the characters in the second string, `t`. 5 | 3. Subtract the sum of the ASCII codes of `s` from the sum of the ASCII codes of `t`. 6 | 4. Return the character represented by the difference. 7 | 8 | **Time complexity:** O(n), where n is the length of the longer string. 9 | 10 | **Space complexity:** O(1), as we only use a few constant variables. 11 | 12 | for example, consider the following two strings: 13 | 14 | s = "ABCDELMN" 15 | t = "ABCFGLMN" 16 | 17 | 18 | The sum of the ASCII codes of all the characters in `s` is: 19 | 20 | A + B + C + D + E + L + M + N = 65 + 66 + 67 + 68 + 69 + 76 + 77 + 78 = 536 21 | 22 | The sum of the ASCII codes of all the characters in `t` is: 23 | 24 | A + B + C + F + G + L + M + N = 65 + 66 + 67 + 70 + 71 + 76 + 77 + 78 = 540 25 | 26 | The difference between the sum of the ASCII codes of `t` and `s` is 540 - 536 = 4 27 | 28 | The character represented by 4 is `F`. Therefore, the function will return `F`. 29 | 30 | -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/392. Is Subsequence/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | bool isSubsequence(string s, string t) { 9 | 10 | int n1 = s.length(); 11 | int n2 = t.length(); 12 | 13 | if(n1 < 1) return true; 14 | 15 | int i = 0; 16 | int j = 0; 17 | 18 | while(i < n2){ 19 | if(t[i] == s[j]){ 20 | j++; 21 | } 22 | i++; 23 | if(j == n1) return true; 24 | } 25 | 26 | return false; 27 | } 28 | }; 29 | 30 | int main() { 31 | 32 | // call the fn here 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/392. Is Subsequence/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | } 6 | 7 | class Solution { 8 | public boolean isSubsequence(String s, String t) { 9 | int n1 = s.length(); 10 | int n2 = t.length(); 11 | 12 | if (n1 < 1) 13 | return true; 14 | int i = 0; 15 | int j = 0; 16 | 17 | while (i < n2) { 18 | if (t.charAt(i) == s.charAt(j)) { 19 | j++; 20 | } 21 | i++; 22 | if (j == n1) 23 | return true; 24 | } 25 | return false; 26 | } 27 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/392. Is Subsequence/sol.md: -------------------------------------------------------------------------------- 1 | **Algorithm:** 2 | 3 | 1. Initialize two pointers, `i` and `j`, to the beginning of the strings `s` and `t`, respectively. 4 | 2. While `i` is less than the length of `t`: 5 | * If the character at `i` in `t` is equal to the character at `j` in `s`: 6 | * Increment `j`. 7 | * Increment `i`. 8 | * If `j` is equal to the length of `s`, then return `true`, indicating that `s` is a subsequence of `t`. 9 | 3. Return `false`, indicating that `s` is not a subsequence of `t`. 10 | 11 | **Time complexity:** O(n), where n is the length of the string `t`. 12 | 13 | **Space complexity:** O(1), as we only use two pointers. 14 | 15 | For example, consider the following two strings: 16 | 17 | s = "abc" 18 | t = "acb" 19 | 20 | The `i` and `j` pointers will be initialized to the beginning of the strings `s` and `t`, respectively. 21 | 22 | The `while` loop will then be executed as follows: 23 | 24 | 25 | Iteration | i | j | t.charAt(i) | s.charAt(j) | Action 26 | ------- | --- | --- | --- | --- | --- 27 | 1 | 0 | 0 | a | a | Increment j 28 | 2 | 1 | 1 | c | b | Do nothing 29 | 3 | 2 | 2 | b | c | Increment j 30 | 31 | 32 | At the end of the loop, `j` will be equal to the length of `s`, indicating that `s` is a subsequence of `t`. The function will then return `true`. -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/58. Length of Last Word/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int lengthOfLastWord(string s) { 9 | 10 | int count = 0; 11 | int i = s.length() - 1; 12 | 13 | while(i >= 0) { 14 | char ch = s[i]; 15 | 16 | if(ch == ' ' && count == 0) { 17 | i--; 18 | continue; 19 | } 20 | 21 | if(ch != ' ') { 22 | count++; 23 | i--; 24 | } else { 25 | return count; 26 | } 27 | } 28 | 29 | return count; 30 | } 31 | }; 32 | 33 | int main() { 34 | string s = "Hello World"; 35 | 36 | Solution sol; 37 | int result = sol.lengthOfLastWord(s); 38 | 39 | cout << result << endl; 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/58. Length of Last Word/sol.java: -------------------------------------------------------------------------------- 1 | public class sol{ 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | } 6 | class Solution { 7 | public int lengthOfLastWord(String s) { 8 | int count = 0; 9 | int i = s.length() - 1; 10 | while(i >= 0){ 11 | char ch = s.charAt(i); 12 | if(ch == ' ' && count == 0){ 13 | i--; 14 | continue; 15 | } 16 | if(ch != ' '){ 17 | count++; 18 | i--; 19 | } else{ 20 | return count; 21 | } 22 | } 23 | return count; 24 | } 25 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/58. Length of Last Word/sol.md: -------------------------------------------------------------------------------- 1 | **Algorithm:** 2 | 3 | 1. Initialize a count variable to 0. 4 | 2. Start at the end of the string and iterate backwards. 5 | 3. If the current character is a space and the count variable is 0, skip the character and continue iterating. 6 | 4. If the current character is not a space, increment the count variable and continue iterating. 7 | 5. If the current character is a space, return the count variable. 8 | 6. If the end of the string is reached, return the count variable. 9 | 10 | **Time complexity:** O(n), where n is the length of the string. 11 | 12 | **Space complexity:** O(1), as we only use a few constant variables. 13 | 14 | For example, consider the following string: 15 | 16 | "Hello World" 17 | 18 | If we call the `lengthOfLastWord()` function on this string, the following steps will be taken: 19 | 20 | 1. The count variable is initialized to 0. 21 | 2. The function starts at the end of the string and iterates backwards. 22 | 3. The current character is a space and the count variable is 0, so the character is skipped and the function continues iterating. 23 | 4. The current character is 'l', so the count variable is incremented to 1 and the function continues iterating. 24 | 5. The current character is 'd', so the count variable is incremented to 2 and the function continues iterating. 25 | 6. The current character is 'o', so the count variable is incremented to 3 and the function continues iterating. 26 | 7. The current character is 'r', so the count variable is incremented to 4 and the function continues iterating. 27 | 8. The current character is 'W', so the count variable is incremented to 5. 28 | 9. The current character is a space, so the function returns the count variable, which is 5. 29 | 30 | Therefore, the `lengthOfLastWord()` function will return `5` in this case. -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/905. Sort Array by Parity/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | vector sortArrayByParity(vector& nums) { 9 | 10 | int left = 0, right = 0; 11 | int n = nums.size(); 12 | 13 | while (right < n) { 14 | if (nums[right] % 2 == 0) { 15 | int temp = nums[left]; 16 | nums[left] = nums[right]; 17 | nums[right] = temp; 18 | left++; 19 | } 20 | right++; 21 | } 22 | 23 | return nums; 24 | } 25 | }; 26 | 27 | int main() { 28 | 29 | // call the fn here 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/905. Sort Array by Parity/sol.java: -------------------------------------------------------------------------------- 1 | public class sol{ 2 | public static void main(String[] args) { 3 | // call your fn here 4 | } 5 | } 6 | class Solution { 7 | public int[] sortArrayByParity(int[] nums) { 8 | int left = 0, right = 0; 9 | int n = nums.length; 10 | 11 | while (right < n) { 12 | if (nums[right] % 2 == 0) { 13 | int temp = nums[left]; 14 | nums[left] = nums[right]; 15 | nums[right] = temp; 16 | left++; 17 | } 18 | right++; 19 | } 20 | return nums; 21 | } 22 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Easy/905. Sort Array by Parity/sol.md: -------------------------------------------------------------------------------- 1 | **Algorithm:** 2 | 3 | 1. Initialize two pointers, `left` and `right`, to the beginning of the array. 4 | 2. While `right` is less than the length of the array: 5 | 3. If the element at `right` is even: 6 | * Swap the elements at `left` and `right`. 7 | * Increment `left`. 8 | 4. Increment `right`. 9 | 5. Return the array. 10 | 11 | **Time complexity:** O(n), where n is the length of the array. 12 | 13 | **Space complexity:** O(1), as we only use two pointers. 14 | 15 | For example, consider the following array: 16 | 17 | [1, 2, 3, 4, 5] 18 | If we call the `sortArrayByParity()` function on this array, the following steps will be taken: 19 | 20 | 1. The `left` and `right` pointers will both be initialized to the beginning of the array, which is index 0. 21 | 2. The element at `right` (index 0) is 1, which is odd. Therefore, the `left` and `right` pointers will not be swapped. 22 | 3. The `right` pointer is incremented to index 1. 23 | 4. The element at `right` (index 1) is 2, which is even. Therefore, the elements at `left` (index 0) and `right` (index 1) will be swapped. 24 | 5. The `left` pointer is incremented to index 1. 25 | 6. The `right` pointer is incremented to index 2. 26 | 7. The element at `right` (index 2) is 3, which is odd. Therefore, the `left` and `right` pointers will not be swapped. 27 | 8. The `right` pointer is incremented to index 3. 28 | 9. The element at `right` (index 3) is 4, which is even. Therefore, the elements at `left` (index 1) and `right` (index 3) will be swapped. 29 | 10. The `left` pointer is incremented to index 2. 30 | 11. The `right` pointer is incremented to index 4. 31 | 12. The element at `right` (index 4) is 5, which is odd. Therefore, the `left` and `right` pointers will not be swapped. 32 | 13. The `right` pointer has reached the end of the array, so the loop will terminate. 33 | 14. The function will return the array, which is now sorted by parity: 34 | 35 | ans = [2, 4, 1, 3, 5] 36 | -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/1095. Find In Mountain Array/sol.md: -------------------------------------------------------------------------------- 1 | Description of the question:- 2 | (This problem is an interactive problem.) 3 | 4 | You may recall that an array arr is a mountain array if and only if: 5 | 6 | arr.length >= 3 7 | There exists some i with 0 < i < arr.length - 1 such that: 8 | arr[0] < arr[1] < ... < arr[i - 1] < arr[i] 9 | arr[i] > arr[i + 1] > ... > arr[arr.length - 1] 10 | Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1. 11 | 12 | You cannot access the mountain array directly. You may only access the array using a MountainArray interface: 13 | 14 | MountainArray.get(k) returns the element of the array at index k (0-indexed). 15 | MountainArray.length() returns the length of the array. 16 | Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification. 17 | 18 | Approach :- 19 | we have to find the element in the Mountain array. 20 | We are also given that duplicate elements can also be present. 21 | So for doing this, first we will find out the Peak element or the Mountain element in the array. 22 | Then, we will apply binary search in the left side and right side of the peak element. 23 | And then if we find the element in both the halves, return the indice of left half. 24 | If not found in left half, return the indice of right half, 25 | Else return -1 as we didn't find the target element. 26 | 27 | Complexity:- 28 | Time complexity: 29 | O(logn) same as binary search. -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/1326. Min no of Taps to Open to Water a Garden/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution 8 | { 9 | public: 10 | int minTaps(int n, vector &ranges) 11 | { 12 | 13 | vector taps(n + 1, 0); 14 | 15 | for (int i = 0; i < ranges.size(); i++) 16 | { 17 | if (ranges[i] == 0) 18 | continue; 19 | int left = max(0, i - ranges[i]); 20 | taps[left] = max(taps[left], i + ranges[i]); 21 | } 22 | 23 | int cnt = 0, end = 0, far = 0; 24 | 25 | for (int i = 0; i <= n; i++) 26 | { 27 | if (i > end) 28 | { 29 | if (far <= end) 30 | return -1; 31 | end = far; 32 | cnt++; 33 | } 34 | far = max(far, taps[i]); 35 | } 36 | 37 | return cnt + (end < n ? 1 : 0); 38 | } 39 | }; 40 | 41 | int main() 42 | { 43 | // call the fn here 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/1326. Min no of Taps to Open to Water a Garden/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class sol { 4 | public static void main(String[] args) { 5 | // Call the fn here 6 | } 7 | 8 | public class Solution { 9 | public int minTaps(int n, int[] ranges) { 10 | int[] arr = new int[n + 1]; 11 | Arrays.fill(arr, 0); 12 | 13 | for (int i = 0; i < ranges.length; i++) { 14 | if (ranges[i] == 0) 15 | continue; 16 | int left = Math.max(0, i - ranges[i]); 17 | arr[left] = Math.max(arr[left], i + ranges[i]); 18 | } 19 | 20 | int end = 0, far_can_reach = 0, cnt = 0; 21 | for (int i = 0; i <= n; i++) { 22 | if (i > end) { 23 | if (far_can_reach <= end) 24 | return -1; 25 | end = far_can_reach; 26 | cnt++; 27 | } 28 | far_can_reach = Math.max(far_can_reach, arr[i]); 29 | } 30 | 31 | return cnt + (end < n ? 1 : 0); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/1359. Count All Valid Pickup and Delivery Options/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int MOD = 1000000007; 6 | 7 | class Solution 8 | { 9 | public: 10 | int countOrders(int n) 11 | { 12 | 13 | long long count = 1; 14 | 15 | for (int i = 2; i <= n; i++) 16 | { 17 | count = (count * (2 * i - 1) % MOD * i % MOD) % MOD; 18 | } 19 | 20 | return (int)count; 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | // call the fn here 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/1359. Count All Valid Pickup and Delivery Options/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | public class Solution { 7 | private static final int MOD = 1000000007; 8 | 9 | public int countOrders(int n) { 10 | long count = 1; 11 | for (int i = 2; i <= n; i++) { 12 | count = (count * (2 * i - 1) * i) % MOD; 13 | } 14 | return (int) count; 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/1359. Count All Valid Pickup and Delivery Options/sol.md: -------------------------------------------------------------------------------- 1 | 1. Initialize a variable `count` to 1. 2 | 2. Iterate over the integers from 2 to `n`, inclusive: 3 | * Multiply `count` by the product of `2 * i - 1` and `i`. 4 | * Take the remainder of the product by the modulus `MOD`, which is 1000000007. 5 | 3. Return `count`. 6 | 7 | The product `2 * i - 1` represents the number of ways to order `i` items if each item must be placed before the next item. For example, if we have 3 items, we can order them in 6 ways: 8 | 9 | 1. 2. 3. 10 | 2. 3. 1. 11 | 3. 3. 2. 12 | 4. 1. 2. 3. 13 | 5. 1. 3. 2. 14 | 6. 2. 1. 3. 15 | 16 | The product `i` represents the number of ways to order `i` items if there are no restrictions on the order. For example, if we have 3 items, we can order them in 6 ways: 17 | 18 | 1. 1. 2. 3. 19 | 2. 1. 3. 2. 20 | 3. 2. 1. 3. 21 | 4. 2. 3. 1. 22 | 5. 3. 1. 2. 23 | 6. 3. 2. 1. 24 | 25 | Therefore, the product `(2 * i - 1) * i` represents the number of ways to order `i` items if each item must be placed before the next item and there are no restrictions on the order of the items within each group. 26 | 27 | The modulus `MOD` is used to ensure that the value of `count` does not exceed the maximum value of an integer. 28 | 29 | **Example:** 30 | 31 | Consider the following input: 32 | 33 | n = 3 34 | 35 | The output is 6. 36 | 37 | **Explanation:** 38 | 39 | The value of `count` after each iteration of the loop is as follows: 40 | 41 | | Iteration | i | count | 42 | |---|---|---| 43 | | 1 | 2 | 1 | 44 | | 2 | 3 | 3 * 1 = 3 | 45 | | 3 | 4 | 6 * 3 = 18 | 46 | 47 | Since the modulus `MOD` is 1000000007, the value of `count` after the final iteration is 18. Therefore, the number of ways to order 4 items is 18. 48 | -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/1489. Find Critical and Pseudo-Critical Edges in Min Spanning Tree/sol.md: -------------------------------------------------------------------------------- 1 | The algorithm for the `findCriticalAndPseudoCriticalEdges()` function can be summarized as follows: 2 | 3 | 1. Sort the edges in ascending order by weight. 4 | 2. Initialize two empty lists: `critical` and `pseudoCritical`. 5 | 3. Iterate over the edges in sorted order: 6 | * If the MST weight increases when the edge is removed, then the edge is critical and should be added to the `critical` list. 7 | * If the MST weight does not change when the edge is removed, then the edge is pseudo-critical and should be added to the `pseudoCritical` list. 8 | 4. Return the `critical` and `pseudoCritical` lists. 9 | 10 | The `findMST()` function uses Prim's algorithm to find the minimum spanning tree of the graph. It takes three arguments: 11 | 12 | * `n`: The number of nodes in the graph. 13 | * `edges`: An array of edges, where each edge is represented by a 4-element array `[u, v, w, i]`, where `u` and `v` are the nodes that the edge connects, `w` is the weight of the edge, and `i` is the index of the edge in the original `edges` array. 14 | * `block`: The index of the edge to block, or -1 if no edge should be blocked. 15 | * `e`: The index of the edge to add before finding the MST, or -1 if no edge should be added. 16 | 17 | The `findMST()` function returns the weight of the MST, or `Integer.MAX_VALUE` if the graph is not connected. 18 | 19 | For example, consider the following input: 20 | 21 | n = 4 22 | edges = [[0, 1, 1], [1, 2, 2], [2, 3, 3], [0, 3, 4], [1, 4, 5], [2, 4, 6]] 23 | 24 | The sorted edges array is as follows: 25 | 26 | edges = [[0, 1, 1], [1, 2, 2], [2, 3, 3], [0, 3, 4], [1, 4, 5], [2, 4, 6]] 27 | 28 | The MST weight without any edges blocked is 6. 29 | 30 | The MST weight with the edge `[0, 3]` blocked is 9. 31 | 32 | The MST weight with the edge `[1, 4]` blocked is 7. 33 | 34 | Therefore, the critical edges are `[0, 3]` and `[1, 4]`, and the pseudo-critical edges are `[1, 2]`, `[2, 3]`, and `[2, 4]`. 35 | -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/2141. Maximum Running Time/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | long long maxRunTime(int n, vector& batteries) { 9 | 10 | long long total = 0; 11 | for(int battery : batteries) { 12 | total += battery; 13 | } 14 | 15 | long long start = 0, end = total; 16 | long long maxTime = 0; 17 | 18 | while(start <= end) { 19 | 20 | long long mid = start + (end - start) / 2; 21 | 22 | if(isFeasible(n, batteries, mid)) { 23 | maxTime = mid; 24 | start = mid + 1; 25 | } 26 | else { 27 | end = mid - 1; 28 | } 29 | } 30 | 31 | return maxTime; 32 | } 33 | 34 | private: 35 | bool isFeasible(int n, vector& batteries, long long time) { 36 | 37 | long long totalRunTime = 0; 38 | 39 | for(int battery : batteries) { 40 | if(battery <= time) { 41 | totalRunTime += battery; 42 | } 43 | else { 44 | totalRunTime += time; 45 | } 46 | } 47 | 48 | return totalRunTime >= time * n; 49 | } 50 | }; 51 | 52 | 53 | int main() { 54 | 55 | // call the fn here 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/2141. Maximum Running Time/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public long maxRunTime(int n, int[] batteries) { 8 | long sum = 0; 9 | for (int x : batteries) { 10 | sum += x; 11 | } 12 | 13 | long stTime = 0; 14 | long endTime = sum; 15 | long ans = 0; 16 | 17 | while (stTime <= endTime) { 18 | long avg = (stTime + endTime) / 2; 19 | if (runFeasible(n, batteries, avg)) { 20 | ans = avg; 21 | stTime = avg + 1; 22 | } else { 23 | endTime = avg - 1; 24 | } 25 | } 26 | return ans; 27 | } 28 | 29 | public boolean runFeasible(int n, int[] batteries, long avg) { 30 | long time = 0; 31 | for (int x : batteries) { 32 | if (x <= avg) { 33 | time += x; 34 | } else { 35 | time += avg; 36 | } 37 | } 38 | return time >= avg * n; 39 | } 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/2141. Maximum Running Time/sol.md: -------------------------------------------------------------------------------- 1 | The algorithm for the `maxRunTime()` function can be summarized as follows: 2 | 3 | 1. Calculate the sum of all batteries. 4 | 2. Initialize the start time and end time to 0 and the sum of all batteries, respectively. 5 | 3. Initialize the answer to 0. 6 | 4. While the start time is less than or equal to the end time: 7 | * Calculate the average of the start time and end time. 8 | * If the average is feasible, then: 9 | * Set the answer to the average. 10 | * Set the start time to the average plus 1. 11 | * Otherwise: 12 | * Set the end time to the average minus 1. 13 | 5. Return the answer. 14 | 15 | The `runFeasible()` function checks if the average run time is feasible. It does this by calculating the total time that all of the batteries can run for at the average run time. If the total time is greater than or equal to the average run time multiplied by the number of batteries, then the average run time is feasible. Otherwise, the average run time is not feasible. 16 | 17 | for example, consider the following input: 18 | 19 | n = 3 20 | batteries = [1, 2, 3] 21 | 22 | The sum of all batteries is 6. The start time and end time are initialized to 0 and 6, respectively. The answer is initialized to 0. 23 | 24 | The while loop is executed like this: 25 | 26 | | Iteration | Start time | End time | Average | Feasible? | Action | 27 | |---|---|---|---|---|---| 28 | | 1 | 0 | 6 | 3 | Yes | Set answer to 3. Set start time to 4. | 29 | | 2 | 4 | 3 | 3.5 | Yes | Set answer to 3.5. Set start time to 4.5. | 30 | | 3 | 4.5 | 3 | 3.75 | No | Set end time to 3. | 31 | | 4 | 4 | 3 | 3.5 | Yes | Set answer to 3.5. Set start time to 4.5. | 32 | | 5 | 4.5 | 3 | 3.75 | No | Set end time to 3. | 33 | 34 | The while loop terminates because the start time is now greater than the end time. The answer is 3.5. 35 | -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/2366. Min Replacements to Sort an Array/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | long long minimumReplacement(vector &nums) 10 | { 11 | 12 | long long ops = 0; 13 | long long prev = nums.back(); 14 | 15 | for (int i = nums.size() - 2; i >= 0; i--) 16 | { 17 | 18 | long long num = nums[i]; 19 | long long times = (num + prev - 1) / prev; 20 | ops += times - 1; 21 | 22 | prev = num / times; 23 | } 24 | 25 | return ops; 26 | } 27 | }; 28 | 29 | int main() 30 | { 31 | // call the fn here 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/2366. Min Replacements to Sort an Array/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | public class Solution { 7 | public long minimumReplacement(int[] nums) { 8 | long operations = 0; 9 | long prev_bound = nums[nums.length - 1]; 10 | 11 | for (int i = nums.length - 2; i >= 0; i--) { 12 | long num = nums[i]; 13 | long no_of_times = (num + prev_bound - 1) / prev_bound; 14 | operations += no_of_times - 1; 15 | prev_bound = num / no_of_times; 16 | } 17 | 18 | return operations; 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/2366. Min Replacements to Sort an Array/sol.md: -------------------------------------------------------------------------------- 1 | 1. Initialize the number of operations to 0. 2 | 2. Initialize the previous bound to the largest element in the array. 3 | 3. Iterate over the array in reverse order: 4 | * For each element in the array, calculate the number of times it needs to be divided by the previous bound to make it less than or equal to the previous bound. 5 | * Add the number of times the element needs to be divided to the number of operations. 6 | * Update the previous bound to the element divided by the number of times it was divided. 7 | 4. Return the number of operations. 8 | 9 | For example, consider the following input: 10 | 11 | nums = [3, 2, 1] 12 | 13 | The output is 1. 14 | 15 | **Explanation:** 16 | 17 | The largest element in the array is 3, so the previous bound is initialized to 3. 18 | 19 | The first element in the array is 2, which is greater than the previous bound. To make the element less than or equal to the previous bound, it needs to be divided by 3 once. 20 | 21 | The second element in the array is 1, which is less than or equal to the previous bound, so it does not need to be divided. 22 | 23 | The updated previous bound is 2, since the first element was divided by 3. 24 | 25 | The total number of operations is 1, since the first element needed to be divided once. 26 | -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/239. Sliding Window Max/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution 8 | { 9 | public: 10 | vector maxSlidingWindow(vector &nums, int k) 11 | { 12 | 13 | int n = nums.size(); 14 | if (n == 0 || k <= 0) 15 | return {}; 16 | 17 | vector ans; 18 | deque dq; 19 | 20 | for (int i = 0; i < n; i++) 21 | { 22 | 23 | if (!dq.empty() && dq.front() == i - k) 24 | { 25 | dq.pop_front(); 26 | } 27 | 28 | while (!dq.empty() && nums[dq.back()] < nums[i]) 29 | { 30 | dq.pop_back(); 31 | } 32 | 33 | dq.push_back(i); 34 | 35 | if (i >= k - 1) 36 | { 37 | ans.push_back(nums[dq.front()]); 38 | } 39 | } 40 | 41 | return ans; 42 | } 43 | }; 44 | 45 | int main() 46 | { 47 | 48 | // call the fn here 49 | 50 | return 0; 51 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/239. Sliding Window Max/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class sol { 3 | public static void main(String[] args) { 4 | // call the fn here 5 | } 6 | 7 | class Solution { 8 | public int[] maxSlidingWindow(int[] nums, int k) { 9 | if (nums == null || nums.length == 0 || k <= 0) { 10 | return new int[0]; 11 | } 12 | 13 | int[] ans = new int[nums.length - k + 1]; 14 | int x = 0; 15 | 16 | Deque deque = new LinkedList<>(); 17 | for (int i = 0; i < nums.length; i++) { 18 | while (!deque.isEmpty() && deque.peek() < i - k + 1) { 19 | deque.poll(); 20 | } 21 | 22 | while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) { 23 | deque.pollLast(); 24 | } 25 | 26 | deque.offer(i); 27 | 28 | if (i >= k - 1) { 29 | ans[x++] = nums[deque.peek()]; 30 | } 31 | } 32 | 33 | return ans; 34 | } 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/239. Sliding Window Max/sol.md: -------------------------------------------------------------------------------- 1 | **Algorithm:** 2 | 3 | 1. Initialize a deque to store the indices of the elements in the sliding window. 4 | 2. Iterate over the array `nums`: 5 | * While the deque is not empty and the front element of the deque is outside the sliding window, remove the front element from the deque. 6 | * While the deque is not empty and the element at the back of the deque is smaller than the current element, remove the back element from the deque. 7 | * Add the index of the current element to the back of the deque. 8 | * If the current index is greater than or equal to `k - 1`, then the sliding window has reached its full size. Add the element at the front of the deque to the answer array. 9 | 3. Return the answer array. 10 | 11 | **Time complexity:** O(n), where n is the length of the array `nums`. 12 | 13 | **Space complexity:** O(k), where k is the size of the sliding window. 14 | 15 | For example, consider the following input: 16 | 17 | nums = [1, 3, -1, -3, 5, 3, 6, 7] 18 | k = 3 19 | 20 | The deque will be filled like this: 21 | 22 | [0, 1, 2] 23 | [1, 2, 3] 24 | [2, 3, 4] 25 | [3, 4, 5] 26 | [4, 5, 6] 27 | [5, 6, 7] 28 | 29 | The answer array will be filled like this: 30 | 31 | ans = [3, 3, 5, 5, 6, 7] 32 | -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/332. Reconstruct Itinerary/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Solution 10 | { 11 | public: 12 | vector findItinerary(vector> &tickets) 13 | { 14 | 15 | map> graph; 16 | 17 | for (auto ticket : tickets) 18 | { 19 | graph[ticket[0]].push(ticket[1]); 20 | } 21 | 22 | list itinerary; 23 | dfs("JFK", graph, itinerary); 24 | 25 | return vector(itinerary.begin(), itinerary.end()); 26 | } 27 | 28 | private: 29 | void dfs(string airport, map> &graph, list &itinerary) 30 | { 31 | 32 | priority_queue &nextAirports = graph[airport]; 33 | 34 | while (!nextAirports.empty()) 35 | { 36 | dfs(nextAirports.top(), graph, itinerary); 37 | nextAirports.pop(); 38 | } 39 | 40 | itinerary.push_front(airport); 41 | } 42 | }; 43 | 44 | int main() 45 | { 46 | 47 | // call the fn here 48 | 49 | return 0; 50 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/332. Reconstruct Itinerary/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class sol { 4 | public static void main(String[] args) { 5 | // call the fn here 6 | } 7 | 8 | class Solution { 9 | public List findItinerary(List> tickets) { 10 | Map> graph = new HashMap<>(); 11 | 12 | for (List ticket : tickets) { 13 | graph.putIfAbsent(ticket.get(0), new PriorityQueue<>()); 14 | graph.get(ticket.get(0)).add(ticket.get(1)); 15 | } 16 | 17 | LinkedList itinerary = new LinkedList<>(); 18 | 19 | dfs("JFK", graph, itinerary); 20 | 21 | return itinerary; 22 | } 23 | 24 | private void dfs(String airport, Map> graph, LinkedList itinerary) { 25 | PriorityQueue nextAirports = graph.get(airport); 26 | while (nextAirports != null && !nextAirports.isEmpty()) { 27 | dfs(nextAirports.poll(), graph, itinerary); 28 | } 29 | itinerary.addFirst(airport); 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/332. Reconstruct Itinerary/sol.md: -------------------------------------------------------------------------------- 1 | 1. Create a map `graph` to store the adjacency list of the graph, where the keys are the airports and the values are priority queues of the next airports that can be visited from the current airport. 2 | 2. Iterate over the `tickets` list and add each ticket to the `graph` map. 3 | 3. Create a linked list `itinerary` to store the itinerary. 4 | 4. Call the `dfs()` function with the starting airport, the `graph` map, and the `itinerary` linked list. 5 | 6 | The `dfs()` function works recursively to find a path from the current airport to the end of the itinerary. It does this by repeatedly removing the next airport from the priority queue and calling itself on that airport. When the priority queue is empty, the function adds the current airport to the `itinerary` linked list. 7 | 8 | **Example:** 9 | 10 | Consider the following input: 11 | 12 | tickets = [[["JFK", "SFO"], ["JFK", "ATL"], ["SFO", "ATL"], ["ATL", "JFK"]]] 13 | 14 | The output is `["JFK", "ATL", "JFK", "SFO"]`. 15 | 16 | **Explanation:** 17 | 18 | The `graph` map after the iteration over the `tickets` list is as follows: 19 | 20 | graph = { 21 | "JFK": ["ATL", "SFO"], 22 | "ATL": ["JFK"], 23 | "SFO": ["ATL"] 24 | } 25 | 26 | The `dfs()` function is called with the starting airport "JFK" as follows: 27 | 28 | dfs("JFK", graph, itinerary); 29 | 30 | The `dfs()` function will recursively call itself on the next airports in the priority queue of "JFK", which are "ATL" and "SFO". The `dfs()` function will eventually reach the end of the itinerary and return. The `itinerary` linked list will then contain the following airports in order: 31 | 32 | ["JFK", "ATL", "JFK", "SFO"] 33 | 34 | Therefore, the output of the `findItinerary()` function is `["JFK", "ATL", "JFK", "SFO"]`. 35 | 36 | -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/4. Median of Two Sorted Arrays/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 9 | 10 | int m = nums1.size(); 11 | int n = nums2.size(); 12 | 13 | vector merged(m + n); 14 | 15 | int i = 0; 16 | int j = 0; 17 | int k = 0; 18 | 19 | while(i < m && j < n){ 20 | if(nums1[i] <= nums2[j]) { 21 | merged[k++] = nums1[i++]; 22 | } 23 | else { 24 | merged[k++] = nums2[j++]; 25 | } 26 | } 27 | 28 | while(i < m) { 29 | merged[k++] = nums1[i++]; 30 | } 31 | 32 | while(j < n) { 33 | merged[k++] = nums2[j++]; 34 | } 35 | 36 | int mid = merged.size() / 2; 37 | 38 | if(merged.size() % 2 == 0) { 39 | return (double)(merged[mid] + merged[mid - 1]) / 2; 40 | } 41 | else { 42 | return merged[mid]; 43 | } 44 | 45 | } 46 | }; 47 | 48 | int main() { 49 | 50 | // call the fn here 51 | 52 | return 0; 53 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/4. Median of Two Sorted Arrays/sol.java: -------------------------------------------------------------------------------- 1 | public class sol{ 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | } 6 | class Solution { 7 | public double findMedianSortedArrays(int[] m, int[] n) { 8 | int[] merged = new int[m.length + n.length]; 9 | int i = 0, j = 0, k = 0; 10 | 11 | while (i < m.length && j < n.length) { 12 | if (m[i] <= n[j]) { 13 | merged[k++] = m[i++]; 14 | } else { 15 | merged[k++] = n[j++]; 16 | } 17 | } 18 | 19 | while (i < m.length) { 20 | merged[k++] = m[i++]; 21 | } 22 | 23 | while (j < n.length) { 24 | merged[k++] = n[j++]; 25 | } 26 | 27 | int mid = merged.length / 2; 28 | if (merged.length % 2 == 0){ 29 | int sum = merged[mid] + merged[mid - 1]; 30 | return (double) sum / 2; 31 | } 32 | else{ 33 | return merged[mid]; 34 | } 35 | 36 | 37 | // return avg; 38 | 39 | } 40 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/4. Median of Two Sorted Arrays/sol.md: -------------------------------------------------------------------------------- 1 | **Algorithm:** 2 | 3 | 1. Create a new array `merged` of size `m.length + n.length` to store the merged sorted array. 4 | 2. Initialize three pointers `i`, `j`, and `k`. `i` and `j` will point to the first elements of the arrays `m` and `n`, respectively. `k` will point to the first element of the array `merged`. 5 | 3. While `i` is less than the length of `m` and `j` is less than the length of `n`: 6 | * If the element at `i` in `m` is less than or equal to the element at `j` in `n`: 7 | * Copy the element at `i` in `m` to the element at `k` in `merged`. 8 | * Increment `i` and `k`. 9 | * Otherwise: 10 | * Copy the element at `j` in `n` to the element at `k` in `merged`. 11 | * Increment `j` and `k`. 12 | 4. While `i` is less than the length of `m`: 13 | * Copy the element at `i` in `m` to the element at `k` in `merged`. 14 | * Increment `i` and `k`. 15 | 5. While `j` is less than the length of `n`: 16 | * Copy the element at `j` in `n` to the element at `k` in `merged`. 17 | * Increment `j` and `k`. 18 | 6. Calculate the middle index of the array `merged`. 19 | 7. If the length of the array `merged` is even: 20 | * Return the average of the two elements at the middle index and the middle index minus one. 21 | 8. Otherwise: 22 | * Return the element at the middle index. 23 | 24 | **Time complexity:** O(m + n), where m and n are the lengths of the arrays `m` and `n`, respectively. This is because we only need to iterate over the two arrays once. 25 | 26 | **Space complexity:** O(m + n), where m and n are the lengths of the arrays `m` and `n`, respectively. This is because we need to store the merged array `merged`. 27 | 28 | for example, consider the following two arrays: 29 | 30 | 31 | m = [1, 3, 5, 7] 32 | n = [2, 4, 6, 8] 33 | 34 | The merged array will be: 35 | 36 | merged = [1, 2, 3, 4, 5, 6, 7, 8] 37 | 38 | The middle index of the merged array is 3. Therefore, the function will return the average of the two elements at index 3 and index 2, which is `(3 + 4) / 2 = 3.5`. 39 | -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/41. First Missing Positive/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int firstMissingPositive(vector& nums) { 10 | 11 | int n = nums.size(); 12 | 13 | for(int i=0; i 0){ 28 | return i+1; 29 | } 30 | } 31 | 32 | return n+1; 33 | } 34 | }; 35 | 36 | int main() { 37 | 38 | /// call the fn here 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/41. First Missing Positive/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public int firstMissingPositive(int[] nums) { 8 | int n = nums.length; 9 | 10 | for (int i = 0; i < n; i++) { 11 | if (nums[i] <= 0) { 12 | nums[i] = n + 1; 13 | } 14 | } 15 | 16 | for (int i = 0; i < n; i++) { 17 | int num = Math.abs(nums[i]); 18 | if (num <= n) { 19 | nums[num - 1] = -Math.abs(nums[num - 1]); 20 | } 21 | } 22 | 23 | for (int i = 0; i < n; i++) { 24 | if (nums[i] > 0) { 25 | return i + 1; 26 | } 27 | } 28 | 29 | return n + 1; 30 | } 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/41. First Missing Positive/sol.md: -------------------------------------------------------------------------------- 1 | **Algorithm:** 2 | 3 | 1. Iterate over the array and replace all non-positive elements with `n + 1`, where `n` is the length of the array. 4 | 2. Iterate over the array again and for each element, take the absolute value and subtract 1. If the element is less than or equal to `n`, then negate the element at that index. 5 | 3. Iterate over the array again and the first element that is greater than 0 is the first missing positive integer. If all elements are greater than 0, then the first missing positive integer is `n + 1`. 6 | 7 | **Time complexity:** O(n), where `n` is the length of the array. 8 | 9 | **Space complexity:** O(1), as we only use a few constant variables. 10 | 11 | for example, consider the following array: 12 | 13 | nums = [3, 4, -1, 1] 14 | 15 | After the first iteration, the array will be: 16 | 17 | nums = [4, 5, 1, 2] 18 | 19 | After the second iteration, the array will be: 20 | 21 | 22 | nums = [-4, -5, 1, -2] 23 | 24 | After the third iteration, the array will be: 25 | 26 | nums = [4, 5, 1, -2] 27 | 28 | The first element that is greater than 0 is `4`, which is at index 0. Therefore, the first missing positive integer is `4`. 29 | -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/664. Strange Printer/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution 8 | { 9 | public: 10 | int strangePrinter(string s) 11 | { 12 | 13 | int n = s.size(); 14 | vector> dp(n, vector(n, 0)); 15 | 16 | return solve(s, 0, n - 1, dp); 17 | } 18 | 19 | private: 20 | int solve(string &s, int i, int j, vector> &dp) 21 | { 22 | 23 | if (i > j) 24 | return 0; 25 | 26 | if (dp[i][j] != 0) 27 | return dp[i][j]; 28 | 29 | int ans = solve(s, i, j - 1, dp) + 1; 30 | 31 | for (int k = i; k < j; k++) 32 | { 33 | if (s[k] == s[j]) 34 | { 35 | ans = min(ans, solve(s, i, k, dp) + solve(s, k + 1, j - 1, dp)); 36 | } 37 | } 38 | 39 | return dp[i][j] = ans; 40 | } 41 | }; 42 | 43 | int main() 44 | { 45 | // call the fn here 46 | return 0; 47 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/664. Strange Printer/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public int strangePrinter(String s) { 8 | int n = s.length(); 9 | int[][] temp = new int[n][n]; 10 | return minTurns(s, 0, n - 1, temp); 11 | } 12 | 13 | int minTurns(String s, int start, int end, int[][] temp) { 14 | if (start > end) { 15 | return 0; 16 | } 17 | 18 | if (temp[start][end] > 0) { 19 | return temp[start][end]; 20 | } 21 | 22 | int turns = minTurns(s, start, end - 1, temp) + 1; 23 | for (int i = start; i < end; i++) { 24 | if (s.charAt(i) == s.charAt(end)) { 25 | turns = Math.min(turns, minTurns(s, start, i, temp) + minTurns(s, i + 1, end - 1, temp)); 26 | } 27 | } 28 | 29 | temp[start][end] = turns; 30 | return turns; 31 | } 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/68. Test Justification/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution 8 | { 9 | public: 10 | vector fullJustify(vector &words, int maxWidth) 11 | { 12 | 13 | vector result; 14 | int i = 0; 15 | 16 | while (i < words.size()) 17 | { 18 | 19 | int wordCount = 0, lineLen = 0; 20 | while (i + wordCount < words.size() && 21 | lineLen + words[i + wordCount].length() + wordCount <= maxWidth) 22 | { 23 | lineLen += words[i + wordCount].length(); 24 | wordCount++; 25 | } 26 | 27 | string line; 28 | if (wordCount == 1 || i + wordCount == words.size()) 29 | { 30 | for (int j = 0; j < wordCount; j++) 31 | { 32 | line += words[i + j] + " "; 33 | } 34 | line += string(maxWidth - line.length(), ' '); 35 | } 36 | else 37 | { 38 | int spaces = (maxWidth - lineLen) / (wordCount - 1); 39 | int extra = (maxWidth - lineLen) % (wordCount - 1); 40 | for (int j = 0; j < wordCount; j++) 41 | { 42 | line += words[i + j]; 43 | if (j != wordCount - 1) 44 | { 45 | line += string(spaces + (extra-- > 0 ? 1 : 0), ' '); 46 | } 47 | } 48 | } 49 | result.push_back(line); 50 | i += wordCount; 51 | } 52 | return result; 53 | } 54 | }; 55 | 56 | int main() 57 | { 58 | // call the fn here 59 | return 0; 60 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/68. Test Justification/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class sol { 3 | public static void main(String[] args) { 4 | // call the fn here 5 | } 6 | 7 | class Solution { 8 | public List fullJustify(String[] words, int maxWidth) { 9 | List result = new ArrayList<>(); 10 | 11 | for (int i = 0, wordCount, lineLength; i < words.length; i += wordCount) { 12 | for (wordCount = 0, lineLength = 0; i + wordCount < words.length && 13 | lineLength + words[i + wordCount].length() + wordCount <= maxWidth; wordCount++) { 14 | lineLength += words[i + wordCount].length(); 15 | } 16 | 17 | StringBuilder lineBuilder = new StringBuilder(words[i]); 18 | 19 | if (wordCount == 1 || i + wordCount == words.length) { 20 | for (int j = 1; j < wordCount; j++) { 21 | lineBuilder.append(" ").append(words[i + j]); 22 | } 23 | lineBuilder.append(" ".repeat(maxWidth - lineBuilder.length())); 24 | } else { 25 | int totalSpaces = (maxWidth - lineLength) / (wordCount - 1); 26 | int extraSpaces = (maxWidth - lineLength) % (wordCount - 1); 27 | 28 | for (int j = 1; j < wordCount; j++) { 29 | int spacesToAdd = totalSpaces + (extraSpaces-- > 0 ? 1 : 0); 30 | lineBuilder.append(" ".repeat(spacesToAdd)).append(words[i + j]); 31 | } 32 | } 33 | result.add(lineBuilder.toString()); 34 | } 35 | return result; 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/68. Test Justification/sol.md: -------------------------------------------------------------------------------- 1 | The algorithm for the `fullJustify()` function can be summarized as follows: 2 | 3 | 1. Initialize a list to store the justified lines. 4 | 2. Iterate over the words array: 5 | * For each word, calculate the length of the current line, including the word and the spaces required to justify it. 6 | * If the current line length is greater than or equal to the maximum width, or if the current word is the last word in the array, then add the current line to the result list and start a new line. 7 | * Otherwise, add the current word to the current line. 8 | 3. For each justified line in the result list: 9 | * If the line contains only one word or if the line is the last line in the list, then pad the line with spaces until it reaches the maximum width. 10 | * Otherwise, calculate the number of spaces to add between each word on the line, and add the spaces accordingly. 11 | 4. Return the list of justified lines. 12 | 13 | for example, consider the following input: 14 | 15 | words = ["This", "is", "an", "example", "of", "text", "justification."] 16 | maxWidth = 16 17 | 18 | The output is as follows: 19 | 20 | ["This is an", 21 | "example of text", 22 | "justification."] 23 | 24 | **Explanation:** 25 | 26 | The first line has a length of 16, which is the maximum width. The second line has a length of 15, so one space is added between each word. The third line is the last line, so it is padded with spaces until it reaches the maximum width. 27 | -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/920. Number of Music Playlists/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int numMusicPlaylists(int n, int goal, int k) { 9 | const int MOD = 1000000007; 10 | vector> temp(goal + 1, vector(n + 1, 0)); 11 | temp[0][0] = 1; 12 | 13 | for (int i = 1; i <= goal; i++) { 14 | for (int j = 1; j <= n; j++) { 15 | temp[i][j] = (temp[i][j] + temp[i - 1][j - 1] * (n - j + 1)) % MOD; 16 | if (j > k) { 17 | temp[i][j] = (temp[i][j] + temp[i - 1][j] * (j - k)) % MOD; 18 | } 19 | } 20 | } 21 | 22 | return static_cast(temp[goal][n]); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/920. Number of Music Playlists/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | private static final int MOD = 1000000007; 8 | 9 | public int numMusicPlaylists(int n, int goal, int k) { 10 | long[][] temp = new long[goal + 1][n + 1]; 11 | temp[0][0] = 1; 12 | 13 | for (int i = 1; i <= goal; i++) { 14 | for (int j = 1; j <= n; j++) { 15 | temp[i][j] = (temp[i][j] + temp[i - 1][j - 1] * (n - j + 1)) % MOD; 16 | if (j > k) { 17 | temp[i][j] = (temp[i][j] + temp[i - 1][j] * (j - k)) % MOD; 18 | } 19 | } 20 | } 21 | 22 | return (int) temp[goal][n]; 23 | } 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /LeetCode Questions/LeetCode Hard/920. Number of Music Playlists/sol.md: -------------------------------------------------------------------------------- 1 | **Algorithm:** 2 | 3 | 1. Initialize a 2D array `temp` to store the number of playlists that can be created with `i` songs and `j` unique songs. 4 | 2. Set the value of `temp[0][0]` to 1, since there is only one playlist that can be created with 0 songs and 0 unique songs. 5 | 3. Iterate over the `temp` array, starting at `(1, 1)`: 6 | * For each index `(i, j)`, calculate the number of playlists that can be created with `i` songs and `j` unique songs as follows: 7 | * Add the number of playlists that can be created with `i - 1` songs and `j - 1` unique songs, multiplied by the number of unique songs that can be added to the playlist. 8 | * If `j > k`, then add the number of playlists that can be created with `i - 1` songs and `j` unique songs, multiplied by the number of ways to reuse a song that has already been played in the playlist. 9 | 4. Return the value of `temp[goal][n]`, which is the number of playlists that can be created with `goal` songs and `n` unique songs. 10 | 11 | **Time complexity:** O(n * goal), where n is the number of unique songs and goal is the number of songs in the playlist. 12 | 13 | **Space complexity:** O(n * goal), where n is the number of unique songs and goal is the number of songs in the playlist. 14 | 15 | for example, consider the following input: 16 | 17 | n = 3 18 | goal = 3 19 | k = 1 20 | 21 | The `temp` array will be filled like this: 22 | 23 | temp = [[1, 3, 6], 24 | [0, 3, 6], 25 | [0, 0, 3]] 26 | 27 | The answer is `temp[goal][n] = 3`, which is the number of playlists that can be created with 3 songs and 3 unique songs. 28 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/1081. Smallest SubSequence of Distinct Characters/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class sol { 4 | public static void main(String[] args) { 5 | // call the fn here 6 | } 7 | 8 | class Solution { 9 | public String smallestSubsequence(String s) { 10 | Stack stack = new Stack<>(); 11 | boolean[] inStack = new boolean[26]; 12 | int[] lastIndex = new int[26]; 13 | 14 | for (int i = 0; i < s.length(); i++) { 15 | lastIndex[s.charAt(i) - 'a'] = i; 16 | } 17 | 18 | for (int i = 0; i < s.length(); i++) { 19 | char ch = s.charAt(i); 20 | 21 | if (inStack[ch - 'a']) { 22 | continue; 23 | } 24 | 25 | while (!stack.isEmpty() && ch < stack.peek() && i < lastIndex[stack.peek() - 'a']) { 26 | inStack[stack.pop() - 'a'] = false; 27 | } 28 | 29 | stack.push(ch); 30 | inStack[ch - 'a'] = true; 31 | } 32 | 33 | StringBuilder result = new StringBuilder(); 34 | for (char ch : stack) { 35 | result.append(ch); 36 | } 37 | 38 | return result.toString(); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/1081. Smallest SubSequence of Distinct Characters/sol.md: -------------------------------------------------------------------------------- 1 | Initialize a stack to store the characters in the smallest subsequence. 2 | Initialize a boolean array inStack to track whether a character is already in the stack. 3 | Initialize an integer array lastIndex to track the last index of each character in the string. 4 | Iterate over the string: 5 | If the character at the current index is already in the stack, skip it. 6 | While the stack is not empty and the current character is less than the character at the top of the stack, and the current index is less than the last index of the character at the top of the stack: 7 | Pop the character at the top of the stack and set the corresponding entry in the inStack array to false. 8 | Push the current character onto the stack and set the corresponding entry in the inStack array to true. 9 | Build the smallest subsequence by popping the characters from the stack and appending them to a string. 10 | Return the smallest subsequence. 11 | The time complexity of the algorithm is O(n), where n is the length of the string. This is because the algorithm needs to traverse the string twice. 12 | 13 | The space complexity of the algorithm is O(n), since it needs to store the stack, the boolean array, and the integer array. -------------------------------------------------------------------------------- /LeetCode Questions/Medium/11. Container With Most Water/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxArea(vector& height) { 4 | int maxArea = 0; 5 | int leftIdx = 0, rightIdx = height.size() - 1; 6 | 7 | while(leftIdx < rightIdx){ 8 | maxArea = max(maxArea, min(height[leftIdx], height[rightIdx]) * (rightIdx - leftIdx)); 9 | if(height[leftIdx] < height[rightIdx]) 10 | leftIdx++; 11 | else 12 | rightIdx--; 13 | } 14 | 15 | return maxArea; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/11. Container With Most Water/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxArea(int[] height) { 3 | int maxArea = 0; 4 | int leftIdx = 0, rightIdx = height.length-1; 5 | 6 | while(leftIdx < rightIdx){ 7 | maxArea = Math.max(maxArea, Math.min(height[leftIdx], height[rightIdx]) * (rightIdx - leftIdx)); 8 | if(height[leftIdx] < height[rightIdx]) 9 | leftIdx++; 10 | else 11 | rightIdx--; 12 | } 13 | 14 | return maxArea; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/142. LinkedList Cycle II/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct ListNode 6 | { 7 | int val; 8 | ListNode *next; 9 | ListNode(int x) : val(x), next(NULL) {} 10 | }; 11 | 12 | class Solution 13 | { 14 | public: 15 | ListNode *detectCycle(ListNode *head) 16 | { 17 | 18 | ListNode *slow = head; 19 | ListNode *fast = head; 20 | 21 | while (fast != NULL && fast->next != NULL) 22 | { 23 | slow = slow->next; 24 | fast = fast->next->next; 25 | 26 | if (slow == fast) 27 | { 28 | return getStartingNode(head, slow); 29 | } 30 | } 31 | 32 | return NULL; 33 | } 34 | 35 | private: 36 | ListNode *getStartingNode(ListNode *head, ListNode *meetingPoint) 37 | { 38 | ListNode *slow = head; 39 | while (slow != meetingPoint) 40 | { 41 | slow = slow->next; 42 | meetingPoint = meetingPoint->next; 43 | } 44 | return slow; 45 | } 46 | }; 47 | 48 | int main() 49 | { 50 | 51 | // call the fn here 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/142. LinkedList Cycle II/sol.java: -------------------------------------------------------------------------------- 1 | 2 | class ListNode { 3 | int val; 4 | ListNode next; 5 | 6 | ListNode() { 7 | } 8 | 9 | ListNode(int val) { 10 | this.val = val; 11 | } 12 | 13 | ListNode(int val, ListNode next) { 14 | this.val = val; 15 | this.next = next; 16 | } 17 | } 18 | 19 | public class sol { 20 | public static void main(String[] args) { 21 | // call the fn here 22 | } 23 | 24 | public class Solution { 25 | public ListNode detectCycle(ListNode head) { 26 | 27 | ListNode slow = head; 28 | ListNode fast = head; 29 | 30 | while (fast != null && fast.next != null) { 31 | slow = slow.next; 32 | fast = fast.next.next; 33 | 34 | if (fast == slow) { 35 | return node(head, slow, fast); 36 | } 37 | } 38 | 39 | return null; 40 | } 41 | 42 | ListNode node(ListNode head, ListNode slow, ListNode fast) { 43 | 44 | slow = head; 45 | while (slow != fast) { 46 | slow = slow.next; 47 | fast = fast.next; 48 | } 49 | 50 | return slow; 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/142. LinkedList Cycle II/sol.md: -------------------------------------------------------------------------------- 1 | 1. Initialize two pointers, `slow` and `fast`, to the head of the linked list. 2 | 2. Iterate over the linked list: 3 | * Move the `slow` pointer one node forward. 4 | * Move the `fast` pointer two nodes forward. 5 | * If the `fast` pointer and the `slow` pointer meet, then there is a cycle in the linked list. 6 | 3. If the `fast` pointer reaches the end of the linked list without meeting the `slow` pointer, then there is no cycle in the linked list. 7 | 4. If there is a cycle in the linked list, then the function returns the node where the `slow` pointer and the `fast` pointer meet. 8 | 9 | **Example:** 10 | 11 | Consider the following linked list: 12 | head -> 1 -> 2 -> 3 -> 4 -> 5 -> 3 13 | 14 | 15 | The algorithm will work as follows: 16 | 17 | 18 | Iteration | slow.val | fast.val | 19 | -------- | -------- | -------- | 20 | 1 | 1 | 1 | 21 | 2 | 2 | 3 | 22 | 3 | 3 | 4 | 23 | 4 | 4 | 5 | 24 | 5 | 5 | 3 | 25 | 26 | 27 | At the fifth iteration, the `slow` pointer and the `fast` pointer meet at the node `3`. Therefore, the function returns the node `3`. 28 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/1448. Count Good Nodes in Binary Tree/Solution.java: -------------------------------------------------------------------------------- 1 | // Using recursion 2 | class Solution { 3 | int n = 0; 4 | public int goodNodes(TreeNode root) { 5 | goodNode(root, root.val); 6 | return n; 7 | } 8 | 9 | public void goodNode(TreeNode root, int lastMax){ 10 | if(root == null) return; 11 | if(root.val >= lastMax){ 12 | n++; 13 | lastMax = root.val; 14 | } 15 | goodNode(root.left, lastMax); 16 | goodNode(root.right, lastMax); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/153. Find Minimum in Rotated Sorted Array/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int findMin(vector &nums) 10 | { 11 | 12 | int start = 0; 13 | int end = nums.size() - 1; 14 | int ans = start; 15 | 16 | while (nums[start] > nums[end]) 17 | { 18 | int mid = (start + end) / 2; 19 | 20 | if (nums[mid] <= nums[start] && nums[mid] <= nums[end]) 21 | { 22 | end = mid; 23 | } 24 | else if (nums[mid] >= nums[start] && nums[mid] >= nums[end]) 25 | { 26 | start = mid + 1; 27 | } 28 | else 29 | { 30 | return nums[mid]; 31 | } 32 | 33 | ans = start; 34 | } 35 | 36 | return nums[ans]; 37 | } 38 | }; 39 | 40 | int main() 41 | { 42 | 43 | // call the fn here 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/153. Find Minimum in Rotated Sorted Array/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public int findMin(int[] nums) { 8 | int start = 0, end = nums.length - 1, ans = start; 9 | while (nums[start] > nums[end]) { 10 | int mid = (start + end) / 2; 11 | if (nums[mid] <= nums[start] && nums[mid] <= nums[end]) { 12 | end = mid; 13 | } else if (nums[mid] >= nums[start] && nums[mid] >= nums[end]) { 14 | start = mid + 1; 15 | } else { 16 | return nums[mid]; 17 | } 18 | ans = start; 19 | } 20 | return nums[ans]; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/153. Find Minimum in Rotated Sorted Array/sol.md: -------------------------------------------------------------------------------- 1 | 1. Initialize two pointers, `start` and `end`, to the beginning and end of the input array `nums`, respectively. 2 | 2. Initialize a variable `ans` to the value of `start`. 3 | 3. While the element at the index `start` is greater than the element at the index `end`: 4 | * Calculate the middle index `mid` as (`start` + `end`) / 2. 5 | * If the element at the index `mid` is less than or equal to the element at the index `start` and the element at the index `mid` is less than or equal to the element at the index `end`, then set the value of `end` to `mid`. 6 | * If the element at the index `mid` is greater than or equal to the element at the index `start` and the element at the index `mid` is greater than or equal to the element at the index `end`, then set the value of `start` to `mid + 1`. 7 | * Otherwise, return the element at the index `mid`. 8 | 4. Update the value of `ans` to `start`. 9 | 5. Return the element at the index `ans`. 10 | 11 | **Example:** 12 | 13 | Consider the following input array `nums`: 14 | 15 | nums = [3, 4, 5, 1, 2] 16 | 17 | The algorithm will work as follows: 18 | 19 | Iteration | start | end | mid | ans 20 | -------- | -------- | -------- | -------- | -------- 21 | 1 | 0 | 4 | 2 | 0 22 | 2 | 0 | 1 | 0 | 0 23 | 24 | The algorithm will return the element at the index `ans`, which is `1`. -------------------------------------------------------------------------------- /LeetCode Questions/Medium/1584. Min Cost to Connect All Dots/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Queue; 3 | 4 | public class sol { 5 | public static void main(String[] args) { 6 | // call the fn here 7 | } 8 | 9 | class Solution { 10 | public int minCostConnectPoints(int[][] points) { 11 | int n = points.length; 12 | int[][] matrix = new int[n][n]; 13 | boolean[] visited = new boolean[n]; 14 | Queue queue = new LinkedList<>(); 15 | int distance = 0; 16 | // get all distance 17 | for (int i = 0; i < n; i++) { 18 | for (int j = 0; j < n; j++) { 19 | matrix[i][j] = Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]); 20 | } 21 | ; 22 | } 23 | 24 | // first 25 | queue.add(0); 26 | visited[0] = true; 27 | while (queue.size() < n) { 28 | int sizes = queue.size(); 29 | int len = Integer.MAX_VALUE; 30 | int choosen = 0; 31 | int nextPoint = 0; 32 | for (int ss = 0; ss < sizes; ss++) { 33 | int connect = queue.poll(); 34 | for (int next = 0; next < n; next++) { 35 | if (!visited[next]) { 36 | if (matrix[connect][next] < len) { 37 | choosen = connect; 38 | nextPoint = next; 39 | len = matrix[connect][next]; 40 | } 41 | } 42 | 43 | } 44 | queue.add(connect); 45 | } 46 | visited[nextPoint] = true; 47 | queue.add(nextPoint); 48 | distance += len; 49 | 50 | } 51 | 52 | return distance; 53 | 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/1584. Min Cost to Connect All Dots/sol.md: -------------------------------------------------------------------------------- 1 | 1. Initialize a priority queue to store the edges that need to be considered. The priority queue is sorted in ascending order of the edge weight. 2 | 2. Add the edge with the lowest weight to the priority queue. 3 | 3. While the priority queue is not empty: 4 | * Pop the edge with the lowest weight from the priority queue. 5 | * If the popped edge connects two unconnected vertices, then add the edge to the spanning tree and mark the two vertices as connected. 6 | * Otherwise, discard the edge. 7 | 4. Return the spanning tree. 8 | 9 | Our code implements Prim's algorithm efficiently by using a priority queue to store the edges that need to be considered. The priority queue ensures that the edges are considered in order of increasing weight, which leads to a more efficient search. 10 | 11 | Here are some specific comments about the code: 12 | 13 | * We use a `boolean[]` array to track which vertices have already been visited. This is a good approach, as it allows we to avoid adding duplicate edges to the spanning tree. 14 | * We use a `Queue` to store the vertices that need to be considered. This is also a good approach, as it allows we to implement Prim's algorithm in a recursive manner. 15 | * We use a `Integer.MAX_VALUE` as the initial value for the `len` variable. This ensures that the first edge added to the priority queue is the edge with the lowest weight. 16 | * We use a `choosen` variable to track the vertex that is connected to the lowest-weight edge. This allows you to avoid adding the same edge to the priority queue multiple times. 17 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/1631. Path With Minimum Effort/sol.md: -------------------------------------------------------------------------------- 1 | 1. Initialize a priority queue to store the nodes that need to be visited. The priority queue is sorted in descending order of the effort required to reach the node. 2 | 2. Add the source node to the priority queue with an effort of 0. 3 | 3. While the priority queue is not empty: 4 | * Pop the node with the lowest effort from the priority queue. 5 | * If the popped node is the destination node, then return the effort. 6 | * For each neighbor of the popped node: 7 | * Calculate the effort to reach the neighbor. 8 | * If the calculated effort is lower than the current effort for the neighbor, then update the effort for the neighbor and add it to the priority queue. 9 | 4. Return the effort required to reach the destination node, or -1 if the destination node is unreachable. 10 | 11 | The code implements Dijkstra's algorithm efficiently by using a priority queue to store the nodes that need to be visited. Priority queue ensures that the nodes are visited in order of increasing effort, which leads to a more efficient search. -------------------------------------------------------------------------------- /LeetCode Questions/Medium/1647. Min Deletions to Make Char Frequencies Unique/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class sol { 4 | public static void main(String[] args) { 5 | // call the fn here 6 | } 7 | 8 | public class Solution { 9 | public int minDeletions(String s) { 10 | int[] freq = new int[26]; // Create an array to store character frequencies 11 | 12 | for (char c : s.toCharArray()) { 13 | freq[c - 'a']++; // Count the frequency of each character 14 | } 15 | 16 | Arrays.sort(freq); // Sort frequencies in ascending order 17 | 18 | int del = 0; // Initialize the deletion count 19 | 20 | for (int i = 24; i >= 0; i--) { 21 | if (freq[i] == 0) { 22 | break; // No more characters with this frequency 23 | } 24 | 25 | if (freq[i] >= freq[i + 1]) { 26 | int prev = freq[i]; 27 | freq[i] = Math.max(0, freq[i + 1] - 1); 28 | del += prev - freq[i]; // Update the deletion count 29 | } 30 | } 31 | 32 | return del; // Return the minimum deletions required 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/1647. Min Deletions to Make Char Frequencies Unique/sol.md: -------------------------------------------------------------------------------- 1 | Create an array to store the frequency of each character in the string. 2 | Sort the frequencies in ascending order. 3 | Initialize the deletion count to zero. 4 | Iterate over the frequencies in reverse order. 5 | If the current frequency is equal to or greater than the next frequency, then decrement the current frequency by the maximum of zero and the next frequency minus one. Update the deletion count by the difference between the previous and current frequencies. 6 | Return the deletion count. 7 | 8 | 9 | his algorithm works by greedily reducing the frequency of the most common characters until all frequencies are distinct. This ensures that the minimum number of deletions is required to achieve a unique frequency distribution. -------------------------------------------------------------------------------- /LeetCode Questions/Medium/1658. Minimum Operations to Reduce X to Zero/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution 8 | { 9 | public: 10 | int minOperations(vector &nums, int x) 11 | { 12 | 13 | int target = 0; 14 | for (int num : nums) 15 | { 16 | target += num; 17 | } 18 | target -= x; 19 | 20 | if (target < 0) 21 | { 22 | return -1; 23 | } 24 | 25 | int left = 0; 26 | int curSum = 0; 27 | int maxLength = INT_MIN; 28 | 29 | for (int right = 0; right < nums.size(); right++) 30 | { 31 | curSum += nums[right]; 32 | 33 | while (curSum > target) 34 | { 35 | curSum -= nums[left++]; 36 | } 37 | 38 | if (curSum == target) 39 | { 40 | maxLength = max(maxLength, right - left + 1); 41 | } 42 | } 43 | 44 | return maxLength == INT_MIN ? -1 : nums.size() - maxLength; 45 | } 46 | }; 47 | 48 | int main() 49 | { 50 | 51 | // call the fn here 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/1658. Minimum Operations to Reduce X to Zero/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public int minOperations(int[] nums, int x) { 8 | int target = 0; 9 | for (int num : nums) { 10 | target += num; 11 | } 12 | target -= x; 13 | 14 | if (target < 0) { 15 | return -1; 16 | } 17 | 18 | int left = 0; 19 | int curSum = 0; 20 | int maxSubLength = Integer.MIN_VALUE; 21 | int n = nums.length; 22 | 23 | for (int right = 0; right < n; right++) { 24 | curSum += nums[right]; 25 | 26 | while (curSum > target) { 27 | curSum -= nums[left]; 28 | left++; 29 | } 30 | 31 | if (curSum == target) { 32 | maxSubLength = Math.max(maxSubLength, right - left + 1); 33 | } 34 | } 35 | 36 | return maxSubLength == Integer.MIN_VALUE ? -1 : n - maxSubLength; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/1658. Minimum Operations to Reduce X to Zero/sol.md: -------------------------------------------------------------------------------- 1 | 1. Initialize the target value to the sum of all elements in the input array `nums` minus the desired value `x`. 2 | 2. If the target value is less than zero, then return -1, since it is impossible to find a subarray with a sum greater than or equal to `x`. 3 | 3. Initialize two pointers, `left` and `right`, to the beginning of the array. 4 | 4. Initialize the current sum `curSum` to zero. 5 | 5. Initialize the maximum subarray length `maxSubLength` to the minimum value of an integer. 6 | 6. While the right pointer is less than the length of the array: 7 | * Add the element at the right pointer to the current sum. 8 | * While the current sum is greater than the target value: 9 | * Subtract the element at the left pointer from the current sum. 10 | * Increment the left pointer. 11 | * If the current sum is equal to the target value, then update the maximum subarray length `maxSubLength` to the maximum of the current length and the right pointer minus the left pointer plus 1. 12 | 7. Increment the right pointer. 13 | 8. Return the difference between the length of the array `nums` and the maximum subarray length `maxSubLength`. 14 | 15 | This algorithm works by sliding a window over the array, keeping track of the current sum of the elements in the window. If the current sum is greater than the target value, then the algorithm shrinks the window by removing the element at the left pointer. If the current sum is equal to the target value, then the algorithm updates the maximum subarray length. The algorithm terminates when the right pointer reaches the end of the array. 16 | 17 | The time complexity of the algorithm is O(n), where n is the length of the input array `nums`. This is because the algorithm traverses the array once. 18 | 19 | The space complexity of the algorithm is O(1), since it only needs to store a few variables. 20 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/179. Largest Number/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution 8 | { 9 | public: 10 | string largestNumber(vector &nums) 11 | { 12 | 13 | vector strNums; 14 | for (int num : nums) 15 | { 16 | strNums.push_back(to_string(num)); 17 | } 18 | 19 | sort(strNums.begin(), strNums.end(), [](string &a, string &b) 20 | { return a + b > b + a; }); 21 | 22 | string ans; 23 | for (string s : strNums) 24 | { 25 | ans += s; 26 | } 27 | 28 | return ans[0] == '0' ? "0" : ans; 29 | } 30 | }; 31 | 32 | int main() 33 | { 34 | 35 | // call the fn here 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/179. Largest Number/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class sol { 4 | public static void main(String[] args) { 5 | // call the fn here 6 | } 7 | 8 | class Solution { 9 | public String largestNumber(int[] nums) { 10 | String ans = ""; 11 | ArrayList list = new ArrayList<>(); 12 | 13 | for (int i = 0; i < nums.length; i++) { 14 | list.add(String.valueOf(nums[i])); 15 | } 16 | 17 | Collections.sort(list, (a, b) -> (b + a).compareTo(a + b)); 18 | 19 | for (String s : list) { 20 | ans += s; 21 | } 22 | 23 | return ans.charAt(0) == '0' ? "0" : ans; 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/179. Largest Number/sol.md: -------------------------------------------------------------------------------- 1 | 1. Create an empty string `ans` to store the largest number. 2 | 2. Create an ArrayList `list` to store the string representations of the input numbers. 3 | 3. Iterate over the input array `nums` and add the string representations of the numbers to the ArrayList `list`. 4 | 4. Sort the ArrayList `list` in decreasing order using a custom comparator function that compares two strings by concatenating them together and comparing the resulting strings. 5 | 5. Iterate over the ArrayList `list` and append the strings to the string `ans`. 6 | 6. If the first character of the string `ans` is '0', then return the string "0". Otherwise, return the string `ans`. 7 | 8 | The custom comparator function works as follows: 9 | 10 | 1. Concatenate the two input strings together. 11 | 2. Compare the two concatenated strings. 12 | 3. Return a negative integer, zero, or a positive integer depending on whether the first concatenated string is less than, equal to, or greater than the second concatenated string, respectively. 13 | 14 | **Example:** 15 | 16 | Consider the following input array `nums`: 17 | 18 | nums = [10, 2, 3, 4, 5] 19 | 20 | The ArrayList `list` after the iteration over the input array `nums` is as follows: 21 | 22 | list = ["10", "2", "3", "4", "5"] 23 | 24 | The ArrayList `list` after the sort operation is as follows: 25 | 26 | list = ["5", "4", "3", "2", "10"] 27 | 28 | The string `ans` after the iteration over the ArrayList `list` is as follows: 29 | 30 | ans = "543210" 31 | 32 | Since the first character of the string `ans` is not '0', the function returns the string `ans`. 33 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/19. Remove nth Node From the End/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct ListNode 6 | { 7 | int val; 8 | ListNode *next; 9 | 10 | ListNode() : val(0), next(nullptr) {} 11 | ListNode(int x) : val(x), next(nullptr) {} 12 | ListNode(int x, ListNode *next) : val(x), next(next) {} 13 | }; 14 | 15 | class Solution 16 | { 17 | public: 18 | ListNode *removeNthFromEnd(ListNode *head, int n) 19 | { 20 | 21 | ListNode *dummy = new ListNode(0); 22 | dummy->next = head; 23 | 24 | ListNode *first = dummy; 25 | ListNode *second = dummy; 26 | 27 | for (int i = 0; i <= n; i++) 28 | { 29 | first = first->next; 30 | } 31 | 32 | while (first != NULL) 33 | { 34 | first = first->next; 35 | second = second->next; 36 | } 37 | 38 | second->next = second->next->next; 39 | 40 | return dummy->next; 41 | } 42 | }; 43 | 44 | int main() 45 | { 46 | // call the fn here 47 | return 0; 48 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/19. Remove nth Node From the End/sol.java: -------------------------------------------------------------------------------- 1 | 2 | class ListNode { 3 | int val; 4 | ListNode next; 5 | 6 | ListNode() { 7 | } 8 | 9 | ListNode(int val) { 10 | this.val = val; 11 | } 12 | 13 | ListNode(int val, ListNode next) { 14 | this.val = val; 15 | this.next = next; 16 | } 17 | } 18 | public class sol { 19 | public static void main(String[] args) { 20 | // call the fn here 21 | } 22 | } 23 | 24 | 25 | class Solution { 26 | public ListNode removeNthFromEnd(ListNode head, int n) { 27 | ListNode dummy = new ListNode(0); 28 | dummy.next = head; 29 | ListNode first = dummy; 30 | ListNode second = dummy; 31 | 32 | for (int i = 0; i <= n; i++) { 33 | first = first.next; 34 | } 35 | 36 | while (first != null) { 37 | first = first.next; 38 | second = second.next; 39 | } 40 | 41 | second.next = second.next.next; 42 | 43 | return dummy.next; 44 | } 45 | 46 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/19. Remove nth Node From the End/sol.md: -------------------------------------------------------------------------------- 1 | 1. Create a dummy node and set its next pointer to the head of the linked list. 2 | 2. Initialize two pointers, `first` and `second`, to the dummy node. 3 | 3. Advance the `first` pointer `n + 1` nodes forward. 4 | 4. While the `first` pointer is not null: 5 | * Advance both the `first` and `second` pointers one node forward. 6 | 5. Set the `next` pointer of the `second` node to the `next` pointer of the `second.next` node. 7 | 6. Return the next pointer of the dummy node. 8 | 9 | The time complexity of the algorithm is O(n), where n is the length of the linked list. This is because the algorithm needs to traverse the linked list twice. 10 | 11 | The space complexity of the algorithm is O(1), since it only needs to store three pointers. 12 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/1996. The Number of Weak Characters in the Game/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static bool compare(vector& a, vector& b){ 4 | if(a[0] == b[0]) 5 | return a[1] < b[1]; 6 | return a[0] > b[0]; 7 | } 8 | 9 | int numberOfWeakCharacters(vector>& properties) { 10 | int n = properties.size(); 11 | int count = 0; 12 | sort(properties.begin(), properties.end(), compare); 13 | int maxN = INT_MIN; 14 | for(int i = 0; i < n; i++){ 15 | if(properties[i][1] < maxN) 16 | count++; 17 | maxN = max(maxN, properties[i][1]); 18 | } 19 | return count; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/1996. The Number of Weak Characters in the Game/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfWeakCharacters(int[][] properties) { 3 | int n = properties.length; 4 | int count = 0; 5 | int maxN = Integer.MIN_VALUE; 6 | Arrays.sort(properties, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]); 7 | for(int i = 0; i < n; i++){ 8 | if(properties[i][1] < maxN) 9 | count++; 10 | maxN = Math.max(maxN, properties[i][1]); 11 | } 12 | return count; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/1996. The Number of Weak Characters in the Game/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numberOfWeakCharacters(self, properties): 3 | count = 0 4 | maxN = ~sys.maxint 5 | properties.sort(key=lambda x: (-x[0], x[1])) 6 | for i in range(len(properties)): 7 | if(properties[i][1] < maxN): 8 | count+=1 9 | maxN = max(maxN, properties[i][1]) 10 | return count 11 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/2. Add Two Numbers/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct ListNode 6 | { 7 | int val; 8 | ListNode *next; 9 | ListNode() : val(0), next(nullptr) {} 10 | ListNode(int x) : val(x), next(nullptr) {} 11 | ListNode(int x, ListNode *next) : val(x), next(next) {} 12 | }; 13 | 14 | class Solution 15 | { 16 | public: 17 | ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) 18 | { 19 | ListNode *dummy = new ListNode(0); 20 | ListNode *cur = dummy; 21 | int carry = 0; 22 | 23 | while (l1 != nullptr || l2 != nullptr) 24 | { 25 | int x = (l1 != nullptr) ? l1->val : 0; 26 | int y = (l2 != nullptr) ? l2->val : 0; 27 | int sum = carry + x + y; 28 | 29 | carry = sum / 10; 30 | cur->next = new ListNode(sum % 10); 31 | cur = cur->next; 32 | 33 | if (l1 != nullptr) 34 | l1 = l1->next; 35 | if (l2 != nullptr) 36 | l2 = l2->next; 37 | } 38 | 39 | if (carry > 0) 40 | { 41 | cur->next = new ListNode(carry); 42 | } 43 | 44 | return dummy->next; 45 | } 46 | }; 47 | 48 | int main() 49 | { 50 | // call the fn here 51 | return 0; 52 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/2. Add Two Numbers/sol.java: -------------------------------------------------------------------------------- 1 | 2 | class ListNode { 3 | int val; 4 | ListNode next; 5 | 6 | ListNode() { 7 | } 8 | 9 | ListNode(int val) { 10 | this.val = val; 11 | } 12 | 13 | ListNode(int val, ListNode next) { 14 | this.val = val; 15 | this.next = next; 16 | } 17 | } 18 | 19 | public class sol { 20 | public static void main(String[] args) { 21 | // call the fn here 22 | } 23 | 24 | class Solution { 25 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 26 | ListNode temp = new ListNode(0); 27 | ListNode temp2 = temp; 28 | int carry = 0; 29 | 30 | while (l1 != null || l2 != null) { 31 | int x = (l1 != null) ? l1.val : 0; 32 | int y = (l2 != null) ? l2.val : 0; 33 | int sum = carry + x + y; 34 | 35 | carry = sum / 10; 36 | temp2.next = new ListNode(sum % 10); 37 | temp2 = temp2.next; 38 | 39 | if (l1 != null) 40 | l1 = l1.next; 41 | if (l2 != null) 42 | l2 = l2.next; 43 | } 44 | 45 | if (carry > 0) { 46 | temp2.next = new ListNode(carry); 47 | } 48 | 49 | return temp.next; 50 | } 51 | } 52 | 53 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/2. Add Two Numbers/sol.md: -------------------------------------------------------------------------------- 1 | 1. Create a new linked list `temp` to store the sum of the two input linked lists. 2 | 2. Iterate over the two input linked lists, `l1` and `l2`: 3 | * Add the values of the current nodes in `l1` and `l2`, and the carryover from the previous iteration, to get the sum. 4 | * Calculate the carryover by dividing the sum by 10 and taking the remainder. 5 | * Add the remainder to the new linked list `temp`. 6 | * Move to the next nodes in `l1` and `l2`. 7 | 3. If there is a carryover after the iteration, add it to the new linked list `temp`. 8 | 4. Return the head of the new linked list `temp`. 9 | 10 | **Example:** 11 | 12 | Consider the following input: 13 | 14 | l1 = [2, 4, 3] 15 | l2 = [5, 6, 4] 16 | 17 | The algorithm will work as follows: 18 | 19 | Iteration | l1.val | l2.val | sum | carryover | temp 20 | -------- | -------- | -------- | -------- | -------- | -------- 21 | 1 | 2 | 5 | 7 | 0 | [7] 22 | 2 | 4 | 6 | 10 | 1 | [7, 1] 23 | 3 | 3 | 4 | 7 | 0 | [7, 1, 7] 24 | 25 | The output of the algorithm is the head of the new linked list `temp`, which is `[7, 1, 7]`. 26 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/200. Number of Islands/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numIslands(vector>& grid) { 4 | int n = 0; 5 | for(int i = 0; i < grid.size(); i++){ 6 | for(int j = 0; j < grid[0].size(); j++){ 7 | if(grid[i][j] == '1'){ 8 | n++; 9 | visitIsland(grid, i, j); 10 | } 11 | } 12 | } 13 | return n; 14 | } 15 | 16 | private: 17 | void visitIsland(vector>& grid, int r, int c){ 18 | if(r < 0 || c < 0 || r >= grid.size() || c >= grid[0].size() || grid[r][c] == '0') 19 | return; 20 | grid[r][c] = '0'; 21 | visitIsland(grid, r + 1, c); 22 | visitIsland(grid, r - 1, c); 23 | visitIsland(grid, r, c + 1); 24 | visitIsland(grid, r, c - 1); 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/200. Number of Islands/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | char[][] mat; 3 | int[] DIR = {1, 0, -1, 0, 1}; 4 | public int numIslands(char[][] grid) { 5 | int n = 0; 6 | mat = grid; 7 | int rows = mat.length; 8 | int cols = mat[0].length; 9 | for(int i = 0; i < rows; i++){ 10 | for(int j = 0; j < cols; j++){ 11 | if(mat[i][j] == '1') { 12 | visitIsland(i, j); 13 | n++; 14 | } 15 | } 16 | } 17 | return n; 18 | } 19 | 20 | public void visitIsland(int r, int c){ 21 | if(r < 0 || c < 0 || r >= mat.length || c >= mat[r].length || mat[r][c] == '0') return; 22 | mat[r][c] = '0'; 23 | for(int i = 0; i < DIR.length - 1; i++){ 24 | visitIsland(r + DIR[i], c + DIR[i + 1]); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/2038. Remove Colored Pieces if/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool winnerOfGame(string colors) { 8 | int countA = 0; 9 | int countB = 0; 10 | 11 | for (int i = 1; i < colors.length() - 1; i++) { 12 | if (colors[i - 1] == colors[i] && colors[i] == colors[i + 1]) { 13 | if (colors[i] == 'A') { 14 | countA++; 15 | } else { 16 | countB++; 17 | } 18 | } 19 | } 20 | 21 | return countA > countB; 22 | } 23 | }; -------------------------------------------------------------------------------- /LeetCode Questions/Medium/2038. Remove Colored Pieces if/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public boolean winnerOfGame(String colors) { 8 | int countA = 0; 9 | int countB = 0; 10 | for (int i = 1; i < colors.length() - 1; i++) { 11 | if (colors.charAt(i - 1) == colors.charAt(i) && colors.charAt(i) == colors.charAt(i + 1)) { 12 | if (colors.charAt(i) == 'A') { 13 | countA++; 14 | } else { 15 | countB++; 16 | } 17 | } 18 | } 19 | return countA > countB; 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/2038. Remove Colored Pieces if/sol.md: -------------------------------------------------------------------------------- 1 | 1. Initialize two variables `countA` and `countB` to keep track of the number of times the characters `A` and `B` appear in consecutive groups of three, respectively. 2 | 2. Iterate over the input string `colors`: 3 | * If the current character and the next two characters are all the same, then increment the corresponding counter `countA` or `countB` depending on the character. 4 | 3. Return `true` if `countA` is greater than `countB`, otherwise return `false`. 5 | 6 | **Example:** 7 | 8 | Consider the following input: 9 | 10 | 11 | colors = "ABBBBAA" 12 | 13 | 14 | The algorithm will work as follows: 15 | 16 | 17 | Iteration | i | colors.charAt(i - 1) | colors.charAt(i) | colors.charAt(i + 1) | countA | countB 18 | -------- | -------- | -------- | -------- | -------- | -------- | -------- 19 | 1 | 1 | A | B | B | 0 | 0 20 | 2 | 2 | B | B | B | 0 | 1 21 | 3 | 3 | B | B | A | 0 | 1 22 | 4 | 4 | B | A | A | 1 | 1 23 | 5 | 5 | A | A | A | 2 | 1 24 | 6 | 6 | A | A | B | 2 | 1 25 | 26 | 27 | The output of the algorithm is `true`, since `countA` is greater than `countB`. -------------------------------------------------------------------------------- /LeetCode Questions/Medium/2707. Extra Chars in a String/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class sol { 5 | public static void main(String[] args) { 6 | // call the fn here 7 | } 8 | 9 | public class Solution { 10 | public int minExtraChar(String s, String[] dictionary) { 11 | Map cache = new HashMap<>(); 12 | 13 | int result = dfs(s, dictionary, cache); 14 | return result; 15 | } 16 | 17 | private int dfs(String text, String[] dictionary, Map cache) { 18 | if (text.isEmpty()) { 19 | return 0; 20 | } 21 | 22 | if (cache.containsKey(text.length())) { 23 | return cache.get(text.length()); 24 | } 25 | 26 | int minimum = text.length(); 27 | 28 | for (String word : dictionary) { 29 | if (text.equals(word)) { 30 | minimum = 0; 31 | cache.put(text.length(), minimum); 32 | return minimum; 33 | } else if (text.startsWith(word)) { 34 | int result = dfs(text.substring(word.length()), dictionary, cache); 35 | minimum = Math.min(minimum, result); 36 | } 37 | } 38 | 39 | int result = 1 + dfs(text.substring(1), dictionary, cache); 40 | minimum = Math.min(minimum, result); 41 | 42 | cache.put(text.length(), minimum); 43 | return minimum; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/2707. Extra Chars in a String/sol.md: -------------------------------------------------------------------------------- 1 | Summary of the algorithm: 2 | 3 | 1. Create a cache to store the minimum number of extra characters needed to make a substring of the given string valid. 4 | 2. Use a recursive function to calculate the minimum number of extra characters needed to make the given string valid. 5 | 3. The recursive function works as follows: 6 | * If the given string is empty, then return 0. 7 | * If the given string is in the dictionary, then return 0. 8 | * Otherwise, try to remove each prefix of the given string and check if the remaining string is valid. 9 | * Return the minimum number of extra characters needed to make the given string valid, plus 1. 10 | 11 | Overall, the code for the `minExtraChar()` function is excellent. It is a correct, efficient, and well-written implementation of the algorithm. 12 | 13 | Here are some additional comments about the code: 14 | 15 | * We use a cache to store the minimum number of extra characters needed to make a substring of the given string valid. This is a good approach, as it can significantly improve the performance of the algorithm. 16 | * We use a recursive function to calculate the minimum number of extra characters needed to make the given string valid. This is also a good approach, as it allows we to easily handle complex cases. 17 | * the code is well-formatted and easy to read. This is important for maintainability and debuggability. 18 | 19 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/287. Find Duplicate Number/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int findDuplicate(vector &nums) 10 | { 11 | 12 | int slow = nums[0]; 13 | int fast = nums[0]; 14 | 15 | do 16 | { 17 | slow = nums[slow]; 18 | fast = nums[nums[fast]]; 19 | } while (slow != fast); 20 | 21 | fast = nums[0]; 22 | 23 | while (slow != fast) 24 | { 25 | slow = nums[slow]; 26 | fast = nums[fast]; 27 | } 28 | 29 | return slow; 30 | } 31 | }; 32 | 33 | int main() 34 | { 35 | 36 | // call the fn here 37 | return 0; 38 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/287. Find Duplicate Number/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public int findDuplicate(int[] arr) { 8 | int slowPtr = arr[0]; 9 | int fastPtr = arr[0]; 10 | 11 | do { 12 | fastPtr = arr[arr[fastPtr]]; 13 | slowPtr = arr[slowPtr]; 14 | } while (fastPtr != slowPtr); 15 | 16 | fastPtr = arr[0]; 17 | 18 | while (fastPtr != slowPtr) { 19 | fastPtr = arr[fastPtr]; 20 | slowPtr = arr[slowPtr]; 21 | } 22 | 23 | return fastPtr; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/287. Find Duplicate Number/sol.md: -------------------------------------------------------------------------------- 1 | 1. Initialize two pointers, `slowPtr` and `fastPtr`, to the beginning of the array. 2 | 2. While the two pointers are not equal: 3 | * Move the `fastPtr` pointer two steps forward. 4 | * Move the `slowPtr` pointer one step forward. 5 | 3. Initialize the `fastPtr` pointer to the beginning of the array. 6 | 4. While the two pointers are not equal: 7 | * Move the `fastPtr` pointer one step forward. 8 | * Move the `slowPtr` pointer one step forward. 9 | 5. The `slowPtr` pointer will now be pointing to the duplicate element in the array. 10 | 6. Return the value of the `slowPtr` pointer. 11 | 12 | The Floyd's cycle detection algorithm works by finding the intersection point of two runners, one that moves two steps at a time and the other that moves one step at a time. If there is a cycle in the array, then the two runners will eventually meet at the intersection point. The intersection point will be the duplicate element in the array. 13 | 14 | The time complexity of the algorithm is O(n), where n is the length of the array. This is because the algorithm traverses the array twice. 15 | 16 | The space complexity of the algorithm is O(1), since it only needs to store two pointers. -------------------------------------------------------------------------------- /LeetCode Questions/Medium/316. Remove Duplicate Letters/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class sol { 4 | public static void main(String[] args) { 5 | // call the fn here 6 | } 7 | 8 | class Solution { 9 | public String removeDuplicateLetters(String s) { 10 | Stack stack = new Stack<>(); 11 | boolean[] inStack = new boolean[26]; 12 | int[] lastIndex = new int[26]; 13 | 14 | for (int i = 0; i < s.length(); i++) { 15 | lastIndex[s.charAt(i) - 'a'] = i; 16 | } 17 | 18 | for (int i = 0; i < s.length(); i++) { 19 | char ch = s.charAt(i); 20 | 21 | if (inStack[ch - 'a']) { 22 | continue; 23 | } 24 | 25 | while (!stack.isEmpty() && ch < stack.peek() && i < lastIndex[stack.peek() - 'a']) { 26 | inStack[stack.pop() - 'a'] = false; 27 | } 28 | 29 | stack.push(ch); 30 | inStack[ch - 'a'] = true; 31 | } 32 | 33 | StringBuilder result = new StringBuilder(); 34 | for (char ch : stack) { 35 | result.append(ch); 36 | } 37 | 38 | return result.toString(); 39 | } 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/316. Remove Duplicate Letters/sol.md: -------------------------------------------------------------------------------- 1 | It is very similar to your code for the `smallestSubsequence()` function. The only difference is that the `removeDuplicateLetters()` function does not append the characters from the stack to a string in a specific order. Instead, it pops the characters from the stack and adds them to the string until the stack is empty. 2 | 3 | Here is a summary of the algorithm: 4 | 5 | 1. Initialize a stack to store the characters in the string. 6 | 2. Initialize a boolean array `inStack` to track whether a character is already in the stack. 7 | 3. Initialize an integer array `lastIndex` to track the last index of each character in the string. 8 | 4. Iterate over the string: 9 | * If the character at the current index is already in the stack, skip it. 10 | * While the stack is not empty and the current character is less than the character at the top of the stack, and the current index is less than the last index of the character at the top of the stack: 11 | * Pop the character at the top of the stack and set the corresponding entry in the `inStack` array to `false`. 12 | * Push the current character onto the stack and set the corresponding entry in the `inStack` array to `true`. 13 | 5. Pop the characters from the stack and add them to a string until the stack is empty. 14 | 6. Return the string. 15 | 16 | The time complexity of the algorithm is O(n), where n is the length of the string. This is because the algorithm needs to traverse the string twice. 17 | 18 | The space complexity of the algorithm is O(n), since it needs to store the stack, the boolean array, and the integer array. 19 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/34. First and Last Position of Element in an Array/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | vector searchRange(vector &nums, int target) 10 | { 11 | 12 | vector result(2, -1); 13 | result[0] = findFirst(nums, target); 14 | result[1] = findLast(nums, target); 15 | 16 | return result; 17 | } 18 | 19 | private: 20 | int findFirst(vector &nums, int target) 21 | { 22 | int low = 0, high = nums.size() - 1; 23 | 24 | while (low <= high) 25 | { 26 | int mid = low + (high - low) / 2; 27 | 28 | if (nums[mid] >= target) 29 | { 30 | high = mid - 1; 31 | } 32 | else 33 | { 34 | low = mid + 1; 35 | } 36 | 37 | if (nums[mid] == target) 38 | { 39 | return mid; 40 | } 41 | } 42 | 43 | return -1; 44 | } 45 | 46 | int findLast(vector &nums, int target) 47 | { 48 | int low = 0, high = nums.size() - 1; 49 | 50 | while (low <= high) 51 | { 52 | int mid = low + (high - low) / 2; 53 | 54 | if (nums[mid] <= target) 55 | { 56 | low = mid + 1; 57 | } 58 | else 59 | { 60 | high = mid - 1; 61 | } 62 | 63 | if (nums[mid] == target) 64 | { 65 | return mid; 66 | } 67 | } 68 | 69 | return -1; 70 | } 71 | }; 72 | 73 | int main() 74 | { 75 | 76 | // call the fn here 77 | 78 | return 0; 79 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/34. First and Last Position of Element in an Array/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public int[] searchRange(int[] nums, int target) { 8 | int[] arr = new int[2]; 9 | arr[0] = firstIndex(nums, target); 10 | arr[1] = lastIndex(nums, target); 11 | return arr; 12 | } 13 | 14 | int firstIndex(int[] nums, int target) { 15 | int index = -1; 16 | int s = 0; 17 | int e = nums.length - 1; 18 | while (s <= e) { 19 | int mid = s + (e - s) / 2; 20 | if (nums[mid] >= target) { 21 | e = mid - 1; 22 | } else { 23 | s = mid + 1; 24 | } 25 | 26 | if (nums[mid] == target) { 27 | index = mid; 28 | } 29 | } 30 | return index; 31 | } 32 | 33 | int lastIndex(int[] nums, int target) { 34 | int index = -1; 35 | int s = 0; 36 | int e = nums.length - 1; 37 | while (s <= e) { 38 | int mid = s + (e - s) / 2; 39 | if (nums[mid] <= target) { 40 | s = mid + 1; 41 | } else { 42 | e = mid - 1; 43 | } 44 | 45 | if (nums[mid] == target) { 46 | index = mid; 47 | } 48 | } 49 | return index; 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/34. First and Last Position of Element in an Array/sol.md: -------------------------------------------------------------------------------- 1 | 1. Create a new array `arr` of size 2 to store the start and end indices of the target element in the sorted array `nums`. 2 | 2. Call the `firstIndex()` function to find the start index of the target element in the sorted array. 3 | 3. Call the `lastIndex()` function to find the end index of the target element in the sorted array. 4 | 4. Return the array `arr`. 5 | 6 | The `firstIndex()` and `lastIndex()` functions work in a similar way. They both use binary search to find the start and end indices of the target element in the sorted array, respectively. 7 | 8 | The `firstIndex()` function works as follows: 9 | 10 | 1. Initialize two pointers, `s` and `e`, to the start and end indices of the sorted array, respectively. 11 | 2. While `s` is less than or equal to `e`: 12 | * Calculate the middle index `mid` as `s + (e - s) / 2`. 13 | * If the element at the middle index is greater than or equal to the target element, then set the end index `e` to `mid - 1`. 14 | * Otherwise, set the start index `s` to `mid + 1`. 15 | * If the element at the middle index is equal to the target element, then set the start index `s` to `mid`. 16 | 3. Return the start index `s`. 17 | 18 | The `lastIndex()` function works in a similar way, except that it sets the end index `e` to `mid + 1` if the element at the middle index is less than or equal to the target element. 19 | 20 | **Example:** 21 | 22 | Consider the following sorted array `nums` and the target element `target = 5`: 23 | 24 | nums = [1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9] 25 | 26 | 27 | The `firstIndex()` function will return the index `3`, which is the start index of the target element in the sorted array. 28 | 29 | The `lastIndex()` function will return the index `5`, which is the end index of the target element in the sorted array. 30 | 31 | Therefore, the `searchRange()` function will return the array `[3, 5]`. 32 | 33 | 34 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/36. Valid Sudoku/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isValidSudoku(char[][] board) { 3 | for(int i = 0; i < 9; i++){ 4 | Set row = new HashSet(); 5 | Set col = new HashSet(); 6 | Set sqr = new HashSet(); 7 | for(int j = 0; j < 9; j++){ 8 | if(board[i][j] != '.' && !row.add(board[i][j])) return false; 9 | if(board[j][i] != '.' && !col.add(board[j][i])) return false; 10 | int rowIdx = 3*(i/3); 11 | int colIdx = 3*(i%3); 12 | if(board[rowIdx + j/3][colIdx + j%3] != '.' && !sqr.add(board[rowIdx + j/3][colIdx + j%3])) return false; 13 | } 14 | } 15 | return true; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/48. Rotate Image/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector>& matrix) { 4 | for(int i = 0; i < matrix.size(); i++){ 5 | for(int j = i; j < matrix[0].size(); j++){ 6 | int t = matrix[i][j]; 7 | matrix[i][j] = matrix[j][i]; 8 | matrix[j][i] = t; 9 | } 10 | } 11 | 12 | for(int i = 0; i < matrix.size(); i++){ 13 | for(int j = 0; j < matrix.size()/2; j++){ 14 | int t = matrix[i][j]; 15 | matrix[i][j] = matrix[i][matrix.size() - 1 - j]; 16 | matrix[i][matrix.size() - 1 - j] = t; 17 | } 18 | } 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/48. Rotate Image/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void rotate(int[][] matrix) { 3 | for(int i = 0; i < matrix.length; i++){ 4 | for(int j = i; j < matrix[0].length; j++){ 5 | int t = matrix[i][j]; 6 | matrix[i][j] = matrix[j][i]; 7 | matrix[j][i] = t; 8 | } 9 | } 10 | 11 | for(int i = 0; i < matrix.length; i++){ 12 | for(int j = 0; j < matrix.length/2; j++){ 13 | int t = matrix[i][j]; 14 | matrix[i][j] = matrix[i][matrix.length - 1 - j]; 15 | matrix[i][matrix.length - 1 - j] = t; 16 | } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/61. Rotate List/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct ListNode 6 | { 7 | int val; 8 | ListNode *next; 9 | ListNode() : val(0), next(nullptr) {} 10 | ListNode(int x) : val(x), next(nullptr) {} 11 | ListNode(int x, ListNode *next) : val(x), next(next) {} 12 | }; 13 | 14 | class Solution 15 | { 16 | public: 17 | ListNode *rotateRight(ListNode *head, int k) 18 | { 19 | 20 | if (!head || !head->next) 21 | return head; 22 | 23 | int n = 1; 24 | ListNode *temp = head; 25 | while (temp->next) 26 | { 27 | n++; 28 | temp = temp->next; 29 | } 30 | 31 | temp->next = head; 32 | 33 | k = k % n; 34 | k = n - k; 35 | while (k-- > 0) 36 | { 37 | temp = temp->next; 38 | } 39 | 40 | head = temp->next; 41 | 42 | temp->next = nullptr; 43 | 44 | return head; 45 | } 46 | }; 47 | 48 | int main() 49 | { 50 | 51 | // call the fn here 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/61. Rotate List/sol.java: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | int val; 3 | ListNode next; 4 | 5 | ListNode() { 6 | } 7 | 8 | ListNode(int val) { 9 | this.val = val; 10 | } 11 | 12 | ListNode(int val, ListNode next) { 13 | this.val = val; 14 | this.next = next; 15 | } 16 | } 17 | 18 | public class sol { 19 | public static void main(String[] args) { 20 | // call the fn here 21 | } 22 | 23 | class Solution { 24 | public ListNode rotateRight(ListNode head, int k) { 25 | 26 | if (head == null || head.next == null) { 27 | return head; 28 | } 29 | 30 | int n = 1; 31 | ListNode temp = head; 32 | while (temp.next != null) { 33 | n++; 34 | temp = temp.next; 35 | } 36 | 37 | temp.next = head; 38 | 39 | k = k % n; 40 | k = n - k; 41 | while (k-- > 0) { 42 | temp = temp.next; 43 | } 44 | 45 | head = temp.next; 46 | 47 | temp.next = null; 48 | 49 | return head; 50 | } 51 | } 52 | 53 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/61. Rotate List/sol.md: -------------------------------------------------------------------------------- 1 | 1. If the linked list is empty or has only one node, then return the head of the linked list. 2 | 2. Calculate the length of the linked list. 3 | 3. Set the `next` pointer of the last node in the linked list to the head of the linked list. 4 | 4. Calculate the new head of the linked list by moving `k` nodes from the end of the linked list. 5 | 5. Set the `next` pointer of the node before the new head to `null`. 6 | 6. Return the new head of the linked list. 7 | 8 | **Example:** 9 | 10 | Consider the following linked list: 11 | 12 | head -> 1 -> 2 -> 3 -> 4 -> 5 13 | 14 | and the value `k = 2`. 15 | 16 | The algorithm will work as follows: 17 | 18 | 1. Calculate the length of the linked list, which is 5. 19 | 2. Set the `next` pointer of the last node in the linked list (node 5) to the head of the linked list (node 1). 20 | 3. Calculate the new head of the linked list by moving 2 nodes from the end of the linked list. The new head is node 4. 21 | 4. Set the `next` pointer of the node before the new head (node 3) to `null`. 22 | 5. Return the new head of the linked list, which is node 4. 23 | 24 | The output of the algorithm is the following linked list: 25 | 26 | 4 -> 5 -> 1 -> 2 -> 3 -> null 27 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/62. Unique Paths/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public int uniquePaths(int m, int n) { 8 | int[][] temp = new int[m][n]; 9 | 10 | for (int i = 0; i < m; i++) { 11 | temp[i][0] = 1; 12 | } 13 | for (int j = 0; j < n; j++) { 14 | temp[0][j] = 1; 15 | } 16 | 17 | for (int i = 1; i < m; i++) { 18 | for (int j = 1; j < n; j++) { 19 | temp[i][j] = temp[i - 1][j] + temp[i][j - 1]; 20 | } 21 | } 22 | 23 | return temp[m - 1][n - 1]; 24 | } 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/62. Unique Paths/sol.md: -------------------------------------------------------------------------------- 1 | Summary of the algorithm: 2 | 3 | 1. Create a 2D array, `temp`, to store the number of unique paths to each cell in the grid. 4 | 2. Initialize the first row and column of `temp` to 1, since there is only one unique path to each cell in the first row and column. 5 | 3. Iterate over the remaining rows and columns of `temp`: 6 | * For each cell, calculate the number of unique paths to the cell by adding the number of unique paths to the cell to the left and the number of unique paths to the cell above. 7 | 4. Return the value of the last cell in `temp`, which is the number of unique paths to the bottom-right corner of the grid. 8 | 9 | This algorithm works by filling in the `temp` array row-by-row, starting with the first row. For each cell in the `temp` array, the algorithm calculates the number of unique paths to the cell by adding the number of unique paths to the cell to the left and the number of unique paths to the cell above. This is because the only way to reach a cell is to come from the left or from above. 10 | 11 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/63. Unique Paths II/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3 | if(obstacleGrid[0][0] == 1) return 0; 4 | int endRow = obstacleGrid.length; 5 | int endCol = obstacleGrid[0].length; 6 | int[][] grid = new int[endRow][endCol]; 7 | for(int i = 0; i < endRow; i++){ 8 | if(obstacleGrid[i][0] == 1){ 9 | grid[i][0] = 0; 10 | break; 11 | } 12 | else 13 | grid[i][0] = 1; 14 | } 15 | for(int j = 0; j < endCol; j++){ 16 | if(obstacleGrid[0][j] == 1){ 17 | grid[0][j] = 0; 18 | break; 19 | } 20 | else 21 | grid[0][j] = 1; 22 | } 23 | for(int i = 1; i < endRow; i++){ 24 | for(int j = 1; j < endCol; j++){ 25 | if(obstacleGrid[i][j] == 1) 26 | grid[i][j] = 0; 27 | else 28 | grid[i][j] = grid[i - 1][j] + grid[i][j - 1]; 29 | } 30 | } 31 | return grid[endRow - 1][endCol - 1]; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/7. Reverse Integer/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int reverse(int x) 10 | { 11 | 12 | string s = to_string(x); 13 | 14 | string reversed; 15 | int start = s[0] == '-' ? 1 : 0; 16 | 17 | for (int i = s.length() - 1; i >= start; i--) 18 | { 19 | reversed += s[i]; 20 | } 21 | 22 | try 23 | { 24 | return x >= 0 ? stoi(reversed) : -stoi(reversed); 25 | } 26 | catch (exception e) 27 | { 28 | return 0; 29 | } 30 | } 31 | }; 32 | 33 | int main() 34 | { 35 | // call the fn here 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /LeetCode Questions/Medium/7. Reverse Integer/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public int reverse(int x) { 8 | String s = String.valueOf(x); 9 | StringBuilder reversed = new StringBuilder(); 10 | 11 | int start = s.charAt(0) == '-' ? 1 : 0; 12 | 13 | for (int i = s.length() - 1; i >= start; i--) { 14 | reversed.append(s.charAt(i)); 15 | } 16 | 17 | try { 18 | return x >= 0 ? Integer.parseInt(reversed.toString()) : -Integer.parseInt(reversed.toString()); 19 | } catch (NumberFormatException e) { 20 | return 0; 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/7. Reverse Integer/sol.md: -------------------------------------------------------------------------------- 1 | 1. Convert the input integer `x` to a string `s`. 2 | 2. Create a new StringBuilder `reversed` to store the reversed string. 3 | 3. Iterate over the string `s` from the end to the beginning and append each character to the StringBuilder `reversed`. 4 | 4. If the first character of the string `s` is `-`, then append a `-` sign to the StringBuilder `reversed`. 5 | 5. Try to convert the StringBuilder `reversed` to an integer. 6 | 6. If the conversion is successful, return the integer. Otherwise, return 0. 7 | 8 | Time complexity: O(n) 9 | The time complexity is O(n) because the function needs to iterate over the input string once to reverse it. 10 | 11 | Space complexity: O(n) 12 | The space complexity is O(n) because the function needs to store the reversed string in the StringBuilder object. 13 | 14 | **Example:** 15 | 16 | Consider the following input integer `x`: 17 | 18 | x = 123 19 | 20 | The string `s` after the conversion is as follows: 21 | 22 | s = "123" 23 | 24 | The StringBuilder `reversed` after the iteration over the string `s` is as follows: 25 | 26 | reversed = "321" 27 | 28 | The integer `reversedInt` after the conversion is as follows: 29 | 30 | reversedInt = 321 31 | 32 | Since the conversion is successful, the function returns the integer `reversedInt`, which is 321. 33 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/725. Split List in Parts/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class ListNode { 4 | int val; 5 | ListNode next; 6 | 7 | ListNode() { 8 | } 9 | 10 | ListNode(int val) { 11 | this.val = val; 12 | } 13 | 14 | ListNode(int val, ListNode next) { 15 | this.val = val; 16 | this.next = next; 17 | } 18 | } 19 | 20 | public class sol { 21 | public static void main(String[] args) { 22 | // call the fn here 23 | } 24 | 25 | public class Solution { 26 | public ListNode[] splitListToParts(ListNode head, int k) { 27 | int length = 0; 28 | ListNode current = head; 29 | List parts = new ArrayList<>(); 30 | 31 | while (current != null) { 32 | length++; 33 | current = current.next; 34 | } 35 | 36 | int base_size = length / k, extra = length % k; 37 | current = head; 38 | 39 | for (int i = 0; i < k; i++) { 40 | int part_size = base_size + (extra > 0 ? 1 : 0); 41 | ListNode part_head = null, part_tail = null; 42 | 43 | for (int j = 0; j < part_size; j++) { 44 | if (part_head == null) { 45 | part_head = part_tail = current; 46 | } else { 47 | part_tail.next = current; 48 | part_tail = part_tail.next; 49 | } 50 | 51 | if (current != null) { 52 | current = current.next; 53 | } 54 | } 55 | 56 | if (part_tail != null) { 57 | part_tail.next = null; 58 | } 59 | 60 | parts.add(part_head); 61 | extra = Math.max(extra - 1, 0); 62 | } 63 | 64 | return parts.toArray(new ListNode[0]); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/725. Split List in Parts/sol.md: -------------------------------------------------------------------------------- 1 | Calculate the length of the linked list. 2 | Initialize two counters, base_size and extra, to the length of the linked list divided by k and the remainder of the division, respectively. 3 | Initialize a pointer, current, to the head of the linked list. 4 | Iterate over the range [0, k - 1]: 5 | Initialize two pointers, part_head and part_tail, to null. 6 | Iterate over the range [0, base_size + (extra > 0 ? 1 : 0) - 1]: 7 | If part_head is null, then set part_head and part_tail to the current node. 8 | Otherwise, set part_tail.next to the current node and update part_tail to the current node. 9 | Update current to the next node in the linked list. 10 | Set part_tail.next to null. 11 | Add part_head to the list of parts. 12 | Decrement extra by 1. 13 | Return the list of parts. 14 | 15 | 16 | This algorithm works by greedily splitting the linked list into k parts of approximately equal size. The base_size variable represents the number of nodes in each part, and the extra variable represents the number of extra nodes that are added to the first extra parts. The algorithm iterates over the linked list, adding each node to the current part until the part is full. Then, the algorithm starts a new part and repeats the process. -------------------------------------------------------------------------------- /LeetCode Questions/Medium/8. String to Integer (atoi)/Solution.js: -------------------------------------------------------------------------------- 1 | const myAtoi = function(str) { 2 | if(str.length===0||!(parseInt(str)*parseInt(str)>=0)){ 3 | return 0; 4 | } 5 | if(parseInt(str)>2147483647){ 6 | return 2147483647; 7 | } 8 | if(parseInt(str)<-2147483648){ 9 | return -2147483648; 10 | } 11 | return parseInt(str); 12 | }; -------------------------------------------------------------------------------- /LeetCode Questions/Medium/967. Numbers With Same Consecutive Differences/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector numsSameConsecDiff(int n, int k) { 4 | if(n == 1) return vector{k}; 5 | vector list; 6 | int min = pow(10, n - 1); 7 | for(int i = 1; i < 10; i++){ 8 | queue q; 9 | q.push(i); 10 | while(!q.empty()){ 11 | int num = q.front(); 12 | q.pop(); 13 | if(num >= min){ 14 | list.push_back(num); 15 | continue; 16 | } 17 | int x = num % 10; 18 | if(k > 0 && x - k >= 0) 19 | q.push(num * 10 + x - k); 20 | if(x + k < 10) 21 | q.push(num * 10 + x + k); 22 | } 23 | } 24 | return list; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/967. Numbers With Same Consecutive Differences/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] numsSameConsecDiff(int n, int k) { 3 | if(n == 1) return new int[]{k}; 4 | List list = new ArrayList(); 5 | int min = (int) Math.pow(10, n - 1); 6 | for(int i = 1; i < 10; i++){ 7 | Queue q = new LinkedList(); 8 | q.add(i); 9 | while(!q.isEmpty()){ 10 | int num = q.poll(); 11 | if (num >= min){ 12 | list.add(num); 13 | continue; 14 | } 15 | int x = num%10; 16 | if(k > 0 && x - k >= 0) 17 | q.add(num * 10 + x - k); 18 | if(x + k < 10) 19 | q.add(num * 10 + x + k); 20 | } 21 | } 22 | return list.stream() 23 | .mapToInt(i -> i) 24 | .toArray(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/967. Numbers With Same Consecutive Differences/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numsSameConsecDiff(self, n: int, k: int) -> List[int]: 3 | list = [] 4 | min = pow(10, n - 1) 5 | for i in range (1, 10): 6 | q = [i] 7 | while len(q): 8 | num = q.pop(0) 9 | if num >= min: 10 | list.append(num) 11 | continue 12 | x = num % 10 13 | if k > 0 and x - k >= 0: 14 | q.append(num * 10 + x - k) 15 | if x + k < 10: 16 | q.append(num * 10 + x + k) 17 | return list 18 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/974. Subarray Sums Divisible by K/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int subarraysDivByK(vector& nums, int k) { 4 | int n = nums.size(); 5 | unordered_map map; 6 | int sum = 0; 7 | int count = 0; 8 | for(int i = 0; i < n; i++) { 9 | sum += nums[i]; 10 | if(sum % k == 0) count++; 11 | int rem = sum % k; 12 | if(rem < 0) rem += k; 13 | if(map[rem]) count += map[rem]; 14 | map[rem] = map[rem] + 1; 15 | } 16 | return count; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/974. Subarray Sums Divisible by K/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subarraysDivByK(int[] arr, int k) { 3 | int n = arr.length; 4 | HashMap map = new HashMap<>(); 5 | int sum = 0; 6 | int count = 0; 7 | for(int i = 0; i int: 3 | n = len(nums) 4 | map = {} 5 | sum = 0 6 | count = 0 7 | for i in range(n): 8 | sum = sum + nums[i] 9 | if sum % k == 0: count = count + 1 10 | rem = sum % k 11 | if rem < 0: rem = rem + k 12 | if map.get(rem): 13 | count = count + map[rem] 14 | map[rem] = map[rem] + 1 15 | else: 16 | map[rem] = 1 17 | return count 18 | -------------------------------------------------------------------------------- /LeetCode Questions/Medium/README.md: -------------------------------------------------------------------------------- 1 | # Problems ![MEDIUM](https://img.shields.io/badge/-MEDIUM-ffa116?style=for-the-badge&logo=LeetCode&logoColor=black) 2 | 3 | | **No.** | **Problem** | 4 | | :------: | :------------------------------------------------------------------------------------------------------------ | 5 | | **11** | [Container With Most Water](11.%20Container%20With%20Most%20Water/) | 6 | | **36** | [Valid Sudoku](36.%20Valid%20Sudoku/) | 7 | | **48** | [Rotate Image](48.%20Rotate%20Image/) | 8 | | **63** | [Unique Paths II](63.%20Unique%20Paths%20II/) | 9 | | **200** | [Number of Islands](200.%20Number%20of%20Islands/) | 10 | | **429** | [N-ary Tree Level Order Traversal](429.%20N-ary%20Tree%20Level%20Order%20Traversal/) | 11 | | **814** | [Binary Tree Pruning](814.%20Binary%20Tree%20Pruning/) | 12 | | **967** | [Numbers With Same Consecutive Differences](967.%20Numbers%20With%20Same%20Consecutive%20Differences/) | 13 | | **974** | [Subarray Sums Divisible by K](974.%20Subarray%20Sums%20Divisible%20by%20K/) | 14 | | **1448** | [Count Good Nodes in Binary Tree](1448.%20Count%20Good%20Nodes%20in%20Binary%20Tree/) | 15 | | **1996** | [The Number of Weak Characters in the Game](1996.%20The%20Number%20of%20Weak%20Characters%20in%20the%20Game/) | 16 | -------------------------------------------------------------------------------- /Other-code/Armstrong.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int num, originalNum, remainder, result = 0; 6 | cout << "Enter a three-digit integer: "; 7 | cin >> num; 8 | originalNum = num; 9 | 10 | while (originalNum != 0) { 11 | // remainder contains the last digit 12 | remainder = originalNum % 10; 13 | 14 | result += remainder * remainder * remainder; 15 | 16 | // removing last digit from the original number 17 | originalNum /= 10; 18 | } 19 | 20 | if (result == num) 21 | cout << num << " is an Armstrong number."; 22 | else 23 | cout << num << " is not an Armstrong number."; 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /Other-code/Calculator.java: -------------------------------------------------------------------------------- 1 | 2 | public class Calculator { 3 | 4 | public static int add( int a, int b) { 5 | return a+b; 6 | } 7 | 8 | public static double add( double a, double b) { 9 | return a+b; 10 | } 11 | 12 | public static double add( double a, int b) { 13 | return a+b; 14 | } 15 | 16 | public static double add( int a, double b) { 17 | return a+b; 18 | } 19 | 20 | public static void main(String[] Args) { 21 | System.out.println(" 7 + 3 = " + add(7, 3)); 22 | System.out.println(" 8.1 + 1.9 = " + add(8.1, 1.9)); 23 | System.out.println(" 6.5 + 3 = " + add(6.5, 3)); 24 | System.out.println(" 7 + 3.8 = " + add(7, 3.8)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Other-code/EquilibriumPoint.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | /** 3 | * Solution for the Equilibrium point problem from GeeksforGeeks.org 4 | * 5 | */ 6 | public class EquilibriumPoint { 7 | public static void main(String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | System.out.print("Enter the length of the array : "); 10 | int ar[] = new int[sc.nextInt()]; 11 | System.out.println("Enter the array : "); 12 | for (int i = 0; i < ar.length; i++) { 13 | System.out.printf("Enter element %d : ",i+1); 14 | ar[i] = sc.nextInt(); 15 | } 16 | for (int i = 0; i < ar.length; i++) { 17 | int sum1 = 0, sum2 = 0; 18 | for(int j = 0; j < i; j++) 19 | { 20 | sum1 = sum1 + ar[j]; 21 | } 22 | for(int k = i+1; k < ar.length; k++) 23 | { 24 | sum2 = sum2 + ar[k]; 25 | } 26 | if(sum1 == sum2) 27 | { 28 | System.out.println("Your array : "); 29 | for (int elem : ar) { 30 | System.out.print(elem+" "); 31 | } 32 | System.out.println("\nEquilibrium Point = "+(i+1)); 33 | break; 34 | } 35 | } 36 | sc.close(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Other-code/addNum.java: -------------------------------------------------------------------------------- 1 | // Add two numbers in Java using command line arguments 2 | 3 | public class AddTwoNumbers { 4 | public static void main(String[] args) { 5 | // Get the command line arguments. 6 | int num1 = Integer.parseInt(args[0]); 7 | int num2 = Integer.parseInt(args[1]); 8 | 9 | // Add the two numbers. 10 | int sum = num1 + num2; 11 | 12 | // Print the result to the console. 13 | System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum); 14 | } 15 | } 16 | 17 | // ------------------------------------------------------------------------------------------------------ 18 | /* 19 | To compile and run this program, you can use the following commands in the terminal/console: 20 | 21 | 1. javac AddTwoNumbers.java --> (promt to compile the file) 22 | 2. java AddTwoNumbers 10 20 --> (prompt to run) 23 | 24 | This will print the following output to the console: " The sum of 10 and 20 is 30 " 25 | 26 | 💡 You can also use command line arguments to pass more than two numbers to the program. 27 | For example, to add three numbers, you can use the following command: 28 | java AddTwoNumbers 10 20 30 29 | 30 | This will print the following output to the console: 31 | " The sum of 10 and 20 and 30 is 60 " 32 | 33 | */ 34 | // ------------------------------------------------------------------------------------------------------ 35 | 36 | // Happy Coding 👨🏽‍💻 -------------------------------------------------------------------------------- /Other-code/binaryToDecimalAndViceversa.cpp: -------------------------------------------------------------------------------- 1 | // convert binary to decimal 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | // function prototype 9 | int convert(long long); 10 | 11 | int main() { 12 | long long n; 13 | cout << "Enter a binary number: "; 14 | cin >> n; 15 | cout << n << " in binary = " << convert(n) << " in decimal"; 16 | return 0; 17 | } 18 | 19 | // function definition 20 | int convert(long long n) { 21 | int dec = 0, i = 0, rem; 22 | 23 | while (n!=0) { 24 | rem = n % 10; 25 | n /= 10; 26 | dec += rem * pow(2, i); 27 | ++i; 28 | } 29 | 30 | return dec; 31 | } 32 | -------------------------------------------------------------------------------- /Other-code/gcd.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int n1, n2, hcf; 6 | cout << "Enter two numbers: "; 7 | cin >> n1 >> n2; 8 | 9 | // swapping variables n1 and n2 if n2 is greater than n1. 10 | if ( n2 > n1) { 11 | int temp = n2; 12 | n2 = n1; 13 | n1 = temp; 14 | } 15 | 16 | for (int i = 1; i <= n2; ++i) { 17 | if (n1 % i == 0 && n2 % i ==0) { 18 | hcf = i; 19 | } 20 | } 21 | 22 | cout << "HCF = " << hcf; 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Other-code/package.java: -------------------------------------------------------------------------------- 1 | package p1; 2 | public class ex 3 | { 4 | public ex() 5 | { 6 | System.out.println("Created"); 7 | } 8 | 9 | public void display() 10 | { 11 | System.out.println("Hello"); 12 | } 13 | } 14 | import p1.*; 15 | class ex1 16 | { 17 | public static void main(String[] a) 18 | { 19 | ex e=new ex(); 20 | e.display(); 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /Other-code/quadratic_equation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int n1, n2, hcf; 6 | cout << "Enter two numbers: "; 7 | cin >> n1 >> n2; 8 | 9 | // swapping variables n1 and n2 if n2 is greater than n1. 10 | if ( n2 > n1) { 11 | int temp = n2; 12 | n2 = n1; 13 | n1 = temp; 14 | } 15 | 16 | for (int i = 1; i <= n2; ++i) { 17 | if (n1 % i == 0 && n2 % i ==0) { 18 | hcf = i; 19 | } 20 | } 21 | 22 | cout << "HCF = " << hcf; 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Other-code/test.java: -------------------------------------------------------------------------------- 1 | //input a matrix. find number x. print indices of x. 2 | import java.util.*; 3 | public class class46 { 4 | public static void main(String args[]){ 5 | Scanner sc=new Scanner(System.in); 6 | System.out.print("Enter the number of rows: "); 7 | int r=sc.nextInt(); 8 | System.out.print("Enter the number of columns: "); 9 | int c=sc.nextInt(); 10 | int [][]matrix=new int[r][c]; 11 | System.out.println("Enter the elements of matrix of size "+r+" x "+c); 12 | for(int i=0;i18){ 6 | System.out.println("You are eligible to vote!"); 7 | }else{ 8 | System.out.println("Sorry, you are not eligible to vote!"); 9 | } 10 | } 11 | public static void main(String args[]){ 12 | Scanner sc=new Scanner(System.in); 13 | System.out.print("Please enter your age: "); 14 | int a=sc.nextInt(); 15 | ageCheck(a); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Question/Q3.4.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class School 3 | { 4 | String name,address,type_of_account; 5 | double balance; 6 | School() 7 | { 8 | } 9 | 10 | School(String name, String address, String type_of_account, double balance) 11 | { 12 | this.name = name; 13 | this.address = address; 14 | this.type_of_account = type_of_account; 15 | this.balance = balance; 16 | } 17 | 18 | void display(School data) 19 | { 20 | System.out.println("The name is "+data.name); 21 | System.out.println("The address is "+data.address); 22 | System.out.println("The type of account is "+data.type_of_account); 23 | System.out.println("The balance is "+data.balance); 24 | } 25 | 26 | } 27 | 28 | public class Main 29 | { 30 | public static void main(String[] args) { 31 | Scanner sc=new Scanner(System.in); 32 | System.out.println("Enter number of students"); 33 | int n = sc.nextInt(); 34 | School arr[] = new School[n]; 35 | for(int i = 1; i <= n; i++) 36 | { 37 | System.out.println("Enter the name, address, type of account and balance of the student "+(i)); 38 | String name = sc.next(); 39 | String address = sc.next(); 40 | String type_of_account = sc.next(); 41 | double balance = sc.nextDouble(); 42 | arr[i-1] = new School(name,address,type_of_account,balance); 43 | } 44 | System.out.println("Enter the name of the student whose information to be displayed"); 45 | String find_name = sc.next(); 46 | School nm=new School(); 47 | int flag=0; 48 | for(int i=0;i 0) { 25 | array[index++] = i; 26 | count[i]--; 27 | } 28 | } 29 | } 30 | 31 | public static void main(String[] args) { 32 | int[] array = {4, 2, 2, 8, 3, 3, 1}; 33 | System.out.println("Original array: " + Arrays.toString(array)); 34 | 35 | countingSort(array); 36 | 37 | System.out.println("Sorted array: " + Arrays.toString(array)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /java-sorting/SelecgtionSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class SelectionSort { 4 | 5 | public static void selectionSort(int[] array) { 6 | int n = array.length; 7 | 8 | // Traverse through all array elements 9 | for (int i = 0; i < n - 1; i++) { 10 | // Find the minimum element in the remaining unsorted array 11 | int minIndex = i; 12 | for (int j = i + 1; j < n; j++) { 13 | if (array[j] < array[minIndex]) { 14 | minIndex = j; 15 | } 16 | } 17 | 18 | // Swap the found minimum element with the first element 19 | if (minIndex != i) { 20 | int temp = array[i]; 21 | array[i] = array[minIndex]; 22 | array[minIndex] = temp; 23 | } 24 | } 25 | } 26 | 27 | public static void main(String[] args) { 28 | int[] array = {64, 25, 12, 22, 11}; 29 | System.out.println("Original array: " + Arrays.toString(array)); 30 | 31 | selectionSort(array); 32 | 33 | System.out.println("Sorted array: " + Arrays.toString(array)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /pattern/HollowDiamond.java: -------------------------------------------------------------------------------- 1 | public class hollow { 2 | public static void main(String[] args){ 3 | Scanner sc=new Scanner(System.in); 4 | int n=sc.nextInt(); 5 | 6 | 7 | for(int i=1;i<=n;i++){ 8 | 9 | for(int j=n-i;j>=0;j--){ 10 | System.out.print("*"); 11 | } 12 | 13 | for(int k=2*(i-1);k>0;k--){ 14 | System.out.print(" "); 15 | } 16 | for(int l=n-i;l>=0;l--){ 17 | System.out.print("*"); 18 | } 19 | System.out.println(); 20 | } 21 | 22 | for(int i=0;i0;k--){ 27 | System.out.print(" "); 28 | } 29 | for(int m=0;m<=i;m++){ 30 | System.out.print("*"); 31 | } 32 | System.out.println(); 33 | } 34 | } 35 | 36 | } 37 | --------------------------------------------------------------------------------