├── 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