From 03d3355423f79c797b10e2a18f9ba1a2e301db0e Mon Sep 17 00:00:00 2001 From: shivaagaur00 Date: Tue, 12 Nov 2024 21:58:07 +0530 Subject: [PATCH 1/5] Assignment shivagaur 2215001353 --- Factorial.java | 15 ++ NaturalSum.java | 17 +++ Nthfibonacii.java | 13 ++ PowerOf2.java | 20 +++ README.md | 362 ---------------------------------------------- Stopwatch.java | 14 ++ binarySearch.java | 13 ++ count.java | 10 ++ listpair.java | 4 + 9 files changed, 106 insertions(+), 362 deletions(-) create mode 100644 Factorial.java create mode 100644 NaturalSum.java create mode 100644 Nthfibonacii.java create mode 100644 PowerOf2.java delete mode 100644 README.md create mode 100644 Stopwatch.java create mode 100644 binarySearch.java create mode 100644 count.java create mode 100644 listpair.java diff --git a/Factorial.java b/Factorial.java new file mode 100644 index 00000000..262240f7 --- /dev/null +++ b/Factorial.java @@ -0,0 +1,15 @@ +package ShivaGaur_2215001653_TBPPP; +import java.util.*; +public class Factorial { + public static void main(String[] args) { + Scanner sc=new Scanner(System.in); + int n=sc.nextInt(); + System.out.println(fact(n)); + } + public static int fact(int n){ + if(n==1 || n==0){ + return 1; + } + return n*fact(n-1); + } +} diff --git a/NaturalSum.java b/NaturalSum.java new file mode 100644 index 00000000..ce8fb531 --- /dev/null +++ b/NaturalSum.java @@ -0,0 +1,17 @@ +package ShivaGaur_2215001653_TBPPP; +import java.util.*; +public class NaturalSum { + public static void main(String[] args) { + Scanner sc=new Scanner(System.in); + int n=sc.nextInt(); + func(n,1); + } + public static void func(int n,int n2){ + if(n==n2){ + System.out.print(n2); + return; + } + System.out.print(n2+"+"); + func(n, n2+1); + } +} diff --git a/Nthfibonacii.java b/Nthfibonacii.java new file mode 100644 index 00000000..9e7eff2d --- /dev/null +++ b/Nthfibonacii.java @@ -0,0 +1,13 @@ +package ShivaGaur_2215001653_TBPPP; +import java.util.*; +public class Nthfibonacii { + public static void main(String[] args) { + Scanner sc=new Scanner(System.in); + int n=sc.nextInt(); + System.out.println(func(n)); + } + public static int func(int n){ + if(n==0 || n==1) return 1; + return func(n-1)+func(n-2); + } +} diff --git a/PowerOf2.java b/PowerOf2.java new file mode 100644 index 00000000..6f3127e2 --- /dev/null +++ b/PowerOf2.java @@ -0,0 +1,20 @@ +package ShivaGaur_2215001653_TBPPP; + +public class PowerOf2 { + public static void main(String[] args) { + PowerOf2 p = new PowerOf2(); + int num = 16; + if (p.isPowerOfTwo(num)) { + System.out.println(num + " is a power of 2."); + } else { + System.out.println(num + " is not a power of 2."); + } + } + + public boolean isPowerOfTwo(int n) { + if (n <= 0) { + return false; + } + return (n & (n - 1)) == 0; + } +} diff --git a/README.md b/README.md deleted file mode 100644 index bc9b5590..00000000 --- a/README.md +++ /dev/null @@ -1,362 +0,0 @@ -# DSA-Task- - -# For Any Doubt 💬 - -Reach out to *Piyush* at *6397415707* Or *Parth* at *9559805577*. -# Week 2 Task: The Beauty of Binary Search 🚀 - -# Ultimate Guide to Binary Search - -Binary Search is one of the most fundamental and efficient searching algorithms. It operates on the principle of **divide and conquer**, allowing you to solve a problem by repeatedly halving the search space. This guide will provide you with everything you need to know about Binary Search, from the basics to advanced topics, along with templates and practice problems. - ---- - -## Table of Contents - -1. [Introduction to Binary Search](#introduction-to-binary-search) -2. [When to Use Binary Search](#when-to-use-binary-search) -3. [Recognizing a Binary Search Problem](#recognizing-a-binary-search-problem) -4. [Upper Bound and Lower Bound](#upper-bound-and-lower-bound) -5. [Binary Search on Answer](#binary-search-on-answer) -6. [Templates for Binary Search](#templates-for-binary-search) -7. [Practice Questions](#practice-questions) - ---- - -## Introduction to Binary Search - -Binary Search is a searching technique used on **sorted arrays or ranges** to find an element or a condition. The algorithm works by dividing the search space into two halves, checking the middle element, and eliminating half of the search space based on the comparison. - -### Key Properties: -- **Input Requirement**: The array or range must be sorted. -- **Efficiency**: The time complexity is **O(log n)**, which makes Binary Search much faster than a linear search, especially for large datasets. - ---- - -## When to Use Binary Search - -### Indicators of Binary Search Problems: -- **Sorted Data**: When the input is sorted (increasing, decreasing, or even rotated), Binary Search is likely applicable. -- **Search for Extremes**: When you're tasked with finding a minimum, maximum, or something like "first occurrence", "last occurrence". -- **Range Queries**: Problems asking for a specific range, such as finding the lower or upper bound. -- **Optimization Problems**: When minimizing or maximizing a value is the goal, Binary Search can often be applied on the answer space. - -### Common Scenarios: -- Searching for an element in a sorted array. -- Finding the first or last occurrence of an element. -- Optimizing time, distance, or other criteria where you are asked to "minimize" or "maximize" something. - ---- - -## Recognizing a Binary Search Problem - -Many problems aren't directly presented as Binary Search problems, but with practice, you'll start to recognize common patterns. - -#### Ask yourself: -1. **Is the input sorted or can it be treated as sorted?** -2. **Can I break down the problem by halving the search space?** -3. **Am I trying to find a value that satisfies a certain condition (minimum/maximum, first/last occurrence)?** -4. **Is the problem asking me to minimize or maximize something?** - -If any of these questions apply, Binary Search could be a potential solution. - ---- - -## Upper Bound and Lower Bound - -### **Lower Bound**: -The smallest index where the target is greater than or equal to a value. Useful when finding the first occurrence or the smallest element that satisfies a condition. - -### **Upper Bound**: -The first index where an element is strictly greater than the target. Useful when finding ranges of elements or when checking the validity of a range. - -### Applications of UB and LB: -- **Range Queries**: Find the number of occurrences of a specific element. -- **Positioning**: Used to find the insert position in sorted arrays. - -### Example (Lower Bound in Java): -```java -public int lowerBound(int[] nums, int target) { - int low = 0, high = nums.length; - while (low < high) { - int mid = low + (high - low) / 2; - if (nums[mid] < target) { - low = mid + 1; - } else { - high = mid; - } - } - return low; -} -``` -### Example (Upper Bound in Java): -```java -public int upperBound(int[] nums, int target) { - int low = 0, high = nums.length; - while (low < high) { - int mid = low + (high - low) / 2; - if (nums[mid] <= target) { - low = mid + 1; - } else { - high = mid; - } - } - return low; -} -``` - -# Binary Search on Answer - -Binary Search isn't always used on arrays. In some problems, we need to search for the answer itself. This is called **Binary Search on the Answer**, where the search space is a range of potential answers, and we determine whether a particular value satisfies a condition. - -## Examples -- **Minimizing Maximum Distance:** Find the maximum minimum distance between elements. -- **Minimizing Time or Cost:** Solve problems like minimizing the maximum load, distance, or time. - -## How to Identify -- The problem asks for the minimum/maximum of some criteria. -- You need to satisfy certain conditions by varying the possible answers. - -## Example: Binary Search on Answer Template in Java - -```java -public boolean canSatisfyCondition(int mid, int[] conditions) { - // Implement the logic to check if mid satisfies the problem's conditions. - return true; // or false depending on whether the condition is satisfied -} - -public int binarySearchOnAnswer(int[] arr) { - int low = 1, high = arr.length, answer = -1; - while (low <= high) { - int mid = low + (high - low) / 2; - if (canSatisfyCondition(mid, arr)) { - answer = mid; // Update answer if condition is met - high = mid - 1; // Adjust for minimizing - } else { - low = mid + 1; // Adjust for maximizing - } - } - return answer; -} -``` -# Binary Search Templates - -## Standard Binary Search -Use this template when searching for an element in a sorted array. - -```java -public int binarySearch(int[] nums, int target) { - int low = 0, high = nums.length - 1; - while (low <= high) { - int mid = low + (high - low) / 2; - if (nums[mid] == target) { - return mid; // Element found - } else if (nums[mid] < target) { - low = mid + 1; - } else { - high = mid - 1; - } - } - return -1; // Element not found -} -``` -# Binary Search on Answer Template - -This template is useful for problems that involve minimizing or maximizing a result. It provides a structured approach to implement binary search over a defined range. - -## Code Template - -The following Java code demonstrates the basic structure for performing a binary search on a specified range. - -```java -public int binarySearchOnRange(int low, int high, int[] arr) { - int answer = -1; - while (low <= high) { - int mid = low + (high - low) / 2; - if (isValid(mid, arr)) { - answer = mid; - high = mid - 1; // Minimizing answer - } else { - low = mid + 1; - } - } - return answer; -} - -public boolean isValid(int mid, int[] arr) { - // Implement problem-specific condition - return true; // Change this based on your criteria -} -``` - -## Explanation - -- **`binarySearchOnRange(int low, int high, int[] arr)`**: - - This method performs binary search within the range defined by `low` and `high` indices. - - It initializes the variable `answer` to keep track of the most recent valid `mid` value that meets the conditions specified in the `isValid` method. - - The search continues as long as `low` is less than or equal to `high`. The midpoint `mid` is calculated, and if it is valid, `answer` is updated, and the search space is narrowed to the lower half (`high = mid - 1`). If it is not valid, the search space is adjusted to the upper half (`low = mid + 1`). - -- **`isValid(int mid, int[] arr)`**: - - This method is a placeholder that needs to be customized to implement the specific conditions required by the problem at hand. - - It should return a boolean value indicating whether the current `mid` value satisfies the necessary criteria. - - -## Practice Questions - -### Easy Questions -1. [Binary Search](https://leetcode.com/problems/binary-search/) -2. [Search Insert Position](https://leetcode.com/problems/search-insert-position/) -3. [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) -4. [Sqrt(x)](https://leetcode.com/problems/sqrtx/) -5. [First Bad Version](https://leetcode.com/problems/first-bad-version/) -6. [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) -7. [Find Smallest Letter Greater Than Target](https://leetcode.com/problems/find-smallest-letter-greater-than-target/) - -### Medium Questions -1. [Find First and Last Position of Element in Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/) -2. [Find Peak Element](https://leetcode.com/problems/find-peak-element/) -3. [Koko Eating Bananas](https://leetcode.com/problems/koko-eating-bananas/) -4. [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) -5. [Minimum Speed to Arrive on Time](https://leetcode.com/problems/minimum-speed-to-arrive-on-time/) -6. [Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/) - -### Hard Questions -1. [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) -2. [Find in Mountain Array](https://leetcode.com/problems/find-in-mountain-array/) -3. [Find a Peak Element II](https://leetcode.com/problems/find-a-peak-element-ii/) - -### Classical Problems -1. [Aggressive Cows (SPOJ)](https://www.spoj.com/problems/aggrcows/) -2. [Painter Partition Problem (GFG)](https://www.geeksforgeeks.org/painter-partition-problem/) - - - ---- - -# Week 1 Task: Let's Master "Subarray" Related Problems 🚀 - -## 1. Understand the Problem Clearly: - -- Carefully read the problem and break it down. -- Are you asked to find a subarray with certain properties (e.g., smallest, largest sum, divisible sum)? -- Are you asked to maximize, minimize, or check for the existence of a condition? -- Does the problem allow for negative numbers or only positive ones? - -Understanding these questions is the first step towards identifying which algorithm or technique might work best for solving the problem. - ---- - -## 2. Analyze the Subarray Nature: - -Subarrays are contiguous parts of an array, and different categories of subarray-related problems exist. -- *Key Point*: Each category has specific patterns and hints towards a particular type of solution, so recognizing the subarray nature in the problem is crucial. - ---- - -## 3. Look for Common Patterns: - -### 1) Sliding Window or Two-Pointer Technique: - -- *When to Use*: - - Finding a subarray with a fixed sum or length. - - Finding a subarray with conditions that can be checked as you move from one end of the array to another. - -- *Why It Works*: This technique is efficient because it processes the array in linear time, expanding and contracting the window as needed. - -- *Common Problem Types*: - - Finding the smallest subarray with a sum greater than X. - - Longest subarray with distinct elements or fixed-length subarrays. - -- *Example*: - - If you’re asked to find the longest subarray with sum ≤ k, sliding window is often the best approach. - ---- - -### 2) Kadane’s Algorithm (Dynamic Programming): - -- *When to Use*: - - Finding the maximum subarray sum. - -- *Why It Works*: - - This algorithm efficiently tracks the maximum subarray sum ending at each index. - - It's optimal as it builds solutions to subproblems (maximum sums ending at earlier indices) and extends them to solve larger problems. - -- *Common Problem Types*: - - Finding the maximum subarray sum, especially when there are no constraints on subarray length or when negative values are allowed. - -- *Example*: - - Given an array, find the maximum sum of any subarray. - ---- - -### 3) Prefix Sum & HashMap: - -- *When to Use*: - - Modulo arithmetic (e.g., sum divisible by a number). - - Checking sums over subarrays (especially when the subarray can be of any size). - -- *Why It Works*: - - The prefix sum allows us to break down a subarray sum into differences between two prefix sums. - - HashMaps are used for fast lookups of previously seen sums, especially useful for problems with conditions like "sum divisible by k." - -- *Common Problem Types*: - - Finding subarrays that sum to k, or removing a subarray to make a sum divisible by a given value. - -- *Example*: - - Find the smallest subarray whose sum is divisible by a number p. - ---- - -## 4. Practice Questions - -### Easy Problems: - -1. [Assign Cookies](https://leetcode.com/problems/assign-cookies/) -2. [Buy Two Chocolates](https://leetcode.com/problems/buy-two-chocolates/) -3. [Count Elements with Maximum Frequency](https://leetcode.com/problems/count-elements-with-maximum-frequency/) -4. [Divide Array into Arrays with Max Difference](https://leetcode.com/problems/divide-array-into-arrays-with-max-difference/) -5. [Find Common Characters](https://leetcode.com/problems/find-common-characters/) -6. [Lemonade Change](https://leetcode.com/problems/lemonade-change/) -7. [Minimum Common Value](https://leetcode.com/problems/minimum-common-value/) - ---- - -### Two-Pointer Problems: - -1. [3Sum](https://leetcode.com/problems/3sum/) -2. [3Sum Closest](https://leetcode.com/problems/3sum-closest/) -3. [Longest Mountain in Array](https://leetcode.com/problems/longest-mountain-in-array/) -4. [Maximum Erasure Value](https://leetcode.com/problems/maximum-erasure-value/) -5. [Max Consecutive Ones II](https://leetcode.com/problems/max-consecutive-ones-ii/) - ---- - -### Prefix Sum Problems: - -1. [Contiguous Array](https://leetcode.com/problems/contiguous-array/) -2. [Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/) -3. [Count Number of Nice Subarrays](https://leetcode.com/problems/count-number-of-nice-subarrays) -4. [Find Pivot Index](https://leetcode.com/problems/find-pivot-index/) -5. [K-radius Subarray Averages](https://leetcode.com/problems/k-radius-subarray-averages/) - ---- - -## 5. Let's Solve Some Problems: - -### Leetcode Problems: - -1. [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) -2. [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) -3. [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/description/) -4. [Count Number of Nice Subarrays](https://leetcode.com/problems/count-number-of-nice-subarrays/description/) - -### OA Problem: - -1. LinkedIn - SDE Intern: - - *Question*: Given a list of words, if any two adjacent characters in a word are equal, change one of them. Determine the minimum number of substitutions so the final string contains no adjacent equal characters. - - Example: - Input: ['add', 'boook', 'break'] - Output: [1, 1, 0] - ---- diff --git a/Stopwatch.java b/Stopwatch.java new file mode 100644 index 00000000..471b3402 --- /dev/null +++ b/Stopwatch.java @@ -0,0 +1,14 @@ +package ShivaGaur_2215001653_TBPPP; +import java.util.*; +public class Stopwatch { + public static void main(String[] args) { + Scanner sc=new Scanner(System.in); + int n=sc.nextInt(); + count(n,1); + } + public static void count(int n,int n2){ + if(n2>n) return; + count(n,n2+1); + System.out.print(n2+" "); + } +} diff --git a/binarySearch.java b/binarySearch.java new file mode 100644 index 00000000..ec520cd3 --- /dev/null +++ b/binarySearch.java @@ -0,0 +1,13 @@ +package ShivaGaur_2215001653_TBPPP; +// class binarySearch{ +// public static void main(String[] args) { + +// } +// public int func(int []arr,int tar){ +// int i=0; +// int n=arr.length-1; +// while(i Date: Tue, 12 Nov 2024 22:15:25 +0530 Subject: [PATCH 2/5] Assignment shivagaur 2215001353 --- Solution.java | 42 +++++++++++++++++++++++++ code1.java | 63 +++++++++++++++++++++++++++++++++++++ code3.java | 0 code4.java | 34 ++++++++++++++++++++ code5.java | 36 +++++++++++++++++++++ code6.java | 0 countElementMaximumSum.java | 23 ++++++++++++++ findPeakElement.java | 0 generate.java | 0 lemonadeChange.java | 33 +++++++++++++++++++ searchRange.java | 50 +++++++++++++++++++++++++++++ 11 files changed, 281 insertions(+) create mode 100644 Solution.java create mode 100644 code1.java create mode 100644 code3.java create mode 100644 code4.java create mode 100644 code5.java create mode 100644 code6.java create mode 100644 countElementMaximumSum.java create mode 100644 findPeakElement.java create mode 100644 generate.java create mode 100644 lemonadeChange.java create mode 100644 searchRange.java diff --git a/Solution.java b/Solution.java new file mode 100644 index 00000000..7f14862c --- /dev/null +++ b/Solution.java @@ -0,0 +1,42 @@ +package ShivaGaur_2215001653_TBPPP; +class Solution { + public int islandPerimeter(int[][] grid) { + int rows = grid.length; + int cols = grid[0].length; + int ans = 0; + int up, down, left, right; + + for (int r = 0; r < rows; r++) { + for (int c = 0; c < cols; c++) { + if (grid[r][c] == 1) { + if (r == 0) { + up = 1; + } else { + up = (grid[r - 1][c] == 0) ? 1 : 0; + } + + if (c == 0) { + left = 1; + } else { + left = (grid[r][c - 1] == 0) ? 1 : 0; + } + + if (r == rows - 1) { + down = 1; + } else { + down = (grid[r + 1][c] == 0) ? 1 : 0; + } + + if (c == cols - 1) { + right = 1; + } else { + right = (grid[r][c + 1] == 0) ? 1 : 0; + } + + ans += up + left + down + right; + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/code1.java b/code1.java new file mode 100644 index 00000000..abf106ef --- /dev/null +++ b/code1.java @@ -0,0 +1,63 @@ +package ShivaGaur_2215001653_TBPPP; + +import java.util.*; +import java.io.*; + +class code2 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int tc = Integer.parseInt(br.readLine().trim()); + + while (tc-- > 0) { + String[] str = br.readLine().trim().split(" "); + int[] a = new int[str.length]; + for (int i = 0; i < str.length; i++) { + a[i] = Integer.parseInt(str[i]); + } + String[] nk = br.readLine().trim().split(" "); + int k = Integer.parseInt(nk[0]); + + Solution sln = new Solution(); + int ans = sln.aggresiveCows(a, k); + + System.out.println(ans); + System.out.println("~"); + } + } +} + +class Solution { + public static int aggresiveCows(int[] stalls, int k) { + Arrays.sort(stalls); + int low = 0; + int ans = 0; + int high = stalls[stalls.length - 1] - stalls[0]; + + while (low <= high) { + int mid = low + (high - low) / 2; + if (possible(stalls, mid, k)) { + ans = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + return ans; + } + + public static boolean possible(int[] stalls, int dist, int cows) { + int count = 1; + int last_cow = stalls[0]; + + for (int i = 1; i < stalls.length; i++) { + if (stalls[i] - last_cow >= dist) { + count++; + last_cow = stalls[i]; + } + if (count >= cows) { + return true; + } + } + return false; + } +} diff --git a/code3.java b/code3.java new file mode 100644 index 00000000..e69de29b diff --git a/code4.java b/code4.java new file mode 100644 index 00000000..cc950530 --- /dev/null +++ b/code4.java @@ -0,0 +1,34 @@ +package ShivaGaur_2215001653_TBPPP; + +public class code4 { + public int[] findPeakGrid(int[][] mat) { + int low=0; + int high=mat[0].length-1; + while(low<=high){ + int mid=low+(high-low)/2; + int row=maxele(mat,mid); + int leftele=mid-1>0?mat[row][mid-1]:-1; + int rightele=mid+1leftele && mat[row][mid]>rightele){ + return new int[]{row,mid}; + } + else if(mat[row][mid]max){ + max=mat[i][col]; + idx=i; + } + } + return idx; + } +} \ No newline at end of file diff --git a/code5.java b/code5.java new file mode 100644 index 00000000..6b6b67a5 --- /dev/null +++ b/code5.java @@ -0,0 +1,36 @@ +package ShivaGaur_2215001653_TBPPP; + +public class code5 { + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + if(nums1.length>nums2.length){ + return findMedianSortedArrays(nums2,nums1); + } + int m=nums1.length; + int n=nums2.length; + int low=0; + int high=nums1.length; + while(low<=high){ + int mid=low+(high-low)/2; + int py=(m+n+1)/2-mid; + int x1= mid==0? Integer.MIN_VALUE:nums1[mid-1]; + int x2= py==0 ? Integer.MIN_VALUE:nums2[py-1]; + int x3= mid==m?Integer.MAX_VALUE:nums1[mid]; + int x4= py==n? Integer.MAX_VALUE:nums2[py]; + if(x1<=x4 && x2<=x3){ + if((m+n)%2==1){ + return Math.max(x1,x2); + } + else{ + return (Math.max(x1,x2)+Math.min(x3,x4))/2.0; + } + } + if(x1>x4){ + high=mid-1; + } + else{ + low=mid+1; + } + } + return -1.0; + } + } \ No newline at end of file diff --git a/code6.java b/code6.java new file mode 100644 index 00000000..e69de29b diff --git a/countElementMaximumSum.java b/countElementMaximumSum.java new file mode 100644 index 00000000..c666ff88 --- /dev/null +++ b/countElementMaximumSum.java @@ -0,0 +1,23 @@ +package ShivaGaur_2215001653_TBPPP; +import java.util.HashMap; + +class CountElementsWithMaximumFrequency { + public static void main(String[] args){ + int[] nums={1,2,2,1,3,4}; + HashMap map=new HashMap<>(); + for(int i:nums){ + map.put(i,map.getOrDefault(i, 0)+1); + } + int max=Integer.MIN_VALUE; + int cnt=0; + for(int i:map.values()){ + max=Math.max(i, max); + } + for(int i:map.values()){ + if(i==max){ + cnt++; + } + } + System.err.println(cnt*max); + } +} \ No newline at end of file diff --git a/findPeakElement.java b/findPeakElement.java new file mode 100644 index 00000000..e69de29b diff --git a/generate.java b/generate.java new file mode 100644 index 00000000..e69de29b diff --git a/lemonadeChange.java b/lemonadeChange.java new file mode 100644 index 00000000..e1719a1b --- /dev/null +++ b/lemonadeChange.java @@ -0,0 +1,33 @@ +package ShivaGaur_2215001653_TBPPP; +import java.util.*; +class Solution { + public boolean lemonadeChange(int[] bills) { + int five=0; + int ten=0; + for(int i=0;i0 && ten>0){ + five--; + ten--; + } + else if(five>=3){ + five-=3; + } + else{ + return false; + } + } + } + return true; + } +} diff --git a/searchRange.java b/searchRange.java new file mode 100644 index 00000000..3baad819 --- /dev/null +++ b/searchRange.java @@ -0,0 +1,50 @@ +package ShivaGaur_2215001653_TBPPP; + +public class searchRange { + + public int[] searchRange(int[] nums, int target) { + int first=firstidx(nums,target); + if(first==-1){ + return new int[]{-1,-1}; + } + int last=lastidx(nums,target); + return new int[]{first,last}; + } + public static int firstidx(int[] arr,int k){ + int low=0; + int high=arr.length-1; + int f=-1; + while(low<=high){ + int mid=low+(high-low)/2; + if(arr[mid]==k){ + f=mid; + high=mid-1; + } + else if(arr[mid] Date: Tue, 12 Nov 2024 22:24:02 +0530 Subject: [PATCH 3/5] assignment --- .../README.md | 27 +++++++ .../remove-trailing-zeros-from-a-string.java | 9 +++ 2825-minimize-string-length/README.md | 72 +++++++++++++++++ .../minimize-string-length.java | 9 +++ .../README.md | 37 +++++++++ ...eatest-common-divisors-in-linked-list.java | 34 ++++++++ .../README.md | 50 ++++++++++++ ...anges-to-make-binary-string-beautiful.java | 13 +++ 3195-separate-black-and-white-balls/README.md | 44 +++++++++++ .../separate-black-and-white-balls.java | 13 +++ 3291-find-if-array-can-be-sorted/README.md | 45 +++++++++++ .../find-if-array-can-be-sorted.java | 34 ++++++++ .../README.md | 39 +++++++++ ...e-length-of-the-longest-common-prefix.java | 25 ++++++ .../README.md | 43 ++++++++++ 3394-minimum-array-end/README.md | 35 ++++++++ 3394-minimum-array-end/minimum-array-end.java | 15 ++++ 3451-string-compression-iii/README.md | 54 +++++++++++++ .../string-compression-iii.java | 23 ++++++ .../README.md | 56 +++++++++++++ ...des-from-linked-list-present-in-array.java | 27 +++++++ .../README.md | 34 ++++++++ .../smallest-divisible-digit-product-i.java | 16 ++++ 55-jump-game/README.md | 28 +++++++ 55-jump-game/jump-game.java | 17 ++++ 554-brick-wall/README.md | 32 ++++++++ 554-brick-wall/brick-wall.java | 17 ++++ 56-merge-intervals/README.md | 27 +++++++ 56-merge-intervals/merge-intervals.java | 31 ++++++++ 58-length-of-last-word/README.md | 37 +++++++++ .../length-of-last-word.java | 11 +++ .../README.md | 36 +++++++++ .../fraction-addition-and-subtraction.java | 72 +++++++++++++++++ 6-zigzag-conversion/README.md | 51 ++++++++++++ 6-zigzag-conversion/zigzag-conversion.java | 32 ++++++++ .../README.md | 45 +++++++++++ .../construct-string-from-binary-tree.java | 26 ++++++ 623-add-one-row-to-tree/README.md | 38 +++++++++ .../add-one-row-to-tree.java | 42 ++++++++++ .../README.md | 25 ++++++ .../average-of-levels-in-binary-tree.java | 36 +++++++++ 654-maximum-binary-tree/README.md | 43 ++++++++++ .../maximum-binary-tree.java | 35 ++++++++ 658-find-k-closest-elements/README.md | 35 ++++++++ .../find-k-closest-elements.java | 17 ++++ 662-maximum-width-of-binary-tree/README.md | 40 ++++++++++ .../maximum-width-of-binary-tree.java | 45 +++++++++++ 669-trim-a-binary-search-tree/README.md | 29 +++++++ .../trim-a-binary-search-tree.java | 27 +++++++ 67-add-binary/README.md | 18 +++++ 67-add-binary/add-binary.java | 21 +++++ 695-max-area-of-island/README.md | 31 ++++++++ .../max-area-of-island.java | 41 ++++++++++ 725-split-linked-list-in-parts/README.md | 36 +++++++++ .../split-linked-list-in-parts.java | 79 +++++++++++++++++++ 729-my-calendar-i/README.md | 36 +++++++++ 729-my-calendar-i/my-calendar-i.java | 23 ++++++ 733-flood-fill/README.md | 53 +++++++++++++ 733-flood-fill/flood-fill.java | 34 ++++++++ 75-sort-colors/README.md | 32 ++++++++ 75-sort-colors/sort-colors.java | 16 ++++ 783-search-in-a-binary-search-tree/README.md | 28 +++++++ .../README.md | 38 +++++++++ .../README.md | 53 +++++++++++++ ...emove-duplicates-from-sorted-array-ii.java | 16 ++++ 801-is-graph-bipartite/README.md | 40 ++++++++++ .../is-graph-bipartite.java | 33 ++++++++ 802-k-th-smallest-prime-fraction/README.md | 38 +++++++++ .../k-th-smallest-prime-fraction.java | 16 ++++ 812-rotate-string/README.md | 23 ++++++ 812-rotate-string/rotate-string.java | 13 +++ 875-longest-mountain-in-array/README.md | 46 +++++++++++ .../longest-mountain-in-array.java | 17 ++++ 88-merge-sorted-array/README.md | 48 +++++++++++ 88-merge-sorted-array/merge-sorted-array.java | 17 ++++ 882-peak-index-in-a-mountain-array/README.md | 39 +++++++++ .../peak-index-in-a-mountain-array.java | 14 ++++ 889-buddy-strings/README.md | 40 ++++++++++ 889-buddy-strings/buddy-strings.java | 30 +++++++ 890-lemonade-change/README.md | 38 +++++++++ 890-lemonade-change/lemonade-change.java | 26 ++++++ .../README.md | 30 +++++++ .../all-nodes-distance-k-in-binary-tree.java | 53 +++++++++++++ 9-palindrome-number/README.md | 36 +++++++++ 9-palindrome-number/palindrome-number.java | 17 ++++ 90-subsets-ii/README.md | 19 +++++ 90-subsets-ii/subsets-ii.java | 18 +++++ 94-binary-tree-inorder-traversal/README.md | 34 ++++++++ .../binary-tree-inorder-traversal.java | 32 ++++++++ 941-sort-array-by-parity/README.md | 27 +++++++ .../sort-array-by-parity.java | 14 ++++ .../README.md | 38 +++++++++ ...minimum-add-to-make-parentheses-valid.java | 13 +++ 98-validate-binary-search-tree/README.md | 33 ++++++++ .../validate-binary-search-tree.java | 11 +++ 95 files changed, 3036 insertions(+) create mode 100644 2819-remove-trailing-zeros-from-a-string/README.md create mode 100644 2819-remove-trailing-zeros-from-a-string/remove-trailing-zeros-from-a-string.java create mode 100644 2825-minimize-string-length/README.md create mode 100644 2825-minimize-string-length/minimize-string-length.java create mode 100644 2903-insert-greatest-common-divisors-in-linked-list/README.md create mode 100644 2903-insert-greatest-common-divisors-in-linked-list/insert-greatest-common-divisors-in-linked-list.java create mode 100644 3174-minimum-number-of-changes-to-make-binary-string-beautiful/README.md create mode 100644 3174-minimum-number-of-changes-to-make-binary-string-beautiful/minimum-number-of-changes-to-make-binary-string-beautiful.java create mode 100644 3195-separate-black-and-white-balls/README.md create mode 100644 3195-separate-black-and-white-balls/separate-black-and-white-balls.java create mode 100644 3291-find-if-array-can-be-sorted/README.md create mode 100644 3291-find-if-array-can-be-sorted/find-if-array-can-be-sorted.java create mode 100644 3329-find-the-length-of-the-longest-common-prefix/README.md create mode 100644 3329-find-the-length-of-the-longest-common-prefix/find-the-length-of-the-longest-common-prefix.java create mode 100644 3331-minimum-operations-to-exceed-threshold-value-i/README.md create mode 100644 3394-minimum-array-end/README.md create mode 100644 3394-minimum-array-end/minimum-array-end.java create mode 100644 3451-string-compression-iii/README.md create mode 100644 3451-string-compression-iii/string-compression-iii.java create mode 100644 3501-delete-nodes-from-linked-list-present-in-array/README.md create mode 100644 3501-delete-nodes-from-linked-list-present-in-array/delete-nodes-from-linked-list-present-in-array.java create mode 100644 3626-smallest-divisible-digit-product-i/README.md create mode 100644 3626-smallest-divisible-digit-product-i/smallest-divisible-digit-product-i.java create mode 100644 55-jump-game/README.md create mode 100644 55-jump-game/jump-game.java create mode 100644 554-brick-wall/README.md create mode 100644 554-brick-wall/brick-wall.java create mode 100644 56-merge-intervals/README.md create mode 100644 56-merge-intervals/merge-intervals.java create mode 100644 58-length-of-last-word/README.md create mode 100644 58-length-of-last-word/length-of-last-word.java create mode 100644 592-fraction-addition-and-subtraction/README.md create mode 100644 592-fraction-addition-and-subtraction/fraction-addition-and-subtraction.java create mode 100644 6-zigzag-conversion/README.md create mode 100644 6-zigzag-conversion/zigzag-conversion.java create mode 100644 606-construct-string-from-binary-tree/README.md create mode 100644 606-construct-string-from-binary-tree/construct-string-from-binary-tree.java create mode 100644 623-add-one-row-to-tree/README.md create mode 100644 623-add-one-row-to-tree/add-one-row-to-tree.java create mode 100644 637-average-of-levels-in-binary-tree/README.md create mode 100644 637-average-of-levels-in-binary-tree/average-of-levels-in-binary-tree.java create mode 100644 654-maximum-binary-tree/README.md create mode 100644 654-maximum-binary-tree/maximum-binary-tree.java create mode 100644 658-find-k-closest-elements/README.md create mode 100644 658-find-k-closest-elements/find-k-closest-elements.java create mode 100644 662-maximum-width-of-binary-tree/README.md create mode 100644 662-maximum-width-of-binary-tree/maximum-width-of-binary-tree.java create mode 100644 669-trim-a-binary-search-tree/README.md create mode 100644 669-trim-a-binary-search-tree/trim-a-binary-search-tree.java create mode 100644 67-add-binary/README.md create mode 100644 67-add-binary/add-binary.java create mode 100644 695-max-area-of-island/README.md create mode 100644 695-max-area-of-island/max-area-of-island.java create mode 100644 725-split-linked-list-in-parts/README.md create mode 100644 725-split-linked-list-in-parts/split-linked-list-in-parts.java create mode 100644 729-my-calendar-i/README.md create mode 100644 729-my-calendar-i/my-calendar-i.java create mode 100644 733-flood-fill/README.md create mode 100644 733-flood-fill/flood-fill.java create mode 100644 75-sort-colors/README.md create mode 100644 75-sort-colors/sort-colors.java create mode 100644 783-search-in-a-binary-search-tree/README.md create mode 100644 784-insert-into-a-binary-search-tree/README.md create mode 100644 80-remove-duplicates-from-sorted-array-ii/README.md create mode 100644 80-remove-duplicates-from-sorted-array-ii/remove-duplicates-from-sorted-array-ii.java create mode 100644 801-is-graph-bipartite/README.md create mode 100644 801-is-graph-bipartite/is-graph-bipartite.java create mode 100644 802-k-th-smallest-prime-fraction/README.md create mode 100644 802-k-th-smallest-prime-fraction/k-th-smallest-prime-fraction.java create mode 100644 812-rotate-string/README.md create mode 100644 812-rotate-string/rotate-string.java create mode 100644 875-longest-mountain-in-array/README.md create mode 100644 875-longest-mountain-in-array/longest-mountain-in-array.java create mode 100644 88-merge-sorted-array/README.md create mode 100644 88-merge-sorted-array/merge-sorted-array.java create mode 100644 882-peak-index-in-a-mountain-array/README.md create mode 100644 882-peak-index-in-a-mountain-array/peak-index-in-a-mountain-array.java create mode 100644 889-buddy-strings/README.md create mode 100644 889-buddy-strings/buddy-strings.java create mode 100644 890-lemonade-change/README.md create mode 100644 890-lemonade-change/lemonade-change.java create mode 100644 893-all-nodes-distance-k-in-binary-tree/README.md create mode 100644 893-all-nodes-distance-k-in-binary-tree/all-nodes-distance-k-in-binary-tree.java create mode 100644 9-palindrome-number/README.md create mode 100644 9-palindrome-number/palindrome-number.java create mode 100644 90-subsets-ii/README.md create mode 100644 90-subsets-ii/subsets-ii.java create mode 100644 94-binary-tree-inorder-traversal/README.md create mode 100644 94-binary-tree-inorder-traversal/binary-tree-inorder-traversal.java create mode 100644 941-sort-array-by-parity/README.md create mode 100644 941-sort-array-by-parity/sort-array-by-parity.java create mode 100644 957-minimum-add-to-make-parentheses-valid/README.md create mode 100644 957-minimum-add-to-make-parentheses-valid/minimum-add-to-make-parentheses-valid.java create mode 100644 98-validate-binary-search-tree/README.md create mode 100644 98-validate-binary-search-tree/validate-binary-search-tree.java diff --git a/2819-remove-trailing-zeros-from-a-string/README.md b/2819-remove-trailing-zeros-from-a-string/README.md new file mode 100644 index 00000000..2d2f7c86 --- /dev/null +++ b/2819-remove-trailing-zeros-from-a-string/README.md @@ -0,0 +1,27 @@ +

Remove Trailing Zeros From a String

Difficulty: Easy

Given a positive integer num represented as a string, return the integer num without trailing zeros as a string.

+ +

 

+

Example 1:

+ +
+Input: num = "51230100"
+Output: "512301"
+Explanation: Integer "51230100" has 2 trailing zeros, we remove them and return integer "512301".
+
+ +

Example 2:

+ +
+Input: num = "123"
+Output: "123"
+Explanation: Integer "123" has no trailing zeros, we return integer "123".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= num.length <= 1000
  • +
  • num consists of only digits.
  • +
  • num doesn't have any leading zeros.
  • +
diff --git a/2819-remove-trailing-zeros-from-a-string/remove-trailing-zeros-from-a-string.java b/2819-remove-trailing-zeros-from-a-string/remove-trailing-zeros-from-a-string.java new file mode 100644 index 00000000..1272b4fc --- /dev/null +++ b/2819-remove-trailing-zeros-from-a-string/remove-trailing-zeros-from-a-string.java @@ -0,0 +1,9 @@ +class Solution { + public String removeTrailingZeros(String num) { + for(int i=num.length()-1;i>=0;i--){ + if(num.charAt(i)=='0') num=num.substring(0,num.length()-1); + else break; + } + return num; + } +} \ No newline at end of file diff --git a/2825-minimize-string-length/README.md b/2825-minimize-string-length/README.md new file mode 100644 index 00000000..241392c6 --- /dev/null +++ b/2825-minimize-string-length/README.md @@ -0,0 +1,72 @@ +

Minimize String Length

Difficulty: Easy

Given a string s, you have two types of operation:

+ +
    +
  1. Choose an index i in the string, and let c be the character in position i. Delete the closest occurrence of c to the left of i (if exists).
  2. +
  3. Choose an index i in the string, and let c be the character in position i. Delete the closest occurrence of c to the right of i (if exists).
  4. +
+ +

Your task is to minimize the length of s by performing the above operations zero or more times.

+ +

Return an integer denoting the length of the minimized string.

+ +

 

+

Example 1:

+ +
+

Input: s = "aaabc"

+ +

Output: 3

+ +

Explanation:

+ +
    +
  1. Operation 2: we choose i = 1 so c is 'a', then we remove s[2] as it is closest 'a' character to the right of s[1].
    + s becomes "aabc" after this.
  2. +
  3. Operation 1: we choose i = 1 so c is 'a', then we remove s[0] as it is closest 'a' character to the left of s[1].
    + s becomes "abc" after this.
  4. +
+
+ +

Example 2:

+ +
+

Input: s = "cbbd"

+ +

Output: 3

+ +

Explanation:

+ +
    +
  1. Operation 1: we choose i = 2 so c is 'b', then we remove s[1] as it is closest 'b' character to the left of s[1].
    + s becomes "cbd" after this.
  2. +
+
+ +

Example 3:

+ +
+

Input: s = "baadccab"

+ +

Output: 4

+ +

Explanation:

+ +
    +
  1. Operation 1: we choose i = 6 so c is 'a', then we remove s[2] as it is closest 'a' character to the left of s[6].
    + s becomes "badccab" after this.
  2. +
  3. Operation 2: we choose i = 0 so c is 'b', then we remove s[6] as it is closest 'b' character to the right of s[0].
    + s becomes "badcca" fter this.
  4. +
  5. Operation 2: we choose i = 3 so c is 'c', then we remove s[4] as it is closest 'c' character to the right of s[3].
    + s becomes "badca" after this.
  6. +
  7. Operation 1: we choose i = 4 so c is 'a', then we remove s[1] as it is closest 'a' character to the left of s[4].
    + s becomes "bdca" after this.
  8. +
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 100
  • +
  • s contains only lowercase English letters
  • +
diff --git a/2825-minimize-string-length/minimize-string-length.java b/2825-minimize-string-length/minimize-string-length.java new file mode 100644 index 00000000..d91c9b8e --- /dev/null +++ b/2825-minimize-string-length/minimize-string-length.java @@ -0,0 +1,9 @@ +class Solution { + public int minimizedStringLength(String s) { + Map map=new HashMap<>(); + for(char a:s.toCharArray()){ + map.put(a,map.getOrDefault(a,0)+1); + } + return map.size(); + } +} \ No newline at end of file diff --git a/2903-insert-greatest-common-divisors-in-linked-list/README.md b/2903-insert-greatest-common-divisors-in-linked-list/README.md new file mode 100644 index 00000000..7306b5f9 --- /dev/null +++ b/2903-insert-greatest-common-divisors-in-linked-list/README.md @@ -0,0 +1,37 @@ +

Insert Greatest Common Divisors in Linked List

Difficulty: Medium

Given the head of a linked list head, in which each node contains an integer value.

+ +

Between every pair of adjacent nodes, insert a new node with a value equal to the greatest common divisor of them.

+ +

Return the linked list after insertion.

+ +

The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.

+ +

 

+

Example 1:

+ +
+Input: head = [18,6,10,3]
+Output: [18,6,6,2,10,1,3]
+Explanation: The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes (nodes in blue are the inserted nodes).
+- We insert the greatest common divisor of 18 and 6 = 6 between the 1st and the 2nd nodes.
+- We insert the greatest common divisor of 6 and 10 = 2 between the 2nd and the 3rd nodes.
+- We insert the greatest common divisor of 10 and 3 = 1 between the 3rd and the 4th nodes.
+There are no more adjacent nodes, so we return the linked list.
+
+ +

Example 2:

+ +
+Input: head = [7]
+Output: [7]
+Explanation: The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes.
+There are no pairs of adjacent nodes, so we return the initial linked list.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [1, 5000].
  • +
  • 1 <= Node.val <= 1000
  • +
diff --git a/2903-insert-greatest-common-divisors-in-linked-list/insert-greatest-common-divisors-in-linked-list.java b/2903-insert-greatest-common-divisors-in-linked-list/insert-greatest-common-divisors-in-linked-list.java new file mode 100644 index 00000000..7535b21e --- /dev/null +++ b/2903-insert-greatest-common-divisors-in-linked-list/insert-greatest-common-divisors-in-linked-list.java @@ -0,0 +1,34 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode insertGreatestCommonDivisors(ListNode head) { + if(head==null) return head; + ListNode ans=new ListNode(head.val); + ListNode dummy=ans; + head=head.next; + while(head!=null){ + int gcd=gcd(ans.val,head.val); + ans.next=new ListNode(gcd); + ans=ans.next; + ans.next=new ListNode(head.val); + ans=ans.next; + head=head.next; + } + return dummy; + } + public int gcd(int a,int b){ + int min=Math.min(a,b); + for(int i=min;i>1;i--){ + if(a%i==0 && b%i==0) return i; + } + return 1; + } +} \ No newline at end of file diff --git a/3174-minimum-number-of-changes-to-make-binary-string-beautiful/README.md b/3174-minimum-number-of-changes-to-make-binary-string-beautiful/README.md new file mode 100644 index 00000000..2cf6d0ac --- /dev/null +++ b/3174-minimum-number-of-changes-to-make-binary-string-beautiful/README.md @@ -0,0 +1,50 @@ +

Minimum Number of Changes to Make Binary String Beautiful

Difficulty: Medium

You are given a 0-indexed binary string s having an even length.

+ +

A string is beautiful if it's possible to partition it into one or more substrings such that:

+ +
    +
  • Each substring has an even length.
  • +
  • Each substring contains only 1's or only 0's.
  • +
+ +

You can change any character in s to 0 or 1.

+ +

Return the minimum number of changes required to make the string s beautiful.

+ +

 

+

Example 1:

+ +
+Input: s = "1001"
+Output: 2
+Explanation: We change s[1] to 1 and s[3] to 0 to get string "1100".
+It can be seen that the string "1100" is beautiful because we can partition it into "11|00".
+It can be proven that 2 is the minimum number of changes needed to make the string beautiful.
+
+ +

Example 2:

+ +
+Input: s = "10"
+Output: 1
+Explanation: We change s[1] to 1 to get string "11".
+It can be seen that the string "11" is beautiful because we can partition it into "11".
+It can be proven that 1 is the minimum number of changes needed to make the string beautiful.
+
+ +

Example 3:

+ +
+Input: s = "0000"
+Output: 0
+Explanation: We don't need to make any changes as the string "0000" is beautiful already.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= s.length <= 105
  • +
  • s has an even length.
  • +
  • s[i] is either '0' or '1'.
  • +
diff --git a/3174-minimum-number-of-changes-to-make-binary-string-beautiful/minimum-number-of-changes-to-make-binary-string-beautiful.java b/3174-minimum-number-of-changes-to-make-binary-string-beautiful/minimum-number-of-changes-to-make-binary-string-beautiful.java new file mode 100644 index 00000000..c81fb6ae --- /dev/null +++ b/3174-minimum-number-of-changes-to-make-binary-string-beautiful/minimum-number-of-changes-to-make-binary-string-beautiful.java @@ -0,0 +1,13 @@ +class Solution { + public int minChanges(String s) { + int i=0; + int ans=0; + while(iSeparate Black and White Balls Difficulty: Medium

There are n balls on a table, each ball has a color black or white.

+ +

You are given a 0-indexed binary string s of length n, where 1 and 0 represent black and white balls, respectively.

+ +

In each step, you can choose two adjacent balls and swap them.

+ +

Return the minimum number of steps to group all the black balls to the right and all the white balls to the left.

+ +

 

+

Example 1:

+ +
+Input: s = "101"
+Output: 1
+Explanation: We can group all the black balls to the right in the following way:
+- Swap s[0] and s[1], s = "011".
+Initially, 1s are not grouped together, requiring at least 1 step to group them to the right.
+ +

Example 2:

+ +
+Input: s = "100"
+Output: 2
+Explanation: We can group all the black balls to the right in the following way:
+- Swap s[0] and s[1], s = "010".
+- Swap s[1] and s[2], s = "001".
+It can be proven that the minimum number of steps needed is 2.
+
+ +

Example 3:

+ +
+Input: s = "0111"
+Output: 0
+Explanation: All the black balls are already grouped to the right.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n == s.length <= 105
  • +
  • s[i] is either '0' or '1'.
  • +
diff --git a/3195-separate-black-and-white-balls/separate-black-and-white-balls.java b/3195-separate-black-and-white-balls/separate-black-and-white-balls.java new file mode 100644 index 00000000..0073910e --- /dev/null +++ b/3195-separate-black-and-white-balls/separate-black-and-white-balls.java @@ -0,0 +1,13 @@ +class Solution { + public long minimumSteps(String s) { + long ans=0; + long temp=0; + for(int i=0;iFind if Array Can Be Sorted Difficulty: Medium

You are given a 0-indexed array of positive integers nums.

+ +

In one operation, you can swap any two adjacent elements if they have the same number of set bits. You are allowed to do this operation any number of times (including zero).

+ +

Return true if you can sort the array, else return false.

+ +

 

+

Example 1:

+ +
+Input: nums = [8,4,2,30,15]
+Output: true
+Explanation: Let's look at the binary representation of every element. The numbers 2, 4, and 8 have one set bit each with binary representation "10", "100", and "1000" respectively. The numbers 15 and 30 have four set bits each with binary representation "1111" and "11110".
+We can sort the array using 4 operations:
+- Swap nums[0] with nums[1]. This operation is valid because 8 and 4 have one set bit each. The array becomes [4,8,2,30,15].
+- Swap nums[1] with nums[2]. This operation is valid because 8 and 2 have one set bit each. The array becomes [4,2,8,30,15].
+- Swap nums[0] with nums[1]. This operation is valid because 4 and 2 have one set bit each. The array becomes [2,4,8,30,15].
+- Swap nums[3] with nums[4]. This operation is valid because 30 and 15 have four set bits each. The array becomes [2,4,8,15,30].
+The array has become sorted, hence we return true.
+Note that there may be other sequences of operations which also sort the array.
+
+ +

Example 2:

+ +
+Input: nums = [1,2,3,4,5]
+Output: true
+Explanation: The array is already sorted, hence we return true.
+
+ +

Example 3:

+ +
+Input: nums = [3,16,8,4,2]
+Output: false
+Explanation: It can be shown that it is not possible to sort the input array using any number of operations.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 1 <= nums[i] <= 28
  • +
diff --git a/3291-find-if-array-can-be-sorted/find-if-array-can-be-sorted.java b/3291-find-if-array-can-be-sorted/find-if-array-can-be-sorted.java new file mode 100644 index 00000000..a571a71d --- /dev/null +++ b/3291-find-if-array-can-be-sorted/find-if-array-can-be-sorted.java @@ -0,0 +1,34 @@ +class Solution { + public boolean canSortArray(int[] nums) { + List ls=new ArrayList<>(); + int bit[]=new int[nums.length]; + for(int i=0;ils.get(i).min || min>ls.get(i).max) return false; + min=Math.max(ls.get(i).max,min); + } + return true; + } +} +class pair{ + int max; + int min; + pair(int min,int max){ + this.min=min; + this.max=max; + } +} \ No newline at end of file diff --git a/3329-find-the-length-of-the-longest-common-prefix/README.md b/3329-find-the-length-of-the-longest-common-prefix/README.md new file mode 100644 index 00000000..90e0bcfc --- /dev/null +++ b/3329-find-the-length-of-the-longest-common-prefix/README.md @@ -0,0 +1,39 @@ +

Find the Length of the Longest Common Prefix

Difficulty: Medium

You are given two arrays with positive integers arr1 and arr2.

+ +

A prefix of a positive integer is an integer formed by one or more of its digits, starting from its leftmost digit. For example, 123 is a prefix of the integer 12345, while 234 is not.

+ +

A common prefix of two integers a and b is an integer c, such that c is a prefix of both a and b. For example, 5655359 and 56554 have a common prefix 565 while 1223 and 43456 do not have a common prefix.

+ +

You need to find the length of the longest common prefix between all pairs of integers (x, y) such that x belongs to arr1 and y belongs to arr2.

+ +

Return the length of the longest common prefix among all pairs. If no common prefix exists among them, return 0.

+ +

 

+

Example 1:

+ +
+Input: arr1 = [1,10,100], arr2 = [1000]
+Output: 3
+Explanation: There are 3 pairs (arr1[i], arr2[j]):
+- The longest common prefix of (1, 1000) is 1.
+- The longest common prefix of (10, 1000) is 10.
+- The longest common prefix of (100, 1000) is 100.
+The longest common prefix is 100 with a length of 3.
+
+ +

Example 2:

+ +
+Input: arr1 = [1,2,3], arr2 = [4,4,4]
+Output: 0
+Explanation: There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0.
+Note that common prefixes between elements of the same array do not count.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr1.length, arr2.length <= 5 * 104
  • +
  • 1 <= arr1[i], arr2[i] <= 108
  • +
diff --git a/3329-find-the-length-of-the-longest-common-prefix/find-the-length-of-the-longest-common-prefix.java b/3329-find-the-length-of-the-longest-common-prefix/find-the-length-of-the-longest-common-prefix.java new file mode 100644 index 00000000..5e021893 --- /dev/null +++ b/3329-find-the-length-of-the-longest-common-prefix/find-the-length-of-the-longest-common-prefix.java @@ -0,0 +1,25 @@ +class Solution { + public int longestCommonPrefix(int[] arr, int[] nums) { + Map map=new HashMap<>(); + int ans=0; + for(int i=0;i set=new HashSet<>(); + for(int a:nums){ + String prefix=""; + String s=""+a; + boolean flag=true; + for(char ch:s.toCharArray()){ + prefix+=ch; + if(map.containsKey(prefix)) ans=Math.max(ans,prefix.length()); + } + } + return ans; + } +} \ No newline at end of file diff --git a/3331-minimum-operations-to-exceed-threshold-value-i/README.md b/3331-minimum-operations-to-exceed-threshold-value-i/README.md new file mode 100644 index 00000000..6bf474d1 --- /dev/null +++ b/3331-minimum-operations-to-exceed-threshold-value-i/README.md @@ -0,0 +1,43 @@ +

Minimum Operations to Exceed Threshold Value I

Difficulty: Easy

You are given a 0-indexed integer array nums, and an integer k.

+ +

In one operation, you can remove one occurrence of the smallest element of nums.

+ +

Return the minimum number of operations needed so that all elements of the array are greater than or equal to k.

+ +

 

+

Example 1:

+ +
+Input: nums = [2,11,10,1,3], k = 10
+Output: 3
+Explanation: After one operation, nums becomes equal to [2, 11, 10, 3].
+After two operations, nums becomes equal to [11, 10, 3].
+After three operations, nums becomes equal to [11, 10].
+At this stage, all the elements of nums are greater than or equal to 10 so we can stop.
+It can be shown that 3 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.
+
+ +

Example 2:

+ +
+Input: nums = [1,1,2,4,9], k = 1
+Output: 0
+Explanation: All elements of the array are greater than or equal to 1 so we do not need to apply any operations on nums.
+ +

Example 3:

+ +
+Input: nums = [1,1,2,4,9], k = 9
+Output: 4
+Explanation: only a single element of nums is greater than or equal to 9 so we need to apply the operations 4 times on nums.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 50
  • +
  • 1 <= nums[i] <= 109
  • +
  • 1 <= k <= 109
  • +
  • The input is generated such that there is at least one index i such that nums[i] >= k.
  • +
diff --git a/3394-minimum-array-end/README.md b/3394-minimum-array-end/README.md new file mode 100644 index 00000000..901f3d55 --- /dev/null +++ b/3394-minimum-array-end/README.md @@ -0,0 +1,35 @@ +

Minimum Array End

Difficulty: Medium

You are given two integers n and x. You have to construct an array of positive integers nums of size n where for every 0 <= i < n - 1, nums[i + 1] is greater than nums[i], and the result of the bitwise AND operation between all elements of nums is x.

+ +

Return the minimum possible value of nums[n - 1].

+ +

 

+

Example 1:

+ +
+

Input: n = 3, x = 4

+ +

Output: 6

+ +

Explanation:

+ +

nums can be [4,5,6] and its last element is 6.

+
+ +

Example 2:

+ +
+

Input: n = 2, x = 7

+ +

Output: 15

+ +

Explanation:

+ +

nums can be [7,15] and its last element is 15.

+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n, x <= 108
  • +
diff --git a/3394-minimum-array-end/minimum-array-end.java b/3394-minimum-array-end/minimum-array-end.java new file mode 100644 index 00000000..1a20e5f0 --- /dev/null +++ b/3394-minimum-array-end/minimum-array-end.java @@ -0,0 +1,15 @@ +class Solution { + public long minEnd(int n, int x) { + long res=x; + long rem=n-1; + long pos=1; + while (rem!=0){ + if ((x&pos)==0) { + res|=(rem&1)*pos; + rem>>=1; + } + pos<<=1; + } + return res; + } +} diff --git a/3451-string-compression-iii/README.md b/3451-string-compression-iii/README.md new file mode 100644 index 00000000..36c55a54 --- /dev/null +++ b/3451-string-compression-iii/README.md @@ -0,0 +1,54 @@ +

String Compression III

Difficulty: Medium

Given a string word, compress it using the following algorithm:

+ +
    +
  • Begin with an empty string comp. While word is not empty, use the following operation: + +
      +
    • Remove a maximum length prefix of word made of a single character c repeating at most 9 times.
    • +
    • Append the length of the prefix followed by c to comp.
    • +
    +
  • +
+ +

Return the string comp.

+ +

 

+

Example 1:

+ +
+

Input: word = "abcde"

+ +

Output: "1a1b1c1d1e"

+ +

Explanation:

+ +

Initially, comp = "". Apply the operation 5 times, choosing "a", "b", "c", "d", and "e" as the prefix in each operation.

+ +

For each prefix, append "1" followed by the character to comp.

+
+ +

Example 2:

+ +
+

Input: word = "aaaaaaaaaaaaaabb"

+ +

Output: "9a5a2b"

+ +

Explanation:

+ +

Initially, comp = "". Apply the operation 3 times, choosing "aaaaaaaaa", "aaaaa", and "bb" as the prefix in each operation.

+ +
    +
  • For prefix "aaaaaaaaa", append "9" followed by "a" to comp.
  • +
  • For prefix "aaaaa", append "5" followed by "a" to comp.
  • +
  • For prefix "bb", append "2" followed by "b" to comp.
  • +
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= word.length <= 2 * 105
  • +
  • word consists only of lowercase English letters.
  • +
diff --git a/3451-string-compression-iii/string-compression-iii.java b/3451-string-compression-iii/string-compression-iii.java new file mode 100644 index 00000000..a12765b2 --- /dev/null +++ b/3451-string-compression-iii/string-compression-iii.java @@ -0,0 +1,23 @@ +class Solution { + public String compressedString(String word) { + String ans=""; + int n=0; + char c=word.charAt(0); + for(int i=0;i0) ans+=""+n+c; + c=word.charAt(i); + n=1; + } + else{ + n++; + if(n==9){ + ans+="9"+c; + n=0; + } + } + } + if(n>0) ans+=""+n+c; + return ans; + } +} \ No newline at end of file diff --git a/3501-delete-nodes-from-linked-list-present-in-array/README.md b/3501-delete-nodes-from-linked-list-present-in-array/README.md new file mode 100644 index 00000000..74c1af53 --- /dev/null +++ b/3501-delete-nodes-from-linked-list-present-in-array/README.md @@ -0,0 +1,56 @@ +

Delete Nodes From Linked List Present in Array

Difficulty: Medium

You are given an array of integers nums and the head of a linked list. Return the head of the modified linked list after removing all nodes from the linked list that have a value that exists in nums.

+ +

 

+

Example 1:

+ +
+

Input: nums = [1,2,3], head = [1,2,3,4,5]

+ +

Output: [4,5]

+ +

Explanation:

+ +

+ +

Remove the nodes with values 1, 2, and 3.

+
+ +

Example 2:

+ +
+

Input: nums = [1], head = [1,2,1,2,1,2]

+ +

Output: [2,2,2]

+ +

Explanation:

+ +

+ +

Remove the nodes with value 1.

+
+ +

Example 3:

+ +
+

Input: nums = [5], head = [1,2,3,4]

+ +

Output: [1,2,3,4]

+ +

Explanation:

+ +

+ +

No node has value 5.

+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 105
  • +
  • All elements in nums are unique.
  • +
  • The number of nodes in the given list is in the range [1, 105].
  • +
  • 1 <= Node.val <= 105
  • +
  • The input is generated such that there is at least one node in the linked list that has a value not present in nums.
  • +
diff --git a/3501-delete-nodes-from-linked-list-present-in-array/delete-nodes-from-linked-list-present-in-array.java b/3501-delete-nodes-from-linked-list-present-in-array/delete-nodes-from-linked-list-present-in-array.java new file mode 100644 index 00000000..32529f4d --- /dev/null +++ b/3501-delete-nodes-from-linked-list-present-in-array/delete-nodes-from-linked-list-present-in-array.java @@ -0,0 +1,27 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode modifiedList(int[] nums, ListNode head) { + if(head==null) return head; + Set arr= new HashSet<>(); + for(int a:nums) arr.add(a); + ListNode dummy=new ListNode(0); + ListNode ans=dummy; + while(head!=null){ + if(!arr.contains(head.val)){ + dummy.next=new ListNode(head.val); + dummy=dummy.next; + } + head=head.next; + } + return ans.next; + } +} \ No newline at end of file diff --git a/3626-smallest-divisible-digit-product-i/README.md b/3626-smallest-divisible-digit-product-i/README.md new file mode 100644 index 00000000..3da039f9 --- /dev/null +++ b/3626-smallest-divisible-digit-product-i/README.md @@ -0,0 +1,34 @@ +

Smallest Divisible Digit Product I

Difficulty: Easy

You are given two integers n and t. Return the smallest number greater than or equal to n such that the product of its digits is divisible by t.

+ +

 

+

Example 1:

+ +
+

Input: n = 10, t = 2

+ +

Output: 10

+ +

Explanation:

+ +

The digit product of 10 is 0, which is divisible by 2, making it the smallest number greater than or equal to 10 that satisfies the condition.

+
+ +

Example 2:

+ +
+

Input: n = 15, t = 3

+ +

Output: 16

+ +

Explanation:

+ +

The digit product of 16 is 6, which is divisible by 3, making it the smallest number greater than or equal to 15 that satisfies the condition.

+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 100
  • +
  • 1 <= t <= 10
  • +
diff --git a/3626-smallest-divisible-digit-product-i/smallest-divisible-digit-product-i.java b/3626-smallest-divisible-digit-product-i/smallest-divisible-digit-product-i.java new file mode 100644 index 00000000..9c65666d --- /dev/null +++ b/3626-smallest-divisible-digit-product-i/smallest-divisible-digit-product-i.java @@ -0,0 +1,16 @@ +public class Solution { + public int smallestNumber(int n, int t) { + while (true) { + if (func(n) % t == 0) return n; + n++; + } + } + public int func(int num) { + int ans = 1; + while (num >0) { + ans*= num%10; + num/=10; + } + return ans; + } +} diff --git a/55-jump-game/README.md b/55-jump-game/README.md new file mode 100644 index 00000000..2b0f2f5f --- /dev/null +++ b/55-jump-game/README.md @@ -0,0 +1,28 @@ +

Jump Game

Difficulty: Medium

You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

+ +

Return true if you can reach the last index, or false otherwise.

+ +

 

+

Example 1:

+ +
+Input: nums = [2,3,1,1,4]
+Output: true
+Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
+
+ +

Example 2:

+ +
+Input: nums = [3,2,1,0,4]
+Output: false
+Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • 0 <= nums[i] <= 105
  • +
diff --git a/55-jump-game/jump-game.java b/55-jump-game/jump-game.java new file mode 100644 index 00000000..e88d7ab7 --- /dev/null +++ b/55-jump-game/jump-game.java @@ -0,0 +1,17 @@ +class Solution { + public boolean canJump(int[] nums) { + boolean flag=true; + for(int a:nums){ + if(a==0){ + flag=false; + } + } + if(flag) return true; + int max=0; + for(int i=0;imax) return false; + max=Math.max(max,nums[i]+i); + } + return true; + } +} \ No newline at end of file diff --git a/554-brick-wall/README.md b/554-brick-wall/README.md new file mode 100644 index 00000000..e5888528 --- /dev/null +++ b/554-brick-wall/README.md @@ -0,0 +1,32 @@ +

Brick Wall

Difficulty: Medium

There is a rectangular brick wall in front of you with n rows of bricks. The ith row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.

+ +

Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.

+ +

Given the 2D array wall that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line.

+ +

 

+

Example 1:

+ +
+Input: wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]
+Output: 2
+
+ +

Example 2:

+ +
+Input: wall = [[1],[1],[1]]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • n == wall.length
  • +
  • 1 <= n <= 104
  • +
  • 1 <= wall[i].length <= 104
  • +
  • 1 <= sum(wall[i].length) <= 2 * 104
  • +
  • sum(wall[i]) is the same for each row i.
  • +
  • 1 <= wall[i][j] <= 231 - 1
  • +
diff --git a/554-brick-wall/brick-wall.java b/554-brick-wall/brick-wall.java new file mode 100644 index 00000000..b41a37ea --- /dev/null +++ b/554-brick-wall/brick-wall.java @@ -0,0 +1,17 @@ +class Solution { + public int leastBricks(List> wall) { + Map map=new HashMap<>(); + int ans=wall.size(); + for(int i=0;iMerge Intervals Difficulty: Medium

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

+ +

 

+

Example 1:

+ +
+Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
+Output: [[1,6],[8,10],[15,18]]
+Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
+
+ +

Example 2:

+ +
+Input: intervals = [[1,4],[4,5]]
+Output: [[1,5]]
+Explanation: Intervals [1,4] and [4,5] are considered overlapping.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= intervals.length <= 104
  • +
  • intervals[i].length == 2
  • +
  • 0 <= starti <= endi <= 104
  • +
diff --git a/56-merge-intervals/merge-intervals.java b/56-merge-intervals/merge-intervals.java new file mode 100644 index 00000000..784e7fa5 --- /dev/null +++ b/56-merge-intervals/merge-intervals.java @@ -0,0 +1,31 @@ +class Solution { + public int[][] merge(int[][] intervals) { + List arr = new ArrayList<>(); + Arrays.sort(intervals, (a, b) ->{ + if(a[0]==b[0]) return a[1]-b[1]; + else return a[0]-b[0]; + }); + int end = intervals[0][1]; + int start = intervals[0][0]; + for (int i = 1; i < intervals.length; i++) { + if (intervals[i][0] <= end) { + end = Math.max(end,intervals[i][1]); + start=Math.min(start,intervals[i][0]); + } else { + int[] a = { start, end }; + arr.add(a); + start = intervals[i][0]; + end = intervals[i][1]; + } + } + int[] a = { start, end }; + arr.add(a); + int[][] ans = new int[arr.size()][2]; + int j = 0; + for (int[] ab : arr) { + ans[j][0] = ab[0]; + ans[j++][1] = ab[1]; + } + return ans; + } +} \ No newline at end of file diff --git a/58-length-of-last-word/README.md b/58-length-of-last-word/README.md new file mode 100644 index 00000000..2c38b6d1 --- /dev/null +++ b/58-length-of-last-word/README.md @@ -0,0 +1,37 @@ +

Length of Last Word

Difficulty: Easy

Given a string s consisting of words and spaces, return the length of the last word in the string.

+ +

A word is a maximal substring consisting of non-space characters only.

+ +

 

+

Example 1:

+ +
+Input: s = "Hello World"
+Output: 5
+Explanation: The last word is "World" with length 5.
+
+ +

Example 2:

+ +
+Input: s = "   fly me   to   the moon  "
+Output: 4
+Explanation: The last word is "moon" with length 4.
+
+ +

Example 3:

+ +
+Input: s = "luffy is still joyboy"
+Output: 6
+Explanation: The last word is "joyboy" with length 6.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of only English letters and spaces ' '.
  • +
  • There will be at least one word in s.
  • +
diff --git a/58-length-of-last-word/length-of-last-word.java b/58-length-of-last-word/length-of-last-word.java new file mode 100644 index 00000000..77e017d0 --- /dev/null +++ b/58-length-of-last-word/length-of-last-word.java @@ -0,0 +1,11 @@ +class Solution { + public int lengthOfLastWord(String s) { + s=s.trim(); + int ans=0; + for(int i=s.length()-1;i>=0;i--){ + if(s.charAt(i)!=' ')ans++; + else break; + } + return ans; + } +} \ No newline at end of file diff --git a/592-fraction-addition-and-subtraction/README.md b/592-fraction-addition-and-subtraction/README.md new file mode 100644 index 00000000..21a19a26 --- /dev/null +++ b/592-fraction-addition-and-subtraction/README.md @@ -0,0 +1,36 @@ +

Fraction Addition and Subtraction

Difficulty: Medium

Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format.

+ +

The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1.

+ +

 

+

Example 1:

+ +
+Input: expression = "-1/2+1/2"
+Output: "0/1"
+
+ +

Example 2:

+ +
+Input: expression = "-1/2+1/2+1/3"
+Output: "1/3"
+
+ +

Example 3:

+ +
+Input: expression = "1/3-1/2"
+Output: "-1/6"
+
+ +

 

+

Constraints:

+ +
    +
  • The input string only contains '0' to '9', '/', '+' and '-'. So does the output.
  • +
  • Each fraction (input and output) has the format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.
  • +
  • The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.
  • +
  • The number of given fractions will be in the range [1, 10].
  • +
  • The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
  • +
diff --git a/592-fraction-addition-and-subtraction/fraction-addition-and-subtraction.java b/592-fraction-addition-and-subtraction/fraction-addition-and-subtraction.java new file mode 100644 index 00000000..7ce58862 --- /dev/null +++ b/592-fraction-addition-and-subtraction/fraction-addition-and-subtraction.java @@ -0,0 +1,72 @@ +class Solution { + public String fractionAddition(String s) { + int deno=1; + boolean flag=false; + String st=""; + List d=new ArrayList<>(); + List n=new ArrayList<>(); + for(int i=1;i0) deno*=Integer.parseInt(st); + d.add(Integer.parseInt(st)); + st=""; + + } + else if(flag){ + st+=s.charAt(i); + } + } + if(st.length()>0){ + deno*=Integer.parseInt(st); + d.add(Integer.parseInt(st)); + } + st=""; + flag=true; + for(int i=0;i0){ + n.add(Integer.parseInt(st)); + } + int num=0; + for(int i=0;i 0) { + if (a % result == 0 && b % result == 0) { + break; + } + result--; + } + return result; +} +} \ No newline at end of file diff --git a/6-zigzag-conversion/README.md b/6-zigzag-conversion/README.md new file mode 100644 index 00000000..eee8a14f --- /dev/null +++ b/6-zigzag-conversion/README.md @@ -0,0 +1,51 @@ +

Zigzag Conversion

Difficulty: Medium

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

+ +
+P   A   H   N
+A P L S I I G
+Y   I   R
+
+ +

And then read line by line: "PAHNAPLSIIGYIR"

+ +

Write the code that will take a string and make this conversion given a number of rows:

+ +
+string convert(string s, int numRows);
+
+ +

 

+

Example 1:

+ +
+Input: s = "PAYPALISHIRING", numRows = 3
+Output: "PAHNAPLSIIGYIR"
+
+ +

Example 2:

+ +
+Input: s = "PAYPALISHIRING", numRows = 4
+Output: "PINALSIGYAHRPI"
+Explanation:
+P     I    N
+A   L S  I G
+Y A   H R
+P     I
+
+ +

Example 3:

+ +
+Input: s = "A", numRows = 1
+Output: "A"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • s consists of English letters (lower-case and upper-case), ',' and '.'.
  • +
  • 1 <= numRows <= 1000
  • +
diff --git a/6-zigzag-conversion/zigzag-conversion.java b/6-zigzag-conversion/zigzag-conversion.java new file mode 100644 index 00000000..1b46f750 --- /dev/null +++ b/6-zigzag-conversion/zigzag-conversion.java @@ -0,0 +1,32 @@ +class Solution { + public String convert(String s, int numRows) { + if(numRows==1)return s; + List> ans=new ArrayList<>(); + for(int i=0;i()); + boolean flag=true; + int idx=0; + while(s.length()!=0){ + ans.get(idx).add(s.charAt(0)); + s=s.substring(1); + if(flag){ + if(idx==numRows-1){ + idx--; + flag=false; + } + else idx++; + } + else{ + if(idx==0){ + flag=true; + idx++; + } + else idx--; + } + } + String st=""; + for(List arr:ans){ + for(char ch:arr) st+=ch; + } + return st; + } +} \ No newline at end of file diff --git a/606-construct-string-from-binary-tree/README.md b/606-construct-string-from-binary-tree/README.md new file mode 100644 index 00000000..3a309726 --- /dev/null +++ b/606-construct-string-from-binary-tree/README.md @@ -0,0 +1,45 @@ +

Construct String from Binary Tree

Difficulty: Medium

Given the root node of a binary tree, your task is to create a string representation of the tree following a specific set of formatting rules. The representation should be based on a preorder traversal of the binary tree and must adhere to the following guidelines:

+ +
    +
  • +

    Node Representation: Each node in the tree should be represented by its integer value.

    +
  • +
  • +

    Parentheses for Children: If a node has at least one child (either left or right), its children should be represented inside parentheses. Specifically:

    + +
      +
    • If a node has a left child, the value of the left child should be enclosed in parentheses immediately following the node's value.
    • +
    • If a node has a right child, the value of the right child should also be enclosed in parentheses. The parentheses for the right child should follow those of the left child.
    • +
    +
  • +
  • +

    Omitting Empty Parentheses: Any empty parentheses pairs (i.e., ()) should be omitted from the final string representation of the tree, with one specific exception: when a node has a right child but no left child. In such cases, you must include an empty pair of parentheses to indicate the absence of the left child. This ensures that the one-to-one mapping between the string representation and the original binary tree structure is maintained.

    + +

    In summary, empty parentheses pairs should be omitted when a node has only a left child or no children. However, when a node has a right child but no left child, an empty pair of parentheses must precede the representation of the right child to reflect the tree's structure accurately.

    +
  • +
+ +

 

+

Example 1:

+ +
+Input: root = [1,2,3,4]
+Output: "1(2(4))(3)"
+Explanation: Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the empty parenthesis pairs. And it will be "1(2(4))(3)".
+
+ +

Example 2:

+ +
+Input: root = [1,2,3,null,4]
+Output: "1(2()(4))(3)"
+Explanation: Almost the same as the first example, except the () after 2 is necessary to indicate the absence of a left child for 2 and the presence of a right child.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -1000 <= Node.val <= 1000
  • +
diff --git a/606-construct-string-from-binary-tree/construct-string-from-binary-tree.java b/606-construct-string-from-binary-tree/construct-string-from-binary-tree.java new file mode 100644 index 00000000..4b4cf01a --- /dev/null +++ b/606-construct-string-from-binary-tree/construct-string-from-binary-tree.java @@ -0,0 +1,26 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + String s=""; + public String tree2str(TreeNode root) { + if(root==null) return ""; + String st="("+tree2str(root.left)+")"; + String temp=tree2str(root.right); + if(temp.length()>0) temp="("+temp+")"; + if(st.equals("()") && temp.length()==0) return ""+root.val; + return ""+root.val+st+temp; + } +} \ No newline at end of file diff --git a/623-add-one-row-to-tree/README.md b/623-add-one-row-to-tree/README.md new file mode 100644 index 00000000..ceee8e9a --- /dev/null +++ b/623-add-one-row-to-tree/README.md @@ -0,0 +1,38 @@ +

Add One Row to Tree

Difficulty: Medium

Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.

+ +

Note that the root node is at depth 1.

+ +

The adding rule is:

+ +
    +
  • Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root.
  • +
  • cur's original left subtree should be the left subtree of the new left subtree root.
  • +
  • cur's original right subtree should be the right subtree of the new right subtree root.
  • +
  • If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.
  • +
+ +

 

+

Example 1:

+ +
+Input: root = [4,2,6,3,1,5], val = 1, depth = 2
+Output: [4,1,1,2,null,null,6,3,1,5]
+
+ +

Example 2:

+ +
+Input: root = [4,2,null,3,1], val = 1, depth = 3
+Output: [4,2,null,1,1,3,null,null,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • The depth of the tree is in the range [1, 104].
  • +
  • -100 <= Node.val <= 100
  • +
  • -105 <= val <= 105
  • +
  • 1 <= depth <= the depth of tree + 1
  • +
diff --git a/623-add-one-row-to-tree/add-one-row-to-tree.java b/623-add-one-row-to-tree/add-one-row-to-tree.java new file mode 100644 index 00000000..2efb5543 --- /dev/null +++ b/623-add-one-row-to-tree/add-one-row-to-tree.java @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode addOneRow(TreeNode root, int val, int depth) { + if(depth==1){ + TreeNode temp=new TreeNode(val); + temp.left=root; + return temp; + } + func(root,val,depth,1); + return root; + } + public void func(TreeNode tree,int val,int depth,int i){ + if(tree==null) return; + if(i==depth-1){ + TreeNode templeft=tree.left; + TreeNode tempright=tree.right; + tree.left=new TreeNode(val); + tree.right=new TreeNode(val); + tree.left.left=templeft; + tree.right.right=tempright; + return; + } + func(tree.left,val,depth,i+1); + func(tree.right,val,depth,i+1); + return ; + } + +} \ No newline at end of file diff --git a/637-average-of-levels-in-binary-tree/README.md b/637-average-of-levels-in-binary-tree/README.md new file mode 100644 index 00000000..518e225e --- /dev/null +++ b/637-average-of-levels-in-binary-tree/README.md @@ -0,0 +1,25 @@ +

Average of Levels in Binary Tree

Difficulty: Easy
Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted. +

 

+

Example 1:

+ +
+Input: root = [3,9,20,null,null,15,7]
+Output: [3.00000,14.50000,11.00000]
+Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.
+Hence return [3, 14.5, 11].
+
+ +

Example 2:

+ +
+Input: root = [3,9,20,15,7]
+Output: [3.00000,14.50000,11.00000]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -231 <= Node.val <= 231 - 1
  • +
diff --git a/637-average-of-levels-in-binary-tree/average-of-levels-in-binary-tree.java b/637-average-of-levels-in-binary-tree/average-of-levels-in-binary-tree.java new file mode 100644 index 00000000..a81f4b30 --- /dev/null +++ b/637-average-of-levels-in-binary-tree/average-of-levels-in-binary-tree.java @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List averageOfLevels(TreeNode root) { + List arr=new ArrayList<>(); + if(root==null) return arr; + Queue stack=new LinkedList<>(); + stack.add(root); + while(!stack.isEmpty()){ + int size=stack.size(); + List tempArr=new ArrayList<>(); + Long sum=0L; + for(int i=0;iMaximum Binary Tree Difficulty: Medium

You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:

+ +
    +
  1. Create a root node whose value is the maximum value in nums.
  2. +
  3. Recursively build the left subtree on the subarray prefix to the left of the maximum value.
  4. +
  5. Recursively build the right subtree on the subarray suffix to the right of the maximum value.
  6. +
+ +

Return the maximum binary tree built from nums.

+ +

 

+

Example 1:

+ +
+Input: nums = [3,2,1,6,0,5]
+Output: [6,3,5,null,2,0,null,null,1]
+Explanation: The recursive calls are as follow:
+- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].
+    - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].
+        - Empty array, so no child.
+        - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].
+            - Empty array, so no child.
+            - Only one element, so child is a node with value 1.
+    - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].
+        - Only one element, so child is a node with value 0.
+        - Empty array, so no child.
+
+ +

Example 2:

+ +
+Input: nums = [3,2,1]
+Output: [3,null,2,null,1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 0 <= nums[i] <= 1000
  • +
  • All integers in nums are unique.
  • +
diff --git a/654-maximum-binary-tree/maximum-binary-tree.java b/654-maximum-binary-tree/maximum-binary-tree.java new file mode 100644 index 00000000..996ef9a7 --- /dev/null +++ b/654-maximum-binary-tree/maximum-binary-tree.java @@ -0,0 +1,35 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode constructMaximumBinaryTree(int[] nums) { + return func(nums,0,nums.length-1); + } + public TreeNode func(int[] nums,int i,int j){ + if(i>j) return null; + int max=Integer.MIN_VALUE; + int k=i; + for(int id=i;id<=j;id++){ + if(maxFind K Closest Elements Difficulty: Medium

Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.

+ +

An integer a is closer to x than an integer b if:

+ +
    +
  • |a - x| < |b - x|, or
  • +
  • |a - x| == |b - x| and a < b
  • +
+ +

 

+

Example 1:

+ +
+

Input: arr = [1,2,3,4,5], k = 4, x = 3

+ +

Output: [1,2,3,4]

+
+ +

Example 2:

+ +
+

Input: arr = [1,1,2,3,4,5], k = 4, x = -1

+ +

Output: [1,1,2,3]

+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= arr.length
  • +
  • 1 <= arr.length <= 104
  • +
  • arr is sorted in ascending order.
  • +
  • -104 <= arr[i], x <= 104
  • +
diff --git a/658-find-k-closest-elements/find-k-closest-elements.java b/658-find-k-closest-elements/find-k-closest-elements.java new file mode 100644 index 00000000..2e0fb46a --- /dev/null +++ b/658-find-k-closest-elements/find-k-closest-elements.java @@ -0,0 +1,17 @@ +class Solution { + public List findClosestElements(int[] arr, int k, int x) { + PriorityQueue pq=new PriorityQueue<>((a,b)->{ + if(a[0]==b[0]) return a[1]-b[1]; + else return a[0]-b[0]; + }); + List ans=new ArrayList<>(); + for(int i=0;iMaximum Width of Binary Tree Difficulty: Medium

Given the root of a binary tree, return the maximum width of the given tree.

+ +

The maximum width of a tree is the maximum width among all levels.

+ +

The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.

+ +

It is guaranteed that the answer will in the range of a 32-bit signed integer.

+ +

 

+

Example 1:

+ +
+Input: root = [1,3,2,5,3,null,9]
+Output: 4
+Explanation: The maximum width exists in the third level with length 4 (5,3,null,9).
+
+ +

Example 2:

+ +
+Input: root = [1,3,2,5,null,null,9,6,null,7]
+Output: 7
+Explanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).
+
+ +

Example 3:

+ +
+Input: root = [1,3,2,5]
+Output: 2
+Explanation: The maximum width exists in the second level with length 2 (3,2).
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 3000].
  • +
  • -100 <= Node.val <= 100
  • +
diff --git a/662-maximum-width-of-binary-tree/maximum-width-of-binary-tree.java b/662-maximum-width-of-binary-tree/maximum-width-of-binary-tree.java new file mode 100644 index 00000000..8f73f6f0 --- /dev/null +++ b/662-maximum-width-of-binary-tree/maximum-width-of-binary-tree.java @@ -0,0 +1,45 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int widthOfBinaryTree(TreeNode root) { + int ans=0; + Queue stack=new LinkedList<>(); + stack.offer(new pair(root,0)); + while(!stack.isEmpty()){ + int n=stack.size(); + int inc=stack.peek().id; + int first=0,last=0; + for(int i=0;iTrim a Binary Search Tree Difficulty: Medium

Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.

+ +

Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

+ +

 

+

Example 1:

+ +
+Input: root = [1,0,2], low = 1, high = 2
+Output: [1,null,2]
+
+ +

Example 2:

+ +
+Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
+Output: [3,2,null,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • 0 <= Node.val <= 104
  • +
  • The value of each node in the tree is unique.
  • +
  • root is guaranteed to be a valid binary search tree.
  • +
  • 0 <= low <= high <= 104
  • +
diff --git a/669-trim-a-binary-search-tree/trim-a-binary-search-tree.java b/669-trim-a-binary-search-tree/trim-a-binary-search-tree.java new file mode 100644 index 00000000..c8f92e6e --- /dev/null +++ b/669-trim-a-binary-search-tree/trim-a-binary-search-tree.java @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode trimBST(TreeNode root, int low, int high) { + if(root==null) return root; + root.left=trimBST(root.left,low,high); + root.right=trimBST(root.right,low,high); + if(root.val>high || root.valAdd Binary Difficulty: Easy

Given two binary strings a and b, return their sum as a binary string.

+ +

 

+

Example 1:

+
Input: a = "11", b = "1"
+Output: "100"
+

Example 2:

+
Input: a = "1010", b = "1011"
+Output: "10101"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= a.length, b.length <= 104
  • +
  • a and b consist only of '0' or '1' characters.
  • +
  • Each string does not contain leading zeros except for the zero itself.
  • +
diff --git a/67-add-binary/add-binary.java b/67-add-binary/add-binary.java new file mode 100644 index 00000000..047e2f69 --- /dev/null +++ b/67-add-binary/add-binary.java @@ -0,0 +1,21 @@ +class Solution { + public String addBinary(String a, String b) { + int n=0; + String ans=""; + int id1=a.length()-1; + while(a.length()!=0 || b.length()!=0){ + if(a.length()>0){ + n+=Character.getNumericValue(a.charAt(a.length()-1)); + a=a.substring(0,a.length()-1); + } + if(b.length()>0){ + n+=Character.getNumericValue(b.charAt(b.length()-1)); + b=b.substring(0,b.length()-1); + } + ans=(n%2)+ans; + n/=2; + } + if(n!=0) ans=n+ans; + return ans; + } +} \ No newline at end of file diff --git a/695-max-area-of-island/README.md b/695-max-area-of-island/README.md new file mode 100644 index 00000000..b5bdf65f --- /dev/null +++ b/695-max-area-of-island/README.md @@ -0,0 +1,31 @@ +

Max Area of Island

Difficulty: Medium

You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

+ +

The area of an island is the number of cells with a value 1 in the island.

+ +

Return the maximum area of an island in grid. If there is no island, return 0.

+ +

 

+

Example 1:

+ +
+Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
+Output: 6
+Explanation: The answer is not 11, because the island must be connected 4-directionally.
+
+ +

Example 2:

+ +
+Input: grid = [[0,0,0,0,0,0,0,0]]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 50
  • +
  • grid[i][j] is either 0 or 1.
  • +
diff --git a/695-max-area-of-island/max-area-of-island.java b/695-max-area-of-island/max-area-of-island.java new file mode 100644 index 00000000..bc1ee3fb --- /dev/null +++ b/695-max-area-of-island/max-area-of-island.java @@ -0,0 +1,41 @@ +class Solution { + public int maxAreaOfIsland(int[][] grid) { + int max=0; + for(int i=0;i q=new LinkedList<>(); + q.add(new pair(id,j)); + int[][] direction = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; + while(!q.isEmpty()){ + ans++; + pair temp=q.poll(); + int r=temp.first; + int c=temp.second; + for (int[] i : direction) { + if (r + i[0] < grid.length && r + i[0] >= 0 && c + i[1] < grid[0].length && c + i[1] >= 0 && grid[r + i[0]][c + i[1]]==1 ) { + q.add(new pair(r+i[0],c+i[1])); + grid[r + i[0]][c + i[1]] = 2; + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/725-split-linked-list-in-parts/README.md b/725-split-linked-list-in-parts/README.md new file mode 100644 index 00000000..63190991 --- /dev/null +++ b/725-split-linked-list-in-parts/README.md @@ -0,0 +1,36 @@ +

Split Linked List in Parts

Difficulty: Medium

Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts.

+ +

The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.

+ +

The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.

+ +

Return an array of the k parts.

+ +

 

+

Example 1:

+ +
+Input: head = [1,2,3], k = 5
+Output: [[1],[2],[3],[],[]]
+Explanation:
+The first element output[0] has output[0].val = 1, output[0].next = null.
+The last element output[4] is null, but its string representation as a ListNode is [].
+
+ +

Example 2:

+ +
+Input: head = [1,2,3,4,5,6,7,8,9,10], k = 3
+Output: [[1,2,3,4],[5,6,7],[8,9,10]]
+Explanation:
+The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 1000].
  • +
  • 0 <= Node.val <= 1000
  • +
  • 1 <= k <= 50
  • +
diff --git a/725-split-linked-list-in-parts/split-linked-list-in-parts.java b/725-split-linked-list-in-parts/split-linked-list-in-parts.java new file mode 100644 index 00000000..45da64d6 --- /dev/null +++ b/725-split-linked-list-in-parts/split-linked-list-in-parts.java @@ -0,0 +1,79 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode[] splitListToParts(ListNode head, int k) { + int size=0; + ListNode temp=head; + while(temp!=null){ + size++; + temp=temp.next; + } + ListNode ans[]=new ListNode[k]; + if(size0){ + if(size>0){ + ListNode a=new ListNode(head.val); + head=head.next; + size--; + ans[i++]=a; + } + else{ + ans[i++]=null; + + } + } + } + else{ + if(size%k!=0){ + int id=size%k; + size/=k; + int i=0; + while(id-->0){ + ListNode b=new ListNode(0); + ListNode append=b; + for(int j=0;j<=size;j++){ + b.next=new ListNode(head.val); + head=head.next; + b=b.next; + } + ans[i++]=append.next; + k--; + } + while(k-->0){ + ListNode c=new ListNode(0); + ListNode append1=c; + for(int j=0;j0){ + ListNode c=new ListNode(0); + ListNode append1=c; + for(int j=0;jMy Calendar I Difficulty: Medium

You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a double booking.

+ +

A double booking happens when two events have some non-empty intersection (i.e., some moment is common to both events.).

+ +

The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end), the range of real numbers x such that start <= x < end.

+ +

Implement the MyCalendar class:

+ +
    +
  • MyCalendar() Initializes the calendar object.
  • +
  • boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a double booking. Otherwise, return false and do not add the event to the calendar.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["MyCalendar", "book", "book", "book"]
+[[], [10, 20], [15, 25], [20, 30]]
+Output
+[null, true, false, true]
+
+Explanation
+MyCalendar myCalendar = new MyCalendar();
+myCalendar.book(10, 20); // return True
+myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.
+myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.
+ +

 

+

Constraints:

+ +
    +
  • 0 <= start < end <= 109
  • +
  • At most 1000 calls will be made to book.
  • +
diff --git a/729-my-calendar-i/my-calendar-i.java b/729-my-calendar-i/my-calendar-i.java new file mode 100644 index 00000000..f4c6a512 --- /dev/null +++ b/729-my-calendar-i/my-calendar-i.java @@ -0,0 +1,23 @@ +class MyCalendar { +List arr; + public MyCalendar() { + arr=new ArrayList<>(); + } + + public boolean book(int start, int end) { + for(int[] nums:arr){ + if(startnums[0]){ + return false; + } + } + arr.add(new int[]{start,end}); + Collections.sort(arr,(a,b) -> a[0] - b[0]); + return true; + } +} + +/** + * Your MyCalendar object will be instantiated and called as such: + * MyCalendar obj = new MyCalendar(); + * boolean param_1 = obj.book(start,end); + */ \ No newline at end of file diff --git a/733-flood-fill/README.md b/733-flood-fill/README.md new file mode 100644 index 00000000..63b0feba --- /dev/null +++ b/733-flood-fill/README.md @@ -0,0 +1,53 @@ +

Flood Fill

Difficulty: Easy

You are given an image represented by an m x n grid of integers image, where image[i][j] represents the pixel value of the image. You are also given three integers sr, sc, and color. Your task is to perform a flood fill on the image starting from the pixel image[sr][sc].

+ +

To perform a flood fill:

+ +
    +
  1. Begin with the starting pixel and change its color to color.
  2. +
  3. Perform the same process for each pixel that is directly adjacent (pixels that share a side with the original pixel, either horizontally or vertically) and shares the same color as the starting pixel.
  4. +
  5. Keep repeating this process by checking neighboring pixels of the updated pixels and modifying their color if it matches the original color of the starting pixel.
  6. +
  7. The process stops when there are no more adjacent pixels of the original color to update.
  8. +
+ +

Return the modified image after performing the flood fill.

+ +

 

+

Example 1:

+ +
+

Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2

+ +

Output: [[2,2,2],[2,2,0],[2,0,1]]

+ +

Explanation:

+ +

+ +

From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.

+ +

Note the bottom corner is not colored 2, because it is not horizontally or vertically connected to the starting pixel.

+
+ +

Example 2:

+ +
+

Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0

+ +

Output: [[0,0,0],[0,0,0]]

+ +

Explanation:

+ +

The starting pixel is already colored with 0, which is the same as the target color. Therefore, no changes are made to the image.

+
+ +

 

+

Constraints:

+ +
    +
  • m == image.length
  • +
  • n == image[i].length
  • +
  • 1 <= m, n <= 50
  • +
  • 0 <= image[i][j], color < 216
  • +
  • 0 <= sr < m
  • +
  • 0 <= sc < n
  • +
diff --git a/733-flood-fill/flood-fill.java b/733-flood-fill/flood-fill.java new file mode 100644 index 00000000..a0d23698 --- /dev/null +++ b/733-flood-fill/flood-fill.java @@ -0,0 +1,34 @@ +class Solution { + public int[][] floodFill(int[][] image, int sr, int sc, int color) { + int start=image[sr][sc]; + bfs(start,sr,sc,color,image); + return image; + } + class pair{ + int first; + int second; + pair(int first,int second){ + this.first=first; + this.second=second; + } + } + public void bfs(int start,int row,int col,int color,int[][] arr){ + arr[row][col]=color; + Queue q=new LinkedList<>(); + boolean[][] visited=new boolean[arr.length][arr[0].length]; + q.add(new pair(row,col)); + while(!q.isEmpty()){ + pair temp=q.poll(); + int r=temp.first; + int c=temp.second; + int[][]direction={{0,1},{1,0},{0,-1},{-1,0}}; + for(int[] num:direction){ + if(r+num[0]=0 && c+num[1]>=0 && c+num[1]Sort Colors Difficulty: Medium

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

+ +

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

+ +

You must solve this problem without using the library's sort function.

+ +

 

+

Example 1:

+ +
+Input: nums = [2,0,2,1,1,0]
+Output: [0,0,1,1,2,2]
+
+ +

Example 2:

+ +
+Input: nums = [2,0,1]
+Output: [0,1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 300
  • +
  • nums[i] is either 0, 1, or 2.
  • +
+ +

 

+

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

diff --git a/75-sort-colors/sort-colors.java b/75-sort-colors/sort-colors.java new file mode 100644 index 00000000..b8334136 --- /dev/null +++ b/75-sort-colors/sort-colors.java @@ -0,0 +1,16 @@ +class Solution { + public void sortColors(int[] nums) { + int zero=0; + int one=0; + int two=0; + int i=0; + for(int a:nums){ + if(a==0)zero++; + if(a==1)one++; + if(a==2)two++; + } + while(zero-->0)nums[i++]=0; + while(one-->0) nums[i++]=1; + while(two-->0) nums[i++]=2; + } +} \ No newline at end of file diff --git a/783-search-in-a-binary-search-tree/README.md b/783-search-in-a-binary-search-tree/README.md new file mode 100644 index 00000000..03534276 --- /dev/null +++ b/783-search-in-a-binary-search-tree/README.md @@ -0,0 +1,28 @@ +

Search in a Binary Search Tree

Difficulty: Easy

You are given the root of a binary search tree (BST) and an integer val.

+ +

Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.

+ +

 

+

Example 1:

+ +
+Input: root = [4,2,7,1,3], val = 2
+Output: [2,1,3]
+
+ +

Example 2:

+ +
+Input: root = [4,2,7,1,3], val = 5
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 5000].
  • +
  • 1 <= Node.val <= 107
  • +
  • root is a binary search tree.
  • +
  • 1 <= val <= 107
  • +
diff --git a/784-insert-into-a-binary-search-tree/README.md b/784-insert-into-a-binary-search-tree/README.md new file mode 100644 index 00000000..a0fc67b1 --- /dev/null +++ b/784-insert-into-a-binary-search-tree/README.md @@ -0,0 +1,38 @@ +

Insert into a Binary Search Tree

Difficulty: Medium

You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

+ +

Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

+ +

 

+

Example 1:

+ +
+Input: root = [4,2,7,1,3], val = 5
+Output: [4,2,7,1,3,5]
+Explanation: Another accepted tree is:
+
+
+ +

Example 2:

+ +
+Input: root = [40,20,60,10,30,50,70], val = 25
+Output: [40,20,60,10,30,50,70,null,null,25]
+
+ +

Example 3:

+ +
+Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5
+Output: [4,2,7,1,3,5]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree will be in the range [0, 104].
  • +
  • -108 <= Node.val <= 108
  • +
  • All the values Node.val are unique.
  • +
  • -108 <= val <= 108
  • +
  • It's guaranteed that val does not exist in the original BST.
  • +
diff --git a/80-remove-duplicates-from-sorted-array-ii/README.md b/80-remove-duplicates-from-sorted-array-ii/README.md new file mode 100644 index 00000000..ded62415 --- /dev/null +++ b/80-remove-duplicates-from-sorted-array-ii/README.md @@ -0,0 +1,53 @@ +

Remove Duplicates from Sorted Array II

Difficulty: Medium

Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.

+ +

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

+ +

Return k after placing the final result in the first k slots of nums.

+ +

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

+ +

Custom Judge:

+ +

The judge will test your solution with the following code:

+ +
+int[] nums = [...]; // Input array
+int[] expectedNums = [...]; // The expected answer with correct length
+
+int k = removeDuplicates(nums); // Calls your implementation
+
+assert k == expectedNums.length;
+for (int i = 0; i < k; i++) {
+    assert nums[i] == expectedNums[i];
+}
+
+ +

If all assertions pass, then your solution will be accepted.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,1,1,2,2,3]
+Output: 5, nums = [1,1,2,2,3,_]
+Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
+It does not matter what you leave beyond the returned k (hence they are underscores).
+
+ +

Example 2:

+ +
+Input: nums = [0,0,1,1,1,1,2,3,3]
+Output: 7, nums = [0,0,1,1,2,3,3,_,_]
+Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.
+It does not matter what you leave beyond the returned k (hence they are underscores).
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • -104 <= nums[i] <= 104
  • +
  • nums is sorted in non-decreasing order.
  • +
diff --git a/80-remove-duplicates-from-sorted-array-ii/remove-duplicates-from-sorted-array-ii.java b/80-remove-duplicates-from-sorted-array-ii/remove-duplicates-from-sorted-array-ii.java new file mode 100644 index 00000000..cb19e9f8 --- /dev/null +++ b/80-remove-duplicates-from-sorted-array-ii/remove-duplicates-from-sorted-array-ii.java @@ -0,0 +1,16 @@ +class Solution { + public int removeDuplicates(int[] nums) { + Map map=new HashMap<>(); + int ans=0; + int j=0; + for(int i=0;iIs Graph Bipartite? Difficulty: Medium

There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties:

+ +
    +
  • There are no self-edges (graph[u] does not contain u).
  • +
  • There are no parallel edges (graph[u] does not contain duplicate values).
  • +
  • If v is in graph[u], then u is in graph[v] (the graph is undirected).
  • +
  • The graph may not be connected, meaning there may be two nodes u and v such that there is no path between them.
  • +
+ +

A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.

+ +

Return true if and only if it is bipartite.

+ +

 

+

Example 1:

+ +
+Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
+Output: false
+Explanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.
+ +

Example 2:

+ +
+Input: graph = [[1,3],[0,2],[1,3],[0,2]]
+Output: true
+Explanation: We can partition the nodes into two sets: {0, 2} and {1, 3}.
+ +

 

+

Constraints:

+ +
    +
  • graph.length == n
  • +
  • 1 <= n <= 100
  • +
  • 0 <= graph[u].length < n
  • +
  • 0 <= graph[u][i] <= n - 1
  • +
  • graph[u] does not contain u.
  • +
  • All the values of graph[u] are unique.
  • +
  • If graph[u] contains v, then graph[v] contains u.
  • +
diff --git a/801-is-graph-bipartite/is-graph-bipartite.java b/801-is-graph-bipartite/is-graph-bipartite.java new file mode 100644 index 00000000..fb2943c4 --- /dev/null +++ b/801-is-graph-bipartite/is-graph-bipartite.java @@ -0,0 +1,33 @@ +class Solution { + public boolean isBipartite(int[][] graph) { + int[]vis=new int[graph.length]; + for(int i=0;i q=new LinkedList<>(); + int k=idx; + vis[idx]=1; + q.add(idx); + while(!q.isEmpty()){ + idx=q.poll(); + for(int i=0;iK-th Smallest Prime Fraction Difficulty: Medium

You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k.

+ +

For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].

+ +

Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].

+ +

 

+

Example 1:

+ +
+Input: arr = [1,2,3,5], k = 3
+Output: [2,5]
+Explanation: The fractions to be considered in sorted order are:
+1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.
+The third fraction is 2/5.
+
+ +

Example 2:

+ +
+Input: arr = [1,7], k = 1
+Output: [1,7]
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= arr.length <= 1000
  • +
  • 1 <= arr[i] <= 3 * 104
  • +
  • arr[0] == 1
  • +
  • arr[i] is a prime number for i > 0.
  • +
  • All the numbers of arr are unique and sorted in strictly increasing order.
  • +
  • 1 <= k <= arr.length * (arr.length - 1) / 2
  • +
+ +

 

+Follow up: Can you solve the problem with better than O(n2) complexity? \ No newline at end of file diff --git a/802-k-th-smallest-prime-fraction/k-th-smallest-prime-fraction.java b/802-k-th-smallest-prime-fraction/k-th-smallest-prime-fraction.java new file mode 100644 index 00000000..af9666a0 --- /dev/null +++ b/802-k-th-smallest-prime-fraction/k-th-smallest-prime-fraction.java @@ -0,0 +1,16 @@ +class Solution { + public int[] kthSmallestPrimeFraction(int[] arr, int k) { + PriorityQueue pq=new PriorityQueue<>((a,b)->Double.compare(a[0]/a[1], b[0]/b[1])); + for(int i=0;i1){ + pq.poll(); + } + double[] temp=pq.poll(); + int ans[]=new int[]{(int)(temp[0]),(int)(temp[1])}; + return ans; + } +} \ No newline at end of file diff --git a/812-rotate-string/README.md b/812-rotate-string/README.md new file mode 100644 index 00000000..deae25c7 --- /dev/null +++ b/812-rotate-string/README.md @@ -0,0 +1,23 @@ +

Rotate String

Difficulty: Easy

Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.

+ +

A shift on s consists of moving the leftmost character of s to the rightmost position.

+ +
    +
  • For example, if s = "abcde", then it will be "bcdea" after one shift.
  • +
+ +

 

+

Example 1:

+
Input: s = "abcde", goal = "cdeab"
+Output: true
+

Example 2:

+
Input: s = "abcde", goal = "abced"
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length, goal.length <= 100
  • +
  • s and goal consist of lowercase English letters.
  • +
diff --git a/812-rotate-string/rotate-string.java b/812-rotate-string/rotate-string.java new file mode 100644 index 00000000..a00069da --- /dev/null +++ b/812-rotate-string/rotate-string.java @@ -0,0 +1,13 @@ +class Solution { + public boolean rotateString(String s, String goal) { + int i=0; + while(iLongest Mountain in Array Difficulty: Medium

You may recall that an array arr is a mountain array if and only if:

+ +
    +
  • arr.length >= 3
  • +
  • There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: +
      +
    • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
    • +
    • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
    • +
    +
  • +
+ +

Given an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray.

+ +

 

+

Example 1:

+ +
+Input: arr = [2,1,4,7,3,2,5]
+Output: 5
+Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
+
+ +

Example 2:

+ +
+Input: arr = [2,2,2]
+Output: 0
+Explanation: There is no mountain.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= arr.length <= 104
  • +
  • 0 <= arr[i] <= 104
  • +
+ +

 

+

Follow up:

+ +
    +
  • Can you solve it using only one pass?
  • +
  • Can you solve it in O(1) space?
  • +
diff --git a/875-longest-mountain-in-array/longest-mountain-in-array.java b/875-longest-mountain-in-array/longest-mountain-in-array.java new file mode 100644 index 00000000..fc40f002 --- /dev/null +++ b/875-longest-mountain-in-array/longest-mountain-in-array.java @@ -0,0 +1,17 @@ +class Solution { + public int longestMountain(int[] arr) { + if(arr.length<3) return 0; + int ans=0; + for(int i=1;iarr[i+1]){ + int left=i-1; + int right=i+1; + while(left>0 && arr[left]>arr[left-1]) left--; + while(rightarr[right+1]) right++; + ans=Math.max(ans,right-left+1); + i=right; + } + } + return ans; + } +} \ No newline at end of file diff --git a/88-merge-sorted-array/README.md b/88-merge-sorted-array/README.md new file mode 100644 index 00000000..066a6f84 --- /dev/null +++ b/88-merge-sorted-array/README.md @@ -0,0 +1,48 @@ +

Merge Sorted Array

Difficulty: Easy

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

+ +

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

+ +

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

+ +

 

+

Example 1:

+ +
+Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
+Output: [1,2,2,3,5,6]
+Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
+The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
+
+ +

Example 2:

+ +
+Input: nums1 = [1], m = 1, nums2 = [], n = 0
+Output: [1]
+Explanation: The arrays we are merging are [1] and [].
+The result of the merge is [1].
+
+ +

Example 3:

+ +
+Input: nums1 = [0], m = 0, nums2 = [1], n = 1
+Output: [1]
+Explanation: The arrays we are merging are [] and [1].
+The result of the merge is [1].
+Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
+
+ +

 

+

Constraints:

+ +
    +
  • nums1.length == m + n
  • +
  • nums2.length == n
  • +
  • 0 <= m, n <= 200
  • +
  • 1 <= m + n <= 200
  • +
  • -109 <= nums1[i], nums2[j] <= 109
  • +
+ +

 

+

Follow up: Can you come up with an algorithm that runs in O(m + n) time?

diff --git a/88-merge-sorted-array/merge-sorted-array.java b/88-merge-sorted-array/merge-sorted-array.java new file mode 100644 index 00000000..a63dbc53 --- /dev/null +++ b/88-merge-sorted-array/merge-sorted-array.java @@ -0,0 +1,17 @@ +class Solution { + public static void merge(int[] nums1, int m, int[] nums2, int n) { + int j=0; + for(int i=0;iPeak Index in a Mountain Array Difficulty: Medium

You are given an integer mountain array arr of length n where the values increase to a peak element and then decrease.

+ +

Return the index of the peak element.

+ +

Your task is to solve it in O(log(n)) time complexity.

+ +

 

+

Example 1:

+ +
+

Input: arr = [0,1,0]

+ +

Output: 1

+
+ +

Example 2:

+ +
+

Input: arr = [0,2,1,0]

+ +

Output: 1

+
+ +

Example 3:

+ +
+

Input: arr = [0,10,5,2]

+ +

Output: 1

+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= arr.length <= 105
  • +
  • 0 <= arr[i] <= 106
  • +
  • arr is guaranteed to be a mountain array.
  • +
diff --git a/882-peak-index-in-a-mountain-array/peak-index-in-a-mountain-array.java b/882-peak-index-in-a-mountain-array/peak-index-in-a-mountain-array.java new file mode 100644 index 00000000..de2fb471 --- /dev/null +++ b/882-peak-index-in-a-mountain-array/peak-index-in-a-mountain-array.java @@ -0,0 +1,14 @@ +class Solution { + public int peakIndexInMountainArray(int[] arr) { + int i=0; + int j=arr.length-1; + while(iBuddy Strings Difficulty: Easy

Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.

+ +

Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].

+ +
    +
  • For example, swapping at indices 0 and 2 in "abcd" results in "cbad".
  • +
+ +

 

+

Example 1:

+ +
+Input: s = "ab", goal = "ba"
+Output: true
+Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
+
+ +

Example 2:

+ +
+Input: s = "ab", goal = "ab"
+Output: false
+Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.
+
+ +

Example 3:

+ +
+Input: s = "aa", goal = "aa"
+Output: true
+Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length, goal.length <= 2 * 104
  • +
  • s and goal consist of lowercase letters.
  • +
diff --git a/889-buddy-strings/buddy-strings.java b/889-buddy-strings/buddy-strings.java new file mode 100644 index 00000000..f4a10371 --- /dev/null +++ b/889-buddy-strings/buddy-strings.java @@ -0,0 +1,30 @@ +class Solution { + public boolean buddyStrings(String s, String goal) { + if(s.length()!=goal.length()) return false; + boolean flag=false; + char[] crr=new char[4]; + int[]arr=new int[26]; + int id=0; + if(s.equals(goal)) flag=true; + for(int i=0;i=2) return true; + } + } + else{ + if(crr[0]!=crr[3] || crr[1]!=crr[2]) return false; + else return true; + } + return false; + } +} \ No newline at end of file diff --git a/890-lemonade-change/README.md b/890-lemonade-change/README.md new file mode 100644 index 00000000..c132dffb --- /dev/null +++ b/890-lemonade-change/README.md @@ -0,0 +1,38 @@ +

Lemonade Change

Difficulty: Easy

At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5.

+ +

Note that you do not have any change in hand at first.

+ +

Given an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise.

+ +

 

+

Example 1:

+ +
+Input: bills = [5,5,5,10,20]
+Output: true
+Explanation: 
+From the first 3 customers, we collect three $5 bills in order.
+From the fourth customer, we collect a $10 bill and give back a $5.
+From the fifth customer, we give a $10 bill and a $5 bill.
+Since all customers got correct change, we output true.
+
+ +

Example 2:

+ +
+Input: bills = [5,5,10,10,20]
+Output: false
+Explanation: 
+From the first two customers in order, we collect two $5 bills.
+For the next two customers in order, we collect a $10 bill and give back a $5 bill.
+For the last customer, we can not give the change of $15 back because we only have two $10 bills.
+Since not every customer received the correct change, the answer is false.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= bills.length <= 105
  • +
  • bills[i] is either 5, 10, or 20.
  • +
diff --git a/890-lemonade-change/lemonade-change.java b/890-lemonade-change/lemonade-change.java new file mode 100644 index 00000000..350bd47a --- /dev/null +++ b/890-lemonade-change/lemonade-change.java @@ -0,0 +1,26 @@ +class Solution { + public boolean lemonadeChange(int[] bills) { + int five = 0; + int ten = 0; + for (int a : bills) { + if (a == 20) { + if (five > 0 && ten > 0) { + five--; + ten--; + } else if (five > 2) + five -= 3; + else + return false; + } else if (a == 10) { + if (five > 0) { + five--; + } else + return false; + ten++; + } else { + five++; + } + } + return true; + } +} \ No newline at end of file diff --git a/893-all-nodes-distance-k-in-binary-tree/README.md b/893-all-nodes-distance-k-in-binary-tree/README.md new file mode 100644 index 00000000..8d8dd100 --- /dev/null +++ b/893-all-nodes-distance-k-in-binary-tree/README.md @@ -0,0 +1,30 @@ +

All Nodes Distance K in Binary Tree

Difficulty: Medium

Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node.

+ +

You can return the answer in any order.

+ +

 

+

Example 1:

+ +
+Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
+Output: [7,4,1]
+Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
+
+ +

Example 2:

+ +
+Input: root = [1], target = 1, k = 3
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 500].
  • +
  • 0 <= Node.val <= 500
  • +
  • All the values Node.val are unique.
  • +
  • target is the value of one of the nodes in the tree.
  • +
  • 0 <= k <= 1000
  • +
diff --git a/893-all-nodes-distance-k-in-binary-tree/all-nodes-distance-k-in-binary-tree.java b/893-all-nodes-distance-k-in-binary-tree/all-nodes-distance-k-in-binary-tree.java new file mode 100644 index 00000000..fc135d4a --- /dev/null +++ b/893-all-nodes-distance-k-in-binary-tree/all-nodes-distance-k-in-binary-tree.java @@ -0,0 +1,53 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List distanceK(TreeNode root, TreeNode target, int k) { + Map map=new HashMap<>(); + put_map(root,map); + Map check=new HashMap<>(); + Queue stack=new LinkedList<>(); + stack.offer(target); + check.put(target,true); + int dis=0; + while(!stack.isEmpty()){ + if(dis==k) break; + dis++; + int n=stack.size(); + for(int i=0;i ans=new ArrayList<>(); + while(!stack.isEmpty()){ + ans.add(stack.poll().val); + } + return ans; + + } + public void put_map(TreeNode root,Map map){ + if(root==null) return; + if(root.left!=null) map.put(root.left,root); + if(root.right!=null) map.put(root.right,root); + put_map(root.left,map); + put_map(root.right,map); + } +} \ No newline at end of file diff --git a/9-palindrome-number/README.md b/9-palindrome-number/README.md new file mode 100644 index 00000000..60ccf187 --- /dev/null +++ b/9-palindrome-number/README.md @@ -0,0 +1,36 @@ +

Palindrome Number

Difficulty: Easy

Given an integer x, return true if x is a palindrome, and false otherwise.

+ +

 

+

Example 1:

+ +
+Input: x = 121
+Output: true
+Explanation: 121 reads as 121 from left to right and from right to left.
+
+ +

Example 2:

+ +
+Input: x = -121
+Output: false
+Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
+
+ +

Example 3:

+ +
+Input: x = 10
+Output: false
+Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
+
+ +

 

+

Constraints:

+ +
    +
  • -231 <= x <= 231 - 1
  • +
+ +

 

+Follow up: Could you solve it without converting the integer to a string? \ No newline at end of file diff --git a/9-palindrome-number/palindrome-number.java b/9-palindrome-number/palindrome-number.java new file mode 100644 index 00000000..a191ddbd --- /dev/null +++ b/9-palindrome-number/palindrome-number.java @@ -0,0 +1,17 @@ +class Solution { + public boolean isPalindrome(int x) { + int y=x; + int new_element=0; + while(y>0){ + int k=y%10; + y=y/10; + new_element=new_element*10+k; + } + if(x==new_element){ + return true; + } + else{ + return false; + } + } +} \ No newline at end of file diff --git a/90-subsets-ii/README.md b/90-subsets-ii/README.md new file mode 100644 index 00000000..0a771dc0 --- /dev/null +++ b/90-subsets-ii/README.md @@ -0,0 +1,19 @@ +

Subsets II

Difficulty: Medium

Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

+ +

The solution set must not contain duplicate subsets. Return the solution in any order.

+ +

 

+

Example 1:

+
Input: nums = [1,2,2]
+Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
+

Example 2:

+
Input: nums = [0]
+Output: [[],[0]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 10
  • +
  • -10 <= nums[i] <= 10
  • +
diff --git a/90-subsets-ii/subsets-ii.java b/90-subsets-ii/subsets-ii.java new file mode 100644 index 00000000..f01104f9 --- /dev/null +++ b/90-subsets-ii/subsets-ii.java @@ -0,0 +1,18 @@ +class Solution { + public List> subsetsWithDup(int[] nums) { + List arr=new ArrayList<>(); + List> list=new ArrayList<>(); + Arrays.sort(nums); + func(list,arr,0,nums); + return list; + } + public void func(List> arr,List list,int i,int[] nums){ + arr.add(new ArrayList<>(list)); + for(int j=i;ji && nums[j]==nums[j-1]) continue; + list.add(nums[j]); + func(arr,list,j+1,nums); + list.remove(list.size()-1); + } + } +} \ No newline at end of file diff --git a/94-binary-tree-inorder-traversal/README.md b/94-binary-tree-inorder-traversal/README.md new file mode 100644 index 00000000..97e71ffb --- /dev/null +++ b/94-binary-tree-inorder-traversal/README.md @@ -0,0 +1,34 @@ +

Binary Tree Inorder Traversal

Difficulty: Easy

Given the root of a binary tree, return the inorder traversal of its nodes' values.

+ +

 

+

Example 1:

+ +
+Input: root = [1,null,2,3]
+Output: [1,3,2]
+
+ +

Example 2:

+ +
+Input: root = []
+Output: []
+
+ +

Example 3:

+ +
+Input: root = [1]
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+Follow up: Recursive solution is trivial, could you do it iteratively? \ No newline at end of file diff --git a/94-binary-tree-inorder-traversal/binary-tree-inorder-traversal.java b/94-binary-tree-inorder-traversal/binary-tree-inorder-traversal.java new file mode 100644 index 00000000..1b950d70 --- /dev/null +++ b/94-binary-tree-inorder-traversal/binary-tree-inorder-traversal.java @@ -0,0 +1,32 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List inorderTraversal(TreeNode root) { + List ans=new ArrayList<>(); + if(root==null) return ans; + Stack stack=new Stack<>(); + while(!stack.isEmpty() || root!=null){ + while(root!=null){ + stack.push(root); + root=root.left; + } + TreeNode temp=stack.pop(); + ans.add(temp.val); + root=temp.right; + } + return ans; + } +} \ No newline at end of file diff --git a/941-sort-array-by-parity/README.md b/941-sort-array-by-parity/README.md new file mode 100644 index 00000000..456f9e5e --- /dev/null +++ b/941-sort-array-by-parity/README.md @@ -0,0 +1,27 @@ +

Sort Array By Parity

Difficulty: Easy

Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.

+ +

Return any array that satisfies this condition.

+ +

 

+

Example 1:

+ +
+Input: nums = [3,1,2,4]
+Output: [2,4,3,1]
+Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
+
+ +

Example 2:

+ +
+Input: nums = [0]
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5000
  • +
  • 0 <= nums[i] <= 5000
  • +
diff --git a/941-sort-array-by-parity/sort-array-by-parity.java b/941-sort-array-by-parity/sort-array-by-parity.java new file mode 100644 index 00000000..a4a332a6 --- /dev/null +++ b/941-sort-array-by-parity/sort-array-by-parity.java @@ -0,0 +1,14 @@ +class Solution { + public int[] sortArrayByParity(int[] nums) { + int i=0; + int j=nums.length-1; + while(iMinimum Add to Make Parentheses Valid Difficulty: Medium

A parentheses string is valid if and only if:

+ +
    +
  • It is the empty string,
  • +
  • It can be written as AB (A concatenated with B), where A and B are valid strings, or
  • +
  • It can be written as (A), where A is a valid string.
  • +
+ +

You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string.

+ +
    +
  • For example, if s = "()))", you can insert an opening parenthesis to be "(()))" or a closing parenthesis to be "())))".
  • +
+ +

Return the minimum number of moves required to make s valid.

+ +

 

+

Example 1:

+ +
+Input: s = "())"
+Output: 1
+
+ +

Example 2:

+ +
+Input: s = "((("
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • s[i] is either '(' or ')'.
  • +
diff --git a/957-minimum-add-to-make-parentheses-valid/minimum-add-to-make-parentheses-valid.java b/957-minimum-add-to-make-parentheses-valid/minimum-add-to-make-parentheses-valid.java new file mode 100644 index 00000000..b441272a --- /dev/null +++ b/957-minimum-add-to-make-parentheses-valid/minimum-add-to-make-parentheses-valid.java @@ -0,0 +1,13 @@ +class Solution { + public int minAddToMakeValid(String s) { + Stack stack=new Stack<>(); + for(char c:s.toCharArray()){ + if(!stack.isEmpty()){ + if(stack.peek()=='(' && c==')') stack.pop(); + else stack.push(c); + } + else stack.push(c); + } + return stack.size(); + } +} \ No newline at end of file diff --git a/98-validate-binary-search-tree/README.md b/98-validate-binary-search-tree/README.md new file mode 100644 index 00000000..93936243 --- /dev/null +++ b/98-validate-binary-search-tree/README.md @@ -0,0 +1,33 @@ +

Validate Binary Search Tree

Difficulty: Medium

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

+ +

A valid BST is defined as follows:

+ +
    +
  • The left subtree of a node contains only nodes with keys less than the node's key.
  • +
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • +
  • Both the left and right subtrees must also be binary search trees.
  • +
+ +

 

+

Example 1:

+ +
+Input: root = [2,1,3]
+Output: true
+
+ +

Example 2:

+ +
+Input: root = [5,1,4,null,null,3,6]
+Output: false
+Explanation: The root node's value is 5 but its right child's value is 4.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -231 <= Node.val <= 231 - 1
  • +
diff --git a/98-validate-binary-search-tree/validate-binary-search-tree.java b/98-validate-binary-search-tree/validate-binary-search-tree.java new file mode 100644 index 00000000..384d23c6 --- /dev/null +++ b/98-validate-binary-search-tree/validate-binary-search-tree.java @@ -0,0 +1,11 @@ +class Solution { + public boolean isValidBST(TreeNode root) { + return func(root, Long.MIN_VALUE, Long.MAX_VALUE); + } + + public boolean func(TreeNode root, long min, long max) { + if (root == null) return true; + if (root.val <= min || root.val >= max) return false; + return func(root.left, min, root.val) && func(root.right, root.val, max); + } +} From c6301df9dffeeed07f6ccb4d4c3d2dfe9925fafe Mon Sep 17 00:00:00 2001 From: shivaagaur00 Date: Thu, 14 Nov 2024 20:38:45 +0530 Subject: [PATCH 4/5] todays question --- 1472DesignBrowserHistory.java | 34 ++++++++ ...umStringLengthAfterRemovingSubstrings.java | 14 ++++ .../README.md | 27 ------- .../remove-trailing-zeros-from-a-string.java | 9 --- 2825-minimize-string-length/README.md | 72 ----------------- .../minimize-string-length.java | 9 --- .../README.md | 37 --------- ...eatest-common-divisors-in-linked-list.java | 34 -------- .../README.md | 50 ------------ ...anges-to-make-binary-string-beautiful.java | 13 --- 3195-separate-black-and-white-balls/README.md | 44 ----------- .../separate-black-and-white-balls.java | 13 --- 3291-find-if-array-can-be-sorted/README.md | 45 ----------- .../find-if-array-can-be-sorted.java | 34 -------- .../README.md | 39 --------- ...e-length-of-the-longest-common-prefix.java | 25 ------ .../README.md | 43 ---------- 3394-minimum-array-end/README.md | 35 -------- 3394-minimum-array-end/minimum-array-end.java | 15 ---- 3451-string-compression-iii/README.md | 54 ------------- .../string-compression-iii.java | 23 ------ .../README.md | 56 ------------- ...des-from-linked-list-present-in-array.java | 27 ------- .../README.md | 34 -------- .../smallest-divisible-digit-product-i.java | 16 ---- 55-jump-game/README.md | 28 ------- 55-jump-game/jump-game.java | 17 ---- 554-brick-wall/README.md | 32 -------- 554-brick-wall/brick-wall.java | 17 ---- 56-merge-intervals/README.md | 27 ------- 56-merge-intervals/merge-intervals.java | 31 -------- 58-length-of-last-word/README.md | 37 --------- .../length-of-last-word.java | 11 --- .../README.md | 36 --------- .../fraction-addition-and-subtraction.java | 72 ----------------- 6-zigzag-conversion/README.md | 51 ------------ 6-zigzag-conversion/zigzag-conversion.java | 32 -------- .../README.md | 45 ----------- .../construct-string-from-binary-tree.java | 26 ------ 623-add-one-row-to-tree/README.md | 38 --------- .../add-one-row-to-tree.java | 42 ---------- .../README.md | 25 ------ .../average-of-levels-in-binary-tree.java | 36 --------- 654-maximum-binary-tree/README.md | 43 ---------- .../maximum-binary-tree.java | 35 -------- 658-find-k-closest-elements/README.md | 35 -------- .../find-k-closest-elements.java | 17 ---- 662-maximum-width-of-binary-tree/README.md | 40 ---------- .../maximum-width-of-binary-tree.java | 45 ----------- 669-trim-a-binary-search-tree/README.md | 29 ------- .../trim-a-binary-search-tree.java | 27 ------- 67-add-binary/README.md | 18 ----- 67-add-binary/add-binary.java | 21 ----- 682BaseballGame.java | 22 ++++++ 695-max-area-of-island/README.md | 31 -------- .../max-area-of-island.java | 41 ---------- 725-split-linked-list-in-parts/README.md | 36 --------- .../split-linked-list-in-parts.java | 79 ------------------- 729-my-calendar-i/README.md | 36 --------- 729-my-calendar-i/my-calendar-i.java | 23 ------ 733-flood-fill/README.md | 53 ------------- 733-flood-fill/flood-fill.java | 34 -------- 75-sort-colors/README.md | 32 -------- 75-sort-colors/sort-colors.java | 16 ---- 783-search-in-a-binary-search-tree/README.md | 28 ------- .../README.md | 38 --------- .../README.md | 53 ------------- ...emove-duplicates-from-sorted-array-ii.java | 16 ---- 801-is-graph-bipartite/README.md | 40 ---------- .../is-graph-bipartite.java | 33 -------- 802-k-th-smallest-prime-fraction/README.md | 38 --------- .../k-th-smallest-prime-fraction.java | 16 ---- 812-rotate-string/README.md | 23 ------ 812-rotate-string/rotate-string.java | 13 --- 875-longest-mountain-in-array/README.md | 46 ----------- .../longest-mountain-in-array.java | 17 ---- 88-merge-sorted-array/README.md | 48 ----------- 88-merge-sorted-array/merge-sorted-array.java | 17 ---- 882-peak-index-in-a-mountain-array/README.md | 39 --------- .../peak-index-in-a-mountain-array.java | 14 ---- 889-buddy-strings/README.md | 40 ---------- 889-buddy-strings/buddy-strings.java | 30 ------- 890-lemonade-change/README.md | 38 --------- 890-lemonade-change/lemonade-change.java | 26 ------ .../README.md | 30 ------- .../all-nodes-distance-k-in-binary-tree.java | 53 ------------- 9-palindrome-number/README.md | 36 --------- 9-palindrome-number/palindrome-number.java | 17 ---- 90-subsets-ii/README.md | 19 ----- 90-subsets-ii/subsets-ii.java | 18 ----- 94-binary-tree-inorder-traversal/README.md | 34 -------- .../binary-tree-inorder-traversal.java | 32 -------- 941-sort-array-by-parity/README.md | 27 ------- .../sort-array-by-parity.java | 14 ---- .../README.md | 38 --------- ...minimum-add-to-make-parentheses-valid.java | 13 --- 98-validate-binary-search-tree/README.md | 33 -------- .../validate-binary-search-tree.java | 11 --- reverseStack.java | 34 ++++++++ 99 files changed, 104 insertions(+), 3036 deletions(-) create mode 100644 1472DesignBrowserHistory.java create mode 100644 2696MinimumStringLengthAfterRemovingSubstrings.java delete mode 100644 2819-remove-trailing-zeros-from-a-string/README.md delete mode 100644 2819-remove-trailing-zeros-from-a-string/remove-trailing-zeros-from-a-string.java delete mode 100644 2825-minimize-string-length/README.md delete mode 100644 2825-minimize-string-length/minimize-string-length.java delete mode 100644 2903-insert-greatest-common-divisors-in-linked-list/README.md delete mode 100644 2903-insert-greatest-common-divisors-in-linked-list/insert-greatest-common-divisors-in-linked-list.java delete mode 100644 3174-minimum-number-of-changes-to-make-binary-string-beautiful/README.md delete mode 100644 3174-minimum-number-of-changes-to-make-binary-string-beautiful/minimum-number-of-changes-to-make-binary-string-beautiful.java delete mode 100644 3195-separate-black-and-white-balls/README.md delete mode 100644 3195-separate-black-and-white-balls/separate-black-and-white-balls.java delete mode 100644 3291-find-if-array-can-be-sorted/README.md delete mode 100644 3291-find-if-array-can-be-sorted/find-if-array-can-be-sorted.java delete mode 100644 3329-find-the-length-of-the-longest-common-prefix/README.md delete mode 100644 3329-find-the-length-of-the-longest-common-prefix/find-the-length-of-the-longest-common-prefix.java delete mode 100644 3331-minimum-operations-to-exceed-threshold-value-i/README.md delete mode 100644 3394-minimum-array-end/README.md delete mode 100644 3394-minimum-array-end/minimum-array-end.java delete mode 100644 3451-string-compression-iii/README.md delete mode 100644 3451-string-compression-iii/string-compression-iii.java delete mode 100644 3501-delete-nodes-from-linked-list-present-in-array/README.md delete mode 100644 3501-delete-nodes-from-linked-list-present-in-array/delete-nodes-from-linked-list-present-in-array.java delete mode 100644 3626-smallest-divisible-digit-product-i/README.md delete mode 100644 3626-smallest-divisible-digit-product-i/smallest-divisible-digit-product-i.java delete mode 100644 55-jump-game/README.md delete mode 100644 55-jump-game/jump-game.java delete mode 100644 554-brick-wall/README.md delete mode 100644 554-brick-wall/brick-wall.java delete mode 100644 56-merge-intervals/README.md delete mode 100644 56-merge-intervals/merge-intervals.java delete mode 100644 58-length-of-last-word/README.md delete mode 100644 58-length-of-last-word/length-of-last-word.java delete mode 100644 592-fraction-addition-and-subtraction/README.md delete mode 100644 592-fraction-addition-and-subtraction/fraction-addition-and-subtraction.java delete mode 100644 6-zigzag-conversion/README.md delete mode 100644 6-zigzag-conversion/zigzag-conversion.java delete mode 100644 606-construct-string-from-binary-tree/README.md delete mode 100644 606-construct-string-from-binary-tree/construct-string-from-binary-tree.java delete mode 100644 623-add-one-row-to-tree/README.md delete mode 100644 623-add-one-row-to-tree/add-one-row-to-tree.java delete mode 100644 637-average-of-levels-in-binary-tree/README.md delete mode 100644 637-average-of-levels-in-binary-tree/average-of-levels-in-binary-tree.java delete mode 100644 654-maximum-binary-tree/README.md delete mode 100644 654-maximum-binary-tree/maximum-binary-tree.java delete mode 100644 658-find-k-closest-elements/README.md delete mode 100644 658-find-k-closest-elements/find-k-closest-elements.java delete mode 100644 662-maximum-width-of-binary-tree/README.md delete mode 100644 662-maximum-width-of-binary-tree/maximum-width-of-binary-tree.java delete mode 100644 669-trim-a-binary-search-tree/README.md delete mode 100644 669-trim-a-binary-search-tree/trim-a-binary-search-tree.java delete mode 100644 67-add-binary/README.md delete mode 100644 67-add-binary/add-binary.java create mode 100644 682BaseballGame.java delete mode 100644 695-max-area-of-island/README.md delete mode 100644 695-max-area-of-island/max-area-of-island.java delete mode 100644 725-split-linked-list-in-parts/README.md delete mode 100644 725-split-linked-list-in-parts/split-linked-list-in-parts.java delete mode 100644 729-my-calendar-i/README.md delete mode 100644 729-my-calendar-i/my-calendar-i.java delete mode 100644 733-flood-fill/README.md delete mode 100644 733-flood-fill/flood-fill.java delete mode 100644 75-sort-colors/README.md delete mode 100644 75-sort-colors/sort-colors.java delete mode 100644 783-search-in-a-binary-search-tree/README.md delete mode 100644 784-insert-into-a-binary-search-tree/README.md delete mode 100644 80-remove-duplicates-from-sorted-array-ii/README.md delete mode 100644 80-remove-duplicates-from-sorted-array-ii/remove-duplicates-from-sorted-array-ii.java delete mode 100644 801-is-graph-bipartite/README.md delete mode 100644 801-is-graph-bipartite/is-graph-bipartite.java delete mode 100644 802-k-th-smallest-prime-fraction/README.md delete mode 100644 802-k-th-smallest-prime-fraction/k-th-smallest-prime-fraction.java delete mode 100644 812-rotate-string/README.md delete mode 100644 812-rotate-string/rotate-string.java delete mode 100644 875-longest-mountain-in-array/README.md delete mode 100644 875-longest-mountain-in-array/longest-mountain-in-array.java delete mode 100644 88-merge-sorted-array/README.md delete mode 100644 88-merge-sorted-array/merge-sorted-array.java delete mode 100644 882-peak-index-in-a-mountain-array/README.md delete mode 100644 882-peak-index-in-a-mountain-array/peak-index-in-a-mountain-array.java delete mode 100644 889-buddy-strings/README.md delete mode 100644 889-buddy-strings/buddy-strings.java delete mode 100644 890-lemonade-change/README.md delete mode 100644 890-lemonade-change/lemonade-change.java delete mode 100644 893-all-nodes-distance-k-in-binary-tree/README.md delete mode 100644 893-all-nodes-distance-k-in-binary-tree/all-nodes-distance-k-in-binary-tree.java delete mode 100644 9-palindrome-number/README.md delete mode 100644 9-palindrome-number/palindrome-number.java delete mode 100644 90-subsets-ii/README.md delete mode 100644 90-subsets-ii/subsets-ii.java delete mode 100644 94-binary-tree-inorder-traversal/README.md delete mode 100644 94-binary-tree-inorder-traversal/binary-tree-inorder-traversal.java delete mode 100644 941-sort-array-by-parity/README.md delete mode 100644 941-sort-array-by-parity/sort-array-by-parity.java delete mode 100644 957-minimum-add-to-make-parentheses-valid/README.md delete mode 100644 957-minimum-add-to-make-parentheses-valid/minimum-add-to-make-parentheses-valid.java delete mode 100644 98-validate-binary-search-tree/README.md delete mode 100644 98-validate-binary-search-tree/validate-binary-search-tree.java create mode 100644 reverseStack.java diff --git a/1472DesignBrowserHistory.java b/1472DesignBrowserHistory.java new file mode 100644 index 00000000..c9990697 --- /dev/null +++ b/1472DesignBrowserHistory.java @@ -0,0 +1,34 @@ +class BrowserHistory { + List arr=new ArrayList<>(); + int i=0; + public BrowserHistory(String homepage) { + arr.add(homepage); + i=0; + } + public void visit(String url) { + while(arr.size()>i+1){ + arr.remove(arr.size()-1); + } + arr.add(url); + i++; + } + public String back(int steps) { + i=Math.max(i-steps,0); + return arr.get(i); + } + public String forward(int steps) { + i=i+steps; + if(i>=arr.size()){ + i=arr.size()-1; + } + return arr.get(i); + } + } + + /** + * Your BrowserHistory object will be instantiated and called as such: + * BrowserHistory obj = new BrowserHistory(homepage); + * obj.visit(url); + * String param_2 = obj.back(steps); + * String param_3 = obj.forward(steps); + */ \ No newline at end of file diff --git a/2696MinimumStringLengthAfterRemovingSubstrings.java b/2696MinimumStringLengthAfterRemovingSubstrings.java new file mode 100644 index 00000000..456e63df --- /dev/null +++ b/2696MinimumStringLengthAfterRemovingSubstrings.java @@ -0,0 +1,14 @@ +class Solution { + public int minLength(String s) { + Stack st=new Stack<>(); + for(char c:s.toCharArray()){ + if(!st.isEmpty()){ + if(st.peek()=='A' && c=='B') st.pop(); + else if(st.peek()=='C' && c=='D') st.pop(); + else st.push(c); + } + else st.push(c); + } + return st.size(); + } +} \ No newline at end of file diff --git a/2819-remove-trailing-zeros-from-a-string/README.md b/2819-remove-trailing-zeros-from-a-string/README.md deleted file mode 100644 index 2d2f7c86..00000000 --- a/2819-remove-trailing-zeros-from-a-string/README.md +++ /dev/null @@ -1,27 +0,0 @@ -

Remove Trailing Zeros From a String

Difficulty: Easy

Given a positive integer num represented as a string, return the integer num without trailing zeros as a string.

- -

 

-

Example 1:

- -
-Input: num = "51230100"
-Output: "512301"
-Explanation: Integer "51230100" has 2 trailing zeros, we remove them and return integer "512301".
-
- -

Example 2:

- -
-Input: num = "123"
-Output: "123"
-Explanation: Integer "123" has no trailing zeros, we return integer "123".
-
- -

 

-

Constraints:

- -
    -
  • 1 <= num.length <= 1000
  • -
  • num consists of only digits.
  • -
  • num doesn't have any leading zeros.
  • -
diff --git a/2819-remove-trailing-zeros-from-a-string/remove-trailing-zeros-from-a-string.java b/2819-remove-trailing-zeros-from-a-string/remove-trailing-zeros-from-a-string.java deleted file mode 100644 index 1272b4fc..00000000 --- a/2819-remove-trailing-zeros-from-a-string/remove-trailing-zeros-from-a-string.java +++ /dev/null @@ -1,9 +0,0 @@ -class Solution { - public String removeTrailingZeros(String num) { - for(int i=num.length()-1;i>=0;i--){ - if(num.charAt(i)=='0') num=num.substring(0,num.length()-1); - else break; - } - return num; - } -} \ No newline at end of file diff --git a/2825-minimize-string-length/README.md b/2825-minimize-string-length/README.md deleted file mode 100644 index 241392c6..00000000 --- a/2825-minimize-string-length/README.md +++ /dev/null @@ -1,72 +0,0 @@ -

Minimize String Length

Difficulty: Easy

Given a string s, you have two types of operation:

- -
    -
  1. Choose an index i in the string, and let c be the character in position i. Delete the closest occurrence of c to the left of i (if exists).
  2. -
  3. Choose an index i in the string, and let c be the character in position i. Delete the closest occurrence of c to the right of i (if exists).
  4. -
- -

Your task is to minimize the length of s by performing the above operations zero or more times.

- -

Return an integer denoting the length of the minimized string.

- -

 

-

Example 1:

- -
-

Input: s = "aaabc"

- -

Output: 3

- -

Explanation:

- -
    -
  1. Operation 2: we choose i = 1 so c is 'a', then we remove s[2] as it is closest 'a' character to the right of s[1].
    - s becomes "aabc" after this.
  2. -
  3. Operation 1: we choose i = 1 so c is 'a', then we remove s[0] as it is closest 'a' character to the left of s[1].
    - s becomes "abc" after this.
  4. -
-
- -

Example 2:

- -
-

Input: s = "cbbd"

- -

Output: 3

- -

Explanation:

- -
    -
  1. Operation 1: we choose i = 2 so c is 'b', then we remove s[1] as it is closest 'b' character to the left of s[1].
    - s becomes "cbd" after this.
  2. -
-
- -

Example 3:

- -
-

Input: s = "baadccab"

- -

Output: 4

- -

Explanation:

- -
    -
  1. Operation 1: we choose i = 6 so c is 'a', then we remove s[2] as it is closest 'a' character to the left of s[6].
    - s becomes "badccab" after this.
  2. -
  3. Operation 2: we choose i = 0 so c is 'b', then we remove s[6] as it is closest 'b' character to the right of s[0].
    - s becomes "badcca" fter this.
  4. -
  5. Operation 2: we choose i = 3 so c is 'c', then we remove s[4] as it is closest 'c' character to the right of s[3].
    - s becomes "badca" after this.
  6. -
  7. Operation 1: we choose i = 4 so c is 'a', then we remove s[1] as it is closest 'a' character to the left of s[4].
    - s becomes "bdca" after this.
  8. -
-
- -

 

-

Constraints:

- -
    -
  • 1 <= s.length <= 100
  • -
  • s contains only lowercase English letters
  • -
diff --git a/2825-minimize-string-length/minimize-string-length.java b/2825-minimize-string-length/minimize-string-length.java deleted file mode 100644 index d91c9b8e..00000000 --- a/2825-minimize-string-length/minimize-string-length.java +++ /dev/null @@ -1,9 +0,0 @@ -class Solution { - public int minimizedStringLength(String s) { - Map map=new HashMap<>(); - for(char a:s.toCharArray()){ - map.put(a,map.getOrDefault(a,0)+1); - } - return map.size(); - } -} \ No newline at end of file diff --git a/2903-insert-greatest-common-divisors-in-linked-list/README.md b/2903-insert-greatest-common-divisors-in-linked-list/README.md deleted file mode 100644 index 7306b5f9..00000000 --- a/2903-insert-greatest-common-divisors-in-linked-list/README.md +++ /dev/null @@ -1,37 +0,0 @@ -

Insert Greatest Common Divisors in Linked List

Difficulty: Medium

Given the head of a linked list head, in which each node contains an integer value.

- -

Between every pair of adjacent nodes, insert a new node with a value equal to the greatest common divisor of them.

- -

Return the linked list after insertion.

- -

The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.

- -

 

-

Example 1:

- -
-Input: head = [18,6,10,3]
-Output: [18,6,6,2,10,1,3]
-Explanation: The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes (nodes in blue are the inserted nodes).
-- We insert the greatest common divisor of 18 and 6 = 6 between the 1st and the 2nd nodes.
-- We insert the greatest common divisor of 6 and 10 = 2 between the 2nd and the 3rd nodes.
-- We insert the greatest common divisor of 10 and 3 = 1 between the 3rd and the 4th nodes.
-There are no more adjacent nodes, so we return the linked list.
-
- -

Example 2:

- -
-Input: head = [7]
-Output: [7]
-Explanation: The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes.
-There are no pairs of adjacent nodes, so we return the initial linked list.
-
- -

 

-

Constraints:

- -
    -
  • The number of nodes in the list is in the range [1, 5000].
  • -
  • 1 <= Node.val <= 1000
  • -
diff --git a/2903-insert-greatest-common-divisors-in-linked-list/insert-greatest-common-divisors-in-linked-list.java b/2903-insert-greatest-common-divisors-in-linked-list/insert-greatest-common-divisors-in-linked-list.java deleted file mode 100644 index 7535b21e..00000000 --- a/2903-insert-greatest-common-divisors-in-linked-list/insert-greatest-common-divisors-in-linked-list.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode insertGreatestCommonDivisors(ListNode head) { - if(head==null) return head; - ListNode ans=new ListNode(head.val); - ListNode dummy=ans; - head=head.next; - while(head!=null){ - int gcd=gcd(ans.val,head.val); - ans.next=new ListNode(gcd); - ans=ans.next; - ans.next=new ListNode(head.val); - ans=ans.next; - head=head.next; - } - return dummy; - } - public int gcd(int a,int b){ - int min=Math.min(a,b); - for(int i=min;i>1;i--){ - if(a%i==0 && b%i==0) return i; - } - return 1; - } -} \ No newline at end of file diff --git a/3174-minimum-number-of-changes-to-make-binary-string-beautiful/README.md b/3174-minimum-number-of-changes-to-make-binary-string-beautiful/README.md deleted file mode 100644 index 2cf6d0ac..00000000 --- a/3174-minimum-number-of-changes-to-make-binary-string-beautiful/README.md +++ /dev/null @@ -1,50 +0,0 @@ -

Minimum Number of Changes to Make Binary String Beautiful

Difficulty: Medium

You are given a 0-indexed binary string s having an even length.

- -

A string is beautiful if it's possible to partition it into one or more substrings such that:

- -
    -
  • Each substring has an even length.
  • -
  • Each substring contains only 1's or only 0's.
  • -
- -

You can change any character in s to 0 or 1.

- -

Return the minimum number of changes required to make the string s beautiful.

- -

 

-

Example 1:

- -
-Input: s = "1001"
-Output: 2
-Explanation: We change s[1] to 1 and s[3] to 0 to get string "1100".
-It can be seen that the string "1100" is beautiful because we can partition it into "11|00".
-It can be proven that 2 is the minimum number of changes needed to make the string beautiful.
-
- -

Example 2:

- -
-Input: s = "10"
-Output: 1
-Explanation: We change s[1] to 1 to get string "11".
-It can be seen that the string "11" is beautiful because we can partition it into "11".
-It can be proven that 1 is the minimum number of changes needed to make the string beautiful.
-
- -

Example 3:

- -
-Input: s = "0000"
-Output: 0
-Explanation: We don't need to make any changes as the string "0000" is beautiful already.
-
- -

 

-

Constraints:

- -
    -
  • 2 <= s.length <= 105
  • -
  • s has an even length.
  • -
  • s[i] is either '0' or '1'.
  • -
diff --git a/3174-minimum-number-of-changes-to-make-binary-string-beautiful/minimum-number-of-changes-to-make-binary-string-beautiful.java b/3174-minimum-number-of-changes-to-make-binary-string-beautiful/minimum-number-of-changes-to-make-binary-string-beautiful.java deleted file mode 100644 index c81fb6ae..00000000 --- a/3174-minimum-number-of-changes-to-make-binary-string-beautiful/minimum-number-of-changes-to-make-binary-string-beautiful.java +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { - public int minChanges(String s) { - int i=0; - int ans=0; - while(iSeparate Black and White Balls Difficulty: Medium

There are n balls on a table, each ball has a color black or white.

- -

You are given a 0-indexed binary string s of length n, where 1 and 0 represent black and white balls, respectively.

- -

In each step, you can choose two adjacent balls and swap them.

- -

Return the minimum number of steps to group all the black balls to the right and all the white balls to the left.

- -

 

-

Example 1:

- -
-Input: s = "101"
-Output: 1
-Explanation: We can group all the black balls to the right in the following way:
-- Swap s[0] and s[1], s = "011".
-Initially, 1s are not grouped together, requiring at least 1 step to group them to the right.
- -

Example 2:

- -
-Input: s = "100"
-Output: 2
-Explanation: We can group all the black balls to the right in the following way:
-- Swap s[0] and s[1], s = "010".
-- Swap s[1] and s[2], s = "001".
-It can be proven that the minimum number of steps needed is 2.
-
- -

Example 3:

- -
-Input: s = "0111"
-Output: 0
-Explanation: All the black balls are already grouped to the right.
-
- -

 

-

Constraints:

- -
    -
  • 1 <= n == s.length <= 105
  • -
  • s[i] is either '0' or '1'.
  • -
diff --git a/3195-separate-black-and-white-balls/separate-black-and-white-balls.java b/3195-separate-black-and-white-balls/separate-black-and-white-balls.java deleted file mode 100644 index 0073910e..00000000 --- a/3195-separate-black-and-white-balls/separate-black-and-white-balls.java +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { - public long minimumSteps(String s) { - long ans=0; - long temp=0; - for(int i=0;iFind if Array Can Be Sorted Difficulty: Medium

You are given a 0-indexed array of positive integers nums.

- -

In one operation, you can swap any two adjacent elements if they have the same number of set bits. You are allowed to do this operation any number of times (including zero).

- -

Return true if you can sort the array, else return false.

- -

 

-

Example 1:

- -
-Input: nums = [8,4,2,30,15]
-Output: true
-Explanation: Let's look at the binary representation of every element. The numbers 2, 4, and 8 have one set bit each with binary representation "10", "100", and "1000" respectively. The numbers 15 and 30 have four set bits each with binary representation "1111" and "11110".
-We can sort the array using 4 operations:
-- Swap nums[0] with nums[1]. This operation is valid because 8 and 4 have one set bit each. The array becomes [4,8,2,30,15].
-- Swap nums[1] with nums[2]. This operation is valid because 8 and 2 have one set bit each. The array becomes [4,2,8,30,15].
-- Swap nums[0] with nums[1]. This operation is valid because 4 and 2 have one set bit each. The array becomes [2,4,8,30,15].
-- Swap nums[3] with nums[4]. This operation is valid because 30 and 15 have four set bits each. The array becomes [2,4,8,15,30].
-The array has become sorted, hence we return true.
-Note that there may be other sequences of operations which also sort the array.
-
- -

Example 2:

- -
-Input: nums = [1,2,3,4,5]
-Output: true
-Explanation: The array is already sorted, hence we return true.
-
- -

Example 3:

- -
-Input: nums = [3,16,8,4,2]
-Output: false
-Explanation: It can be shown that it is not possible to sort the input array using any number of operations.
-
- -

 

-

Constraints:

- -
    -
  • 1 <= nums.length <= 100
  • -
  • 1 <= nums[i] <= 28
  • -
diff --git a/3291-find-if-array-can-be-sorted/find-if-array-can-be-sorted.java b/3291-find-if-array-can-be-sorted/find-if-array-can-be-sorted.java deleted file mode 100644 index a571a71d..00000000 --- a/3291-find-if-array-can-be-sorted/find-if-array-can-be-sorted.java +++ /dev/null @@ -1,34 +0,0 @@ -class Solution { - public boolean canSortArray(int[] nums) { - List ls=new ArrayList<>(); - int bit[]=new int[nums.length]; - for(int i=0;ils.get(i).min || min>ls.get(i).max) return false; - min=Math.max(ls.get(i).max,min); - } - return true; - } -} -class pair{ - int max; - int min; - pair(int min,int max){ - this.min=min; - this.max=max; - } -} \ No newline at end of file diff --git a/3329-find-the-length-of-the-longest-common-prefix/README.md b/3329-find-the-length-of-the-longest-common-prefix/README.md deleted file mode 100644 index 90e0bcfc..00000000 --- a/3329-find-the-length-of-the-longest-common-prefix/README.md +++ /dev/null @@ -1,39 +0,0 @@ -

Find the Length of the Longest Common Prefix

Difficulty: Medium

You are given two arrays with positive integers arr1 and arr2.

- -

A prefix of a positive integer is an integer formed by one or more of its digits, starting from its leftmost digit. For example, 123 is a prefix of the integer 12345, while 234 is not.

- -

A common prefix of two integers a and b is an integer c, such that c is a prefix of both a and b. For example, 5655359 and 56554 have a common prefix 565 while 1223 and 43456 do not have a common prefix.

- -

You need to find the length of the longest common prefix between all pairs of integers (x, y) such that x belongs to arr1 and y belongs to arr2.

- -

Return the length of the longest common prefix among all pairs. If no common prefix exists among them, return 0.

- -

 

-

Example 1:

- -
-Input: arr1 = [1,10,100], arr2 = [1000]
-Output: 3
-Explanation: There are 3 pairs (arr1[i], arr2[j]):
-- The longest common prefix of (1, 1000) is 1.
-- The longest common prefix of (10, 1000) is 10.
-- The longest common prefix of (100, 1000) is 100.
-The longest common prefix is 100 with a length of 3.
-
- -

Example 2:

- -
-Input: arr1 = [1,2,3], arr2 = [4,4,4]
-Output: 0
-Explanation: There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0.
-Note that common prefixes between elements of the same array do not count.
-
- -

 

-

Constraints:

- -
    -
  • 1 <= arr1.length, arr2.length <= 5 * 104
  • -
  • 1 <= arr1[i], arr2[i] <= 108
  • -
diff --git a/3329-find-the-length-of-the-longest-common-prefix/find-the-length-of-the-longest-common-prefix.java b/3329-find-the-length-of-the-longest-common-prefix/find-the-length-of-the-longest-common-prefix.java deleted file mode 100644 index 5e021893..00000000 --- a/3329-find-the-length-of-the-longest-common-prefix/find-the-length-of-the-longest-common-prefix.java +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { - public int longestCommonPrefix(int[] arr, int[] nums) { - Map map=new HashMap<>(); - int ans=0; - for(int i=0;i set=new HashSet<>(); - for(int a:nums){ - String prefix=""; - String s=""+a; - boolean flag=true; - for(char ch:s.toCharArray()){ - prefix+=ch; - if(map.containsKey(prefix)) ans=Math.max(ans,prefix.length()); - } - } - return ans; - } -} \ No newline at end of file diff --git a/3331-minimum-operations-to-exceed-threshold-value-i/README.md b/3331-minimum-operations-to-exceed-threshold-value-i/README.md deleted file mode 100644 index 6bf474d1..00000000 --- a/3331-minimum-operations-to-exceed-threshold-value-i/README.md +++ /dev/null @@ -1,43 +0,0 @@ -

Minimum Operations to Exceed Threshold Value I

Difficulty: Easy

You are given a 0-indexed integer array nums, and an integer k.

- -

In one operation, you can remove one occurrence of the smallest element of nums.

- -

Return the minimum number of operations needed so that all elements of the array are greater than or equal to k.

- -

 

-

Example 1:

- -
-Input: nums = [2,11,10,1,3], k = 10
-Output: 3
-Explanation: After one operation, nums becomes equal to [2, 11, 10, 3].
-After two operations, nums becomes equal to [11, 10, 3].
-After three operations, nums becomes equal to [11, 10].
-At this stage, all the elements of nums are greater than or equal to 10 so we can stop.
-It can be shown that 3 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.
-
- -

Example 2:

- -
-Input: nums = [1,1,2,4,9], k = 1
-Output: 0
-Explanation: All elements of the array are greater than or equal to 1 so we do not need to apply any operations on nums.
- -

Example 3:

- -
-Input: nums = [1,1,2,4,9], k = 9
-Output: 4
-Explanation: only a single element of nums is greater than or equal to 9 so we need to apply the operations 4 times on nums.
-
- -

 

-

Constraints:

- -
    -
  • 1 <= nums.length <= 50
  • -
  • 1 <= nums[i] <= 109
  • -
  • 1 <= k <= 109
  • -
  • The input is generated such that there is at least one index i such that nums[i] >= k.
  • -
diff --git a/3394-minimum-array-end/README.md b/3394-minimum-array-end/README.md deleted file mode 100644 index 901f3d55..00000000 --- a/3394-minimum-array-end/README.md +++ /dev/null @@ -1,35 +0,0 @@ -

Minimum Array End

Difficulty: Medium

You are given two integers n and x. You have to construct an array of positive integers nums of size n where for every 0 <= i < n - 1, nums[i + 1] is greater than nums[i], and the result of the bitwise AND operation between all elements of nums is x.

- -

Return the minimum possible value of nums[n - 1].

- -

 

-

Example 1:

- -
-

Input: n = 3, x = 4

- -

Output: 6

- -

Explanation:

- -

nums can be [4,5,6] and its last element is 6.

-
- -

Example 2:

- -
-

Input: n = 2, x = 7

- -

Output: 15

- -

Explanation:

- -

nums can be [7,15] and its last element is 15.

-
- -

 

-

Constraints:

- -
    -
  • 1 <= n, x <= 108
  • -
diff --git a/3394-minimum-array-end/minimum-array-end.java b/3394-minimum-array-end/minimum-array-end.java deleted file mode 100644 index 1a20e5f0..00000000 --- a/3394-minimum-array-end/minimum-array-end.java +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { - public long minEnd(int n, int x) { - long res=x; - long rem=n-1; - long pos=1; - while (rem!=0){ - if ((x&pos)==0) { - res|=(rem&1)*pos; - rem>>=1; - } - pos<<=1; - } - return res; - } -} diff --git a/3451-string-compression-iii/README.md b/3451-string-compression-iii/README.md deleted file mode 100644 index 36c55a54..00000000 --- a/3451-string-compression-iii/README.md +++ /dev/null @@ -1,54 +0,0 @@ -

String Compression III

Difficulty: Medium

Given a string word, compress it using the following algorithm:

- -
    -
  • Begin with an empty string comp. While word is not empty, use the following operation: - -
      -
    • Remove a maximum length prefix of word made of a single character c repeating at most 9 times.
    • -
    • Append the length of the prefix followed by c to comp.
    • -
    -
  • -
- -

Return the string comp.

- -

 

-

Example 1:

- -
-

Input: word = "abcde"

- -

Output: "1a1b1c1d1e"

- -

Explanation:

- -

Initially, comp = "". Apply the operation 5 times, choosing "a", "b", "c", "d", and "e" as the prefix in each operation.

- -

For each prefix, append "1" followed by the character to comp.

-
- -

Example 2:

- -
-

Input: word = "aaaaaaaaaaaaaabb"

- -

Output: "9a5a2b"

- -

Explanation:

- -

Initially, comp = "". Apply the operation 3 times, choosing "aaaaaaaaa", "aaaaa", and "bb" as the prefix in each operation.

- -
    -
  • For prefix "aaaaaaaaa", append "9" followed by "a" to comp.
  • -
  • For prefix "aaaaa", append "5" followed by "a" to comp.
  • -
  • For prefix "bb", append "2" followed by "b" to comp.
  • -
-
- -

 

-

Constraints:

- -
    -
  • 1 <= word.length <= 2 * 105
  • -
  • word consists only of lowercase English letters.
  • -
diff --git a/3451-string-compression-iii/string-compression-iii.java b/3451-string-compression-iii/string-compression-iii.java deleted file mode 100644 index a12765b2..00000000 --- a/3451-string-compression-iii/string-compression-iii.java +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { - public String compressedString(String word) { - String ans=""; - int n=0; - char c=word.charAt(0); - for(int i=0;i0) ans+=""+n+c; - c=word.charAt(i); - n=1; - } - else{ - n++; - if(n==9){ - ans+="9"+c; - n=0; - } - } - } - if(n>0) ans+=""+n+c; - return ans; - } -} \ No newline at end of file diff --git a/3501-delete-nodes-from-linked-list-present-in-array/README.md b/3501-delete-nodes-from-linked-list-present-in-array/README.md deleted file mode 100644 index 74c1af53..00000000 --- a/3501-delete-nodes-from-linked-list-present-in-array/README.md +++ /dev/null @@ -1,56 +0,0 @@ -

Delete Nodes From Linked List Present in Array

Difficulty: Medium

You are given an array of integers nums and the head of a linked list. Return the head of the modified linked list after removing all nodes from the linked list that have a value that exists in nums.

- -

 

-

Example 1:

- -
-

Input: nums = [1,2,3], head = [1,2,3,4,5]

- -

Output: [4,5]

- -

Explanation:

- -

- -

Remove the nodes with values 1, 2, and 3.

-
- -

Example 2:

- -
-

Input: nums = [1], head = [1,2,1,2,1,2]

- -

Output: [2,2,2]

- -

Explanation:

- -

- -

Remove the nodes with value 1.

-
- -

Example 3:

- -
-

Input: nums = [5], head = [1,2,3,4]

- -

Output: [1,2,3,4]

- -

Explanation:

- -

- -

No node has value 5.

-
- -

 

-

Constraints:

- -
    -
  • 1 <= nums.length <= 105
  • -
  • 1 <= nums[i] <= 105
  • -
  • All elements in nums are unique.
  • -
  • The number of nodes in the given list is in the range [1, 105].
  • -
  • 1 <= Node.val <= 105
  • -
  • The input is generated such that there is at least one node in the linked list that has a value not present in nums.
  • -
diff --git a/3501-delete-nodes-from-linked-list-present-in-array/delete-nodes-from-linked-list-present-in-array.java b/3501-delete-nodes-from-linked-list-present-in-array/delete-nodes-from-linked-list-present-in-array.java deleted file mode 100644 index 32529f4d..00000000 --- a/3501-delete-nodes-from-linked-list-present-in-array/delete-nodes-from-linked-list-present-in-array.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode modifiedList(int[] nums, ListNode head) { - if(head==null) return head; - Set arr= new HashSet<>(); - for(int a:nums) arr.add(a); - ListNode dummy=new ListNode(0); - ListNode ans=dummy; - while(head!=null){ - if(!arr.contains(head.val)){ - dummy.next=new ListNode(head.val); - dummy=dummy.next; - } - head=head.next; - } - return ans.next; - } -} \ No newline at end of file diff --git a/3626-smallest-divisible-digit-product-i/README.md b/3626-smallest-divisible-digit-product-i/README.md deleted file mode 100644 index 3da039f9..00000000 --- a/3626-smallest-divisible-digit-product-i/README.md +++ /dev/null @@ -1,34 +0,0 @@ -

Smallest Divisible Digit Product I

Difficulty: Easy

You are given two integers n and t. Return the smallest number greater than or equal to n such that the product of its digits is divisible by t.

- -

 

-

Example 1:

- -
-

Input: n = 10, t = 2

- -

Output: 10

- -

Explanation:

- -

The digit product of 10 is 0, which is divisible by 2, making it the smallest number greater than or equal to 10 that satisfies the condition.

-
- -

Example 2:

- -
-

Input: n = 15, t = 3

- -

Output: 16

- -

Explanation:

- -

The digit product of 16 is 6, which is divisible by 3, making it the smallest number greater than or equal to 15 that satisfies the condition.

-
- -

 

-

Constraints:

- -
    -
  • 1 <= n <= 100
  • -
  • 1 <= t <= 10
  • -
diff --git a/3626-smallest-divisible-digit-product-i/smallest-divisible-digit-product-i.java b/3626-smallest-divisible-digit-product-i/smallest-divisible-digit-product-i.java deleted file mode 100644 index 9c65666d..00000000 --- a/3626-smallest-divisible-digit-product-i/smallest-divisible-digit-product-i.java +++ /dev/null @@ -1,16 +0,0 @@ -public class Solution { - public int smallestNumber(int n, int t) { - while (true) { - if (func(n) % t == 0) return n; - n++; - } - } - public int func(int num) { - int ans = 1; - while (num >0) { - ans*= num%10; - num/=10; - } - return ans; - } -} diff --git a/55-jump-game/README.md b/55-jump-game/README.md deleted file mode 100644 index 2b0f2f5f..00000000 --- a/55-jump-game/README.md +++ /dev/null @@ -1,28 +0,0 @@ -

Jump Game

Difficulty: Medium

You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

- -

Return true if you can reach the last index, or false otherwise.

- -

 

-

Example 1:

- -
-Input: nums = [2,3,1,1,4]
-Output: true
-Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
-
- -

Example 2:

- -
-Input: nums = [3,2,1,0,4]
-Output: false
-Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
-
- -

 

-

Constraints:

- -
    -
  • 1 <= nums.length <= 104
  • -
  • 0 <= nums[i] <= 105
  • -
diff --git a/55-jump-game/jump-game.java b/55-jump-game/jump-game.java deleted file mode 100644 index e88d7ab7..00000000 --- a/55-jump-game/jump-game.java +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { - public boolean canJump(int[] nums) { - boolean flag=true; - for(int a:nums){ - if(a==0){ - flag=false; - } - } - if(flag) return true; - int max=0; - for(int i=0;imax) return false; - max=Math.max(max,nums[i]+i); - } - return true; - } -} \ No newline at end of file diff --git a/554-brick-wall/README.md b/554-brick-wall/README.md deleted file mode 100644 index e5888528..00000000 --- a/554-brick-wall/README.md +++ /dev/null @@ -1,32 +0,0 @@ -

Brick Wall

Difficulty: Medium

There is a rectangular brick wall in front of you with n rows of bricks. The ith row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.

- -

Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.

- -

Given the 2D array wall that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line.

- -

 

-

Example 1:

- -
-Input: wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]
-Output: 2
-
- -

Example 2:

- -
-Input: wall = [[1],[1],[1]]
-Output: 3
-
- -

 

-

Constraints:

- -
    -
  • n == wall.length
  • -
  • 1 <= n <= 104
  • -
  • 1 <= wall[i].length <= 104
  • -
  • 1 <= sum(wall[i].length) <= 2 * 104
  • -
  • sum(wall[i]) is the same for each row i.
  • -
  • 1 <= wall[i][j] <= 231 - 1
  • -
diff --git a/554-brick-wall/brick-wall.java b/554-brick-wall/brick-wall.java deleted file mode 100644 index b41a37ea..00000000 --- a/554-brick-wall/brick-wall.java +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { - public int leastBricks(List> wall) { - Map map=new HashMap<>(); - int ans=wall.size(); - for(int i=0;iMerge Intervals Difficulty: Medium

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

- -

 

-

Example 1:

- -
-Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
-Output: [[1,6],[8,10],[15,18]]
-Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
-
- -

Example 2:

- -
-Input: intervals = [[1,4],[4,5]]
-Output: [[1,5]]
-Explanation: Intervals [1,4] and [4,5] are considered overlapping.
-
- -

 

-

Constraints:

- -
    -
  • 1 <= intervals.length <= 104
  • -
  • intervals[i].length == 2
  • -
  • 0 <= starti <= endi <= 104
  • -
diff --git a/56-merge-intervals/merge-intervals.java b/56-merge-intervals/merge-intervals.java deleted file mode 100644 index 784e7fa5..00000000 --- a/56-merge-intervals/merge-intervals.java +++ /dev/null @@ -1,31 +0,0 @@ -class Solution { - public int[][] merge(int[][] intervals) { - List arr = new ArrayList<>(); - Arrays.sort(intervals, (a, b) ->{ - if(a[0]==b[0]) return a[1]-b[1]; - else return a[0]-b[0]; - }); - int end = intervals[0][1]; - int start = intervals[0][0]; - for (int i = 1; i < intervals.length; i++) { - if (intervals[i][0] <= end) { - end = Math.max(end,intervals[i][1]); - start=Math.min(start,intervals[i][0]); - } else { - int[] a = { start, end }; - arr.add(a); - start = intervals[i][0]; - end = intervals[i][1]; - } - } - int[] a = { start, end }; - arr.add(a); - int[][] ans = new int[arr.size()][2]; - int j = 0; - for (int[] ab : arr) { - ans[j][0] = ab[0]; - ans[j++][1] = ab[1]; - } - return ans; - } -} \ No newline at end of file diff --git a/58-length-of-last-word/README.md b/58-length-of-last-word/README.md deleted file mode 100644 index 2c38b6d1..00000000 --- a/58-length-of-last-word/README.md +++ /dev/null @@ -1,37 +0,0 @@ -

Length of Last Word

Difficulty: Easy

Given a string s consisting of words and spaces, return the length of the last word in the string.

- -

A word is a maximal substring consisting of non-space characters only.

- -

 

-

Example 1:

- -
-Input: s = "Hello World"
-Output: 5
-Explanation: The last word is "World" with length 5.
-
- -

Example 2:

- -
-Input: s = "   fly me   to   the moon  "
-Output: 4
-Explanation: The last word is "moon" with length 4.
-
- -

Example 3:

- -
-Input: s = "luffy is still joyboy"
-Output: 6
-Explanation: The last word is "joyboy" with length 6.
-
- -

 

-

Constraints:

- -
    -
  • 1 <= s.length <= 104
  • -
  • s consists of only English letters and spaces ' '.
  • -
  • There will be at least one word in s.
  • -
diff --git a/58-length-of-last-word/length-of-last-word.java b/58-length-of-last-word/length-of-last-word.java deleted file mode 100644 index 77e017d0..00000000 --- a/58-length-of-last-word/length-of-last-word.java +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { - public int lengthOfLastWord(String s) { - s=s.trim(); - int ans=0; - for(int i=s.length()-1;i>=0;i--){ - if(s.charAt(i)!=' ')ans++; - else break; - } - return ans; - } -} \ No newline at end of file diff --git a/592-fraction-addition-and-subtraction/README.md b/592-fraction-addition-and-subtraction/README.md deleted file mode 100644 index 21a19a26..00000000 --- a/592-fraction-addition-and-subtraction/README.md +++ /dev/null @@ -1,36 +0,0 @@ -

Fraction Addition and Subtraction

Difficulty: Medium

Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format.

- -

The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1.

- -

 

-

Example 1:

- -
-Input: expression = "-1/2+1/2"
-Output: "0/1"
-
- -

Example 2:

- -
-Input: expression = "-1/2+1/2+1/3"
-Output: "1/3"
-
- -

Example 3:

- -
-Input: expression = "1/3-1/2"
-Output: "-1/6"
-
- -

 

-

Constraints:

- -
    -
  • The input string only contains '0' to '9', '/', '+' and '-'. So does the output.
  • -
  • Each fraction (input and output) has the format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.
  • -
  • The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.
  • -
  • The number of given fractions will be in the range [1, 10].
  • -
  • The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
  • -
diff --git a/592-fraction-addition-and-subtraction/fraction-addition-and-subtraction.java b/592-fraction-addition-and-subtraction/fraction-addition-and-subtraction.java deleted file mode 100644 index 7ce58862..00000000 --- a/592-fraction-addition-and-subtraction/fraction-addition-and-subtraction.java +++ /dev/null @@ -1,72 +0,0 @@ -class Solution { - public String fractionAddition(String s) { - int deno=1; - boolean flag=false; - String st=""; - List d=new ArrayList<>(); - List n=new ArrayList<>(); - for(int i=1;i0) deno*=Integer.parseInt(st); - d.add(Integer.parseInt(st)); - st=""; - - } - else if(flag){ - st+=s.charAt(i); - } - } - if(st.length()>0){ - deno*=Integer.parseInt(st); - d.add(Integer.parseInt(st)); - } - st=""; - flag=true; - for(int i=0;i0){ - n.add(Integer.parseInt(st)); - } - int num=0; - for(int i=0;i 0) { - if (a % result == 0 && b % result == 0) { - break; - } - result--; - } - return result; -} -} \ No newline at end of file diff --git a/6-zigzag-conversion/README.md b/6-zigzag-conversion/README.md deleted file mode 100644 index eee8a14f..00000000 --- a/6-zigzag-conversion/README.md +++ /dev/null @@ -1,51 +0,0 @@ -

Zigzag Conversion

Difficulty: Medium

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

- -
-P   A   H   N
-A P L S I I G
-Y   I   R
-
- -

And then read line by line: "PAHNAPLSIIGYIR"

- -

Write the code that will take a string and make this conversion given a number of rows:

- -
-string convert(string s, int numRows);
-
- -

 

-

Example 1:

- -
-Input: s = "PAYPALISHIRING", numRows = 3
-Output: "PAHNAPLSIIGYIR"
-
- -

Example 2:

- -
-Input: s = "PAYPALISHIRING", numRows = 4
-Output: "PINALSIGYAHRPI"
-Explanation:
-P     I    N
-A   L S  I G
-Y A   H R
-P     I
-
- -

Example 3:

- -
-Input: s = "A", numRows = 1
-Output: "A"
-
- -

 

-

Constraints:

- -
    -
  • 1 <= s.length <= 1000
  • -
  • s consists of English letters (lower-case and upper-case), ',' and '.'.
  • -
  • 1 <= numRows <= 1000
  • -
diff --git a/6-zigzag-conversion/zigzag-conversion.java b/6-zigzag-conversion/zigzag-conversion.java deleted file mode 100644 index 1b46f750..00000000 --- a/6-zigzag-conversion/zigzag-conversion.java +++ /dev/null @@ -1,32 +0,0 @@ -class Solution { - public String convert(String s, int numRows) { - if(numRows==1)return s; - List> ans=new ArrayList<>(); - for(int i=0;i()); - boolean flag=true; - int idx=0; - while(s.length()!=0){ - ans.get(idx).add(s.charAt(0)); - s=s.substring(1); - if(flag){ - if(idx==numRows-1){ - idx--; - flag=false; - } - else idx++; - } - else{ - if(idx==0){ - flag=true; - idx++; - } - else idx--; - } - } - String st=""; - for(List arr:ans){ - for(char ch:arr) st+=ch; - } - return st; - } -} \ No newline at end of file diff --git a/606-construct-string-from-binary-tree/README.md b/606-construct-string-from-binary-tree/README.md deleted file mode 100644 index 3a309726..00000000 --- a/606-construct-string-from-binary-tree/README.md +++ /dev/null @@ -1,45 +0,0 @@ -

Construct String from Binary Tree

Difficulty: Medium

Given the root node of a binary tree, your task is to create a string representation of the tree following a specific set of formatting rules. The representation should be based on a preorder traversal of the binary tree and must adhere to the following guidelines:

- -
    -
  • -

    Node Representation: Each node in the tree should be represented by its integer value.

    -
  • -
  • -

    Parentheses for Children: If a node has at least one child (either left or right), its children should be represented inside parentheses. Specifically:

    - -
      -
    • If a node has a left child, the value of the left child should be enclosed in parentheses immediately following the node's value.
    • -
    • If a node has a right child, the value of the right child should also be enclosed in parentheses. The parentheses for the right child should follow those of the left child.
    • -
    -
  • -
  • -

    Omitting Empty Parentheses: Any empty parentheses pairs (i.e., ()) should be omitted from the final string representation of the tree, with one specific exception: when a node has a right child but no left child. In such cases, you must include an empty pair of parentheses to indicate the absence of the left child. This ensures that the one-to-one mapping between the string representation and the original binary tree structure is maintained.

    - -

    In summary, empty parentheses pairs should be omitted when a node has only a left child or no children. However, when a node has a right child but no left child, an empty pair of parentheses must precede the representation of the right child to reflect the tree's structure accurately.

    -
  • -
- -

 

-

Example 1:

- -
-Input: root = [1,2,3,4]
-Output: "1(2(4))(3)"
-Explanation: Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the empty parenthesis pairs. And it will be "1(2(4))(3)".
-
- -

Example 2:

- -
-Input: root = [1,2,3,null,4]
-Output: "1(2()(4))(3)"
-Explanation: Almost the same as the first example, except the () after 2 is necessary to indicate the absence of a left child for 2 and the presence of a right child.
-
- -

 

-

Constraints:

- -
    -
  • The number of nodes in the tree is in the range [1, 104].
  • -
  • -1000 <= Node.val <= 1000
  • -
diff --git a/606-construct-string-from-binary-tree/construct-string-from-binary-tree.java b/606-construct-string-from-binary-tree/construct-string-from-binary-tree.java deleted file mode 100644 index 4b4cf01a..00000000 --- a/606-construct-string-from-binary-tree/construct-string-from-binary-tree.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - String s=""; - public String tree2str(TreeNode root) { - if(root==null) return ""; - String st="("+tree2str(root.left)+")"; - String temp=tree2str(root.right); - if(temp.length()>0) temp="("+temp+")"; - if(st.equals("()") && temp.length()==0) return ""+root.val; - return ""+root.val+st+temp; - } -} \ No newline at end of file diff --git a/623-add-one-row-to-tree/README.md b/623-add-one-row-to-tree/README.md deleted file mode 100644 index ceee8e9a..00000000 --- a/623-add-one-row-to-tree/README.md +++ /dev/null @@ -1,38 +0,0 @@ -

Add One Row to Tree

Difficulty: Medium

Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.

- -

Note that the root node is at depth 1.

- -

The adding rule is:

- -
    -
  • Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root.
  • -
  • cur's original left subtree should be the left subtree of the new left subtree root.
  • -
  • cur's original right subtree should be the right subtree of the new right subtree root.
  • -
  • If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.
  • -
- -

 

-

Example 1:

- -
-Input: root = [4,2,6,3,1,5], val = 1, depth = 2
-Output: [4,1,1,2,null,null,6,3,1,5]
-
- -

Example 2:

- -
-Input: root = [4,2,null,3,1], val = 1, depth = 3
-Output: [4,2,null,1,1,3,null,null,1]
-
- -

 

-

Constraints:

- -
    -
  • The number of nodes in the tree is in the range [1, 104].
  • -
  • The depth of the tree is in the range [1, 104].
  • -
  • -100 <= Node.val <= 100
  • -
  • -105 <= val <= 105
  • -
  • 1 <= depth <= the depth of tree + 1
  • -
diff --git a/623-add-one-row-to-tree/add-one-row-to-tree.java b/623-add-one-row-to-tree/add-one-row-to-tree.java deleted file mode 100644 index 2efb5543..00000000 --- a/623-add-one-row-to-tree/add-one-row-to-tree.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public TreeNode addOneRow(TreeNode root, int val, int depth) { - if(depth==1){ - TreeNode temp=new TreeNode(val); - temp.left=root; - return temp; - } - func(root,val,depth,1); - return root; - } - public void func(TreeNode tree,int val,int depth,int i){ - if(tree==null) return; - if(i==depth-1){ - TreeNode templeft=tree.left; - TreeNode tempright=tree.right; - tree.left=new TreeNode(val); - tree.right=new TreeNode(val); - tree.left.left=templeft; - tree.right.right=tempright; - return; - } - func(tree.left,val,depth,i+1); - func(tree.right,val,depth,i+1); - return ; - } - -} \ No newline at end of file diff --git a/637-average-of-levels-in-binary-tree/README.md b/637-average-of-levels-in-binary-tree/README.md deleted file mode 100644 index 518e225e..00000000 --- a/637-average-of-levels-in-binary-tree/README.md +++ /dev/null @@ -1,25 +0,0 @@ -

Average of Levels in Binary Tree

Difficulty: Easy
Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted. -

 

-

Example 1:

- -
-Input: root = [3,9,20,null,null,15,7]
-Output: [3.00000,14.50000,11.00000]
-Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.
-Hence return [3, 14.5, 11].
-
- -

Example 2:

- -
-Input: root = [3,9,20,15,7]
-Output: [3.00000,14.50000,11.00000]
-
- -

 

-

Constraints:

- -
    -
  • The number of nodes in the tree is in the range [1, 104].
  • -
  • -231 <= Node.val <= 231 - 1
  • -
diff --git a/637-average-of-levels-in-binary-tree/average-of-levels-in-binary-tree.java b/637-average-of-levels-in-binary-tree/average-of-levels-in-binary-tree.java deleted file mode 100644 index a81f4b30..00000000 --- a/637-average-of-levels-in-binary-tree/average-of-levels-in-binary-tree.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public List averageOfLevels(TreeNode root) { - List arr=new ArrayList<>(); - if(root==null) return arr; - Queue stack=new LinkedList<>(); - stack.add(root); - while(!stack.isEmpty()){ - int size=stack.size(); - List tempArr=new ArrayList<>(); - Long sum=0L; - for(int i=0;iMaximum Binary Tree Difficulty: Medium

You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:

- -
    -
  1. Create a root node whose value is the maximum value in nums.
  2. -
  3. Recursively build the left subtree on the subarray prefix to the left of the maximum value.
  4. -
  5. Recursively build the right subtree on the subarray suffix to the right of the maximum value.
  6. -
- -

Return the maximum binary tree built from nums.

- -

 

-

Example 1:

- -
-Input: nums = [3,2,1,6,0,5]
-Output: [6,3,5,null,2,0,null,null,1]
-Explanation: The recursive calls are as follow:
-- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].
-    - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].
-        - Empty array, so no child.
-        - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].
-            - Empty array, so no child.
-            - Only one element, so child is a node with value 1.
-    - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].
-        - Only one element, so child is a node with value 0.
-        - Empty array, so no child.
-
- -

Example 2:

- -
-Input: nums = [3,2,1]
-Output: [3,null,2,null,1]
-
- -

 

-

Constraints:

- -
    -
  • 1 <= nums.length <= 1000
  • -
  • 0 <= nums[i] <= 1000
  • -
  • All integers in nums are unique.
  • -
diff --git a/654-maximum-binary-tree/maximum-binary-tree.java b/654-maximum-binary-tree/maximum-binary-tree.java deleted file mode 100644 index 996ef9a7..00000000 --- a/654-maximum-binary-tree/maximum-binary-tree.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public TreeNode constructMaximumBinaryTree(int[] nums) { - return func(nums,0,nums.length-1); - } - public TreeNode func(int[] nums,int i,int j){ - if(i>j) return null; - int max=Integer.MIN_VALUE; - int k=i; - for(int id=i;id<=j;id++){ - if(maxFind K Closest Elements Difficulty: Medium

Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.

- -

An integer a is closer to x than an integer b if:

- -
    -
  • |a - x| < |b - x|, or
  • -
  • |a - x| == |b - x| and a < b
  • -
- -

 

-

Example 1:

- -
-

Input: arr = [1,2,3,4,5], k = 4, x = 3

- -

Output: [1,2,3,4]

-
- -

Example 2:

- -
-

Input: arr = [1,1,2,3,4,5], k = 4, x = -1

- -

Output: [1,1,2,3]

-
- -

 

-

Constraints:

- -
    -
  • 1 <= k <= arr.length
  • -
  • 1 <= arr.length <= 104
  • -
  • arr is sorted in ascending order.
  • -
  • -104 <= arr[i], x <= 104
  • -
diff --git a/658-find-k-closest-elements/find-k-closest-elements.java b/658-find-k-closest-elements/find-k-closest-elements.java deleted file mode 100644 index 2e0fb46a..00000000 --- a/658-find-k-closest-elements/find-k-closest-elements.java +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { - public List findClosestElements(int[] arr, int k, int x) { - PriorityQueue pq=new PriorityQueue<>((a,b)->{ - if(a[0]==b[0]) return a[1]-b[1]; - else return a[0]-b[0]; - }); - List ans=new ArrayList<>(); - for(int i=0;iMaximum Width of Binary Tree Difficulty: Medium

Given the root of a binary tree, return the maximum width of the given tree.

- -

The maximum width of a tree is the maximum width among all levels.

- -

The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.

- -

It is guaranteed that the answer will in the range of a 32-bit signed integer.

- -

 

-

Example 1:

- -
-Input: root = [1,3,2,5,3,null,9]
-Output: 4
-Explanation: The maximum width exists in the third level with length 4 (5,3,null,9).
-
- -

Example 2:

- -
-Input: root = [1,3,2,5,null,null,9,6,null,7]
-Output: 7
-Explanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).
-
- -

Example 3:

- -
-Input: root = [1,3,2,5]
-Output: 2
-Explanation: The maximum width exists in the second level with length 2 (3,2).
-
- -

 

-

Constraints:

- -
    -
  • The number of nodes in the tree is in the range [1, 3000].
  • -
  • -100 <= Node.val <= 100
  • -
diff --git a/662-maximum-width-of-binary-tree/maximum-width-of-binary-tree.java b/662-maximum-width-of-binary-tree/maximum-width-of-binary-tree.java deleted file mode 100644 index 8f73f6f0..00000000 --- a/662-maximum-width-of-binary-tree/maximum-width-of-binary-tree.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public int widthOfBinaryTree(TreeNode root) { - int ans=0; - Queue stack=new LinkedList<>(); - stack.offer(new pair(root,0)); - while(!stack.isEmpty()){ - int n=stack.size(); - int inc=stack.peek().id; - int first=0,last=0; - for(int i=0;iTrim a Binary Search Tree Difficulty: Medium

Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.

- -

Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

- -

 

-

Example 1:

- -
-Input: root = [1,0,2], low = 1, high = 2
-Output: [1,null,2]
-
- -

Example 2:

- -
-Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
-Output: [3,2,null,1]
-
- -

 

-

Constraints:

- -
    -
  • The number of nodes in the tree is in the range [1, 104].
  • -
  • 0 <= Node.val <= 104
  • -
  • The value of each node in the tree is unique.
  • -
  • root is guaranteed to be a valid binary search tree.
  • -
  • 0 <= low <= high <= 104
  • -
diff --git a/669-trim-a-binary-search-tree/trim-a-binary-search-tree.java b/669-trim-a-binary-search-tree/trim-a-binary-search-tree.java deleted file mode 100644 index c8f92e6e..00000000 --- a/669-trim-a-binary-search-tree/trim-a-binary-search-tree.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public TreeNode trimBST(TreeNode root, int low, int high) { - if(root==null) return root; - root.left=trimBST(root.left,low,high); - root.right=trimBST(root.right,low,high); - if(root.val>high || root.valAdd Binary Difficulty: Easy

Given two binary strings a and b, return their sum as a binary string.

- -

 

-

Example 1:

-
Input: a = "11", b = "1"
-Output: "100"
-

Example 2:

-
Input: a = "1010", b = "1011"
-Output: "10101"
-
-

 

-

Constraints:

- -
    -
  • 1 <= a.length, b.length <= 104
  • -
  • a and b consist only of '0' or '1' characters.
  • -
  • Each string does not contain leading zeros except for the zero itself.
  • -
diff --git a/67-add-binary/add-binary.java b/67-add-binary/add-binary.java deleted file mode 100644 index 047e2f69..00000000 --- a/67-add-binary/add-binary.java +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { - public String addBinary(String a, String b) { - int n=0; - String ans=""; - int id1=a.length()-1; - while(a.length()!=0 || b.length()!=0){ - if(a.length()>0){ - n+=Character.getNumericValue(a.charAt(a.length()-1)); - a=a.substring(0,a.length()-1); - } - if(b.length()>0){ - n+=Character.getNumericValue(b.charAt(b.length()-1)); - b=b.substring(0,b.length()-1); - } - ans=(n%2)+ans; - n/=2; - } - if(n!=0) ans=n+ans; - return ans; - } -} \ No newline at end of file diff --git a/682BaseballGame.java b/682BaseballGame.java new file mode 100644 index 00000000..67655c3a --- /dev/null +++ b/682BaseballGame.java @@ -0,0 +1,22 @@ +class Solution { + public int calPoints(String[] operations) { + Stack stack=new Stack<>(); + for(String st:operations){ + if(st.equals("C")) stack.pop(); + else if(st.equals("D")) stack.push(stack.peek()*2); + else if(st.equals("+")){ + int a=stack.pop(); + int b=stack.pop(); + stack.push(b); + stack.push(a); + stack.push(a+b); + } + else stack.push(Integer.parseInt(st)); + } + int ans=0; + while(!stack.isEmpty()){ + ans+=stack.pop(); + } + return ans; + } +} \ No newline at end of file diff --git a/695-max-area-of-island/README.md b/695-max-area-of-island/README.md deleted file mode 100644 index b5bdf65f..00000000 --- a/695-max-area-of-island/README.md +++ /dev/null @@ -1,31 +0,0 @@ -

Max Area of Island

Difficulty: Medium

You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

- -

The area of an island is the number of cells with a value 1 in the island.

- -

Return the maximum area of an island in grid. If there is no island, return 0.

- -

 

-

Example 1:

- -
-Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
-Output: 6
-Explanation: The answer is not 11, because the island must be connected 4-directionally.
-
- -

Example 2:

- -
-Input: grid = [[0,0,0,0,0,0,0,0]]
-Output: 0
-
- -

 

-

Constraints:

- -
    -
  • m == grid.length
  • -
  • n == grid[i].length
  • -
  • 1 <= m, n <= 50
  • -
  • grid[i][j] is either 0 or 1.
  • -
diff --git a/695-max-area-of-island/max-area-of-island.java b/695-max-area-of-island/max-area-of-island.java deleted file mode 100644 index bc1ee3fb..00000000 --- a/695-max-area-of-island/max-area-of-island.java +++ /dev/null @@ -1,41 +0,0 @@ -class Solution { - public int maxAreaOfIsland(int[][] grid) { - int max=0; - for(int i=0;i q=new LinkedList<>(); - q.add(new pair(id,j)); - int[][] direction = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; - while(!q.isEmpty()){ - ans++; - pair temp=q.poll(); - int r=temp.first; - int c=temp.second; - for (int[] i : direction) { - if (r + i[0] < grid.length && r + i[0] >= 0 && c + i[1] < grid[0].length && c + i[1] >= 0 && grid[r + i[0]][c + i[1]]==1 ) { - q.add(new pair(r+i[0],c+i[1])); - grid[r + i[0]][c + i[1]] = 2; - } - } - } - return ans; - } -} \ No newline at end of file diff --git a/725-split-linked-list-in-parts/README.md b/725-split-linked-list-in-parts/README.md deleted file mode 100644 index 63190991..00000000 --- a/725-split-linked-list-in-parts/README.md +++ /dev/null @@ -1,36 +0,0 @@ -

Split Linked List in Parts

Difficulty: Medium

Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts.

- -

The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.

- -

The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.

- -

Return an array of the k parts.

- -

 

-

Example 1:

- -
-Input: head = [1,2,3], k = 5
-Output: [[1],[2],[3],[],[]]
-Explanation:
-The first element output[0] has output[0].val = 1, output[0].next = null.
-The last element output[4] is null, but its string representation as a ListNode is [].
-
- -

Example 2:

- -
-Input: head = [1,2,3,4,5,6,7,8,9,10], k = 3
-Output: [[1,2,3,4],[5,6,7],[8,9,10]]
-Explanation:
-The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
-
- -

 

-

Constraints:

- -
    -
  • The number of nodes in the list is in the range [0, 1000].
  • -
  • 0 <= Node.val <= 1000
  • -
  • 1 <= k <= 50
  • -
diff --git a/725-split-linked-list-in-parts/split-linked-list-in-parts.java b/725-split-linked-list-in-parts/split-linked-list-in-parts.java deleted file mode 100644 index 45da64d6..00000000 --- a/725-split-linked-list-in-parts/split-linked-list-in-parts.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode[] splitListToParts(ListNode head, int k) { - int size=0; - ListNode temp=head; - while(temp!=null){ - size++; - temp=temp.next; - } - ListNode ans[]=new ListNode[k]; - if(size0){ - if(size>0){ - ListNode a=new ListNode(head.val); - head=head.next; - size--; - ans[i++]=a; - } - else{ - ans[i++]=null; - - } - } - } - else{ - if(size%k!=0){ - int id=size%k; - size/=k; - int i=0; - while(id-->0){ - ListNode b=new ListNode(0); - ListNode append=b; - for(int j=0;j<=size;j++){ - b.next=new ListNode(head.val); - head=head.next; - b=b.next; - } - ans[i++]=append.next; - k--; - } - while(k-->0){ - ListNode c=new ListNode(0); - ListNode append1=c; - for(int j=0;j0){ - ListNode c=new ListNode(0); - ListNode append1=c; - for(int j=0;jMy Calendar I Difficulty: Medium

You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a double booking.

- -

A double booking happens when two events have some non-empty intersection (i.e., some moment is common to both events.).

- -

The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end), the range of real numbers x such that start <= x < end.

- -

Implement the MyCalendar class:

- -
    -
  • MyCalendar() Initializes the calendar object.
  • -
  • boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a double booking. Otherwise, return false and do not add the event to the calendar.
  • -
- -

 

-

Example 1:

- -
-Input
-["MyCalendar", "book", "book", "book"]
-[[], [10, 20], [15, 25], [20, 30]]
-Output
-[null, true, false, true]
-
-Explanation
-MyCalendar myCalendar = new MyCalendar();
-myCalendar.book(10, 20); // return True
-myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.
-myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.
- -

 

-

Constraints:

- -
    -
  • 0 <= start < end <= 109
  • -
  • At most 1000 calls will be made to book.
  • -
diff --git a/729-my-calendar-i/my-calendar-i.java b/729-my-calendar-i/my-calendar-i.java deleted file mode 100644 index f4c6a512..00000000 --- a/729-my-calendar-i/my-calendar-i.java +++ /dev/null @@ -1,23 +0,0 @@ -class MyCalendar { -List arr; - public MyCalendar() { - arr=new ArrayList<>(); - } - - public boolean book(int start, int end) { - for(int[] nums:arr){ - if(startnums[0]){ - return false; - } - } - arr.add(new int[]{start,end}); - Collections.sort(arr,(a,b) -> a[0] - b[0]); - return true; - } -} - -/** - * Your MyCalendar object will be instantiated and called as such: - * MyCalendar obj = new MyCalendar(); - * boolean param_1 = obj.book(start,end); - */ \ No newline at end of file diff --git a/733-flood-fill/README.md b/733-flood-fill/README.md deleted file mode 100644 index 63b0feba..00000000 --- a/733-flood-fill/README.md +++ /dev/null @@ -1,53 +0,0 @@ -

Flood Fill

Difficulty: Easy

You are given an image represented by an m x n grid of integers image, where image[i][j] represents the pixel value of the image. You are also given three integers sr, sc, and color. Your task is to perform a flood fill on the image starting from the pixel image[sr][sc].

- -

To perform a flood fill:

- -
    -
  1. Begin with the starting pixel and change its color to color.
  2. -
  3. Perform the same process for each pixel that is directly adjacent (pixels that share a side with the original pixel, either horizontally or vertically) and shares the same color as the starting pixel.
  4. -
  5. Keep repeating this process by checking neighboring pixels of the updated pixels and modifying their color if it matches the original color of the starting pixel.
  6. -
  7. The process stops when there are no more adjacent pixels of the original color to update.
  8. -
- -

Return the modified image after performing the flood fill.

- -

 

-

Example 1:

- -
-

Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2

- -

Output: [[2,2,2],[2,2,0],[2,0,1]]

- -

Explanation:

- -

- -

From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.

- -

Note the bottom corner is not colored 2, because it is not horizontally or vertically connected to the starting pixel.

-
- -

Example 2:

- -
-

Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0

- -

Output: [[0,0,0],[0,0,0]]

- -

Explanation:

- -

The starting pixel is already colored with 0, which is the same as the target color. Therefore, no changes are made to the image.

-
- -

 

-

Constraints:

- -
    -
  • m == image.length
  • -
  • n == image[i].length
  • -
  • 1 <= m, n <= 50
  • -
  • 0 <= image[i][j], color < 216
  • -
  • 0 <= sr < m
  • -
  • 0 <= sc < n
  • -
diff --git a/733-flood-fill/flood-fill.java b/733-flood-fill/flood-fill.java deleted file mode 100644 index a0d23698..00000000 --- a/733-flood-fill/flood-fill.java +++ /dev/null @@ -1,34 +0,0 @@ -class Solution { - public int[][] floodFill(int[][] image, int sr, int sc, int color) { - int start=image[sr][sc]; - bfs(start,sr,sc,color,image); - return image; - } - class pair{ - int first; - int second; - pair(int first,int second){ - this.first=first; - this.second=second; - } - } - public void bfs(int start,int row,int col,int color,int[][] arr){ - arr[row][col]=color; - Queue q=new LinkedList<>(); - boolean[][] visited=new boolean[arr.length][arr[0].length]; - q.add(new pair(row,col)); - while(!q.isEmpty()){ - pair temp=q.poll(); - int r=temp.first; - int c=temp.second; - int[][]direction={{0,1},{1,0},{0,-1},{-1,0}}; - for(int[] num:direction){ - if(r+num[0]=0 && c+num[1]>=0 && c+num[1]Sort Colors Difficulty: Medium

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

- -

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

- -

You must solve this problem without using the library's sort function.

- -

 

-

Example 1:

- -
-Input: nums = [2,0,2,1,1,0]
-Output: [0,0,1,1,2,2]
-
- -

Example 2:

- -
-Input: nums = [2,0,1]
-Output: [0,1,2]
-
- -

 

-

Constraints:

- -
    -
  • n == nums.length
  • -
  • 1 <= n <= 300
  • -
  • nums[i] is either 0, 1, or 2.
  • -
- -

 

-

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

diff --git a/75-sort-colors/sort-colors.java b/75-sort-colors/sort-colors.java deleted file mode 100644 index b8334136..00000000 --- a/75-sort-colors/sort-colors.java +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { - public void sortColors(int[] nums) { - int zero=0; - int one=0; - int two=0; - int i=0; - for(int a:nums){ - if(a==0)zero++; - if(a==1)one++; - if(a==2)two++; - } - while(zero-->0)nums[i++]=0; - while(one-->0) nums[i++]=1; - while(two-->0) nums[i++]=2; - } -} \ No newline at end of file diff --git a/783-search-in-a-binary-search-tree/README.md b/783-search-in-a-binary-search-tree/README.md deleted file mode 100644 index 03534276..00000000 --- a/783-search-in-a-binary-search-tree/README.md +++ /dev/null @@ -1,28 +0,0 @@ -

Search in a Binary Search Tree

Difficulty: Easy

You are given the root of a binary search tree (BST) and an integer val.

- -

Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.

- -

 

-

Example 1:

- -
-Input: root = [4,2,7,1,3], val = 2
-Output: [2,1,3]
-
- -

Example 2:

- -
-Input: root = [4,2,7,1,3], val = 5
-Output: []
-
- -

 

-

Constraints:

- -
    -
  • The number of nodes in the tree is in the range [1, 5000].
  • -
  • 1 <= Node.val <= 107
  • -
  • root is a binary search tree.
  • -
  • 1 <= val <= 107
  • -
diff --git a/784-insert-into-a-binary-search-tree/README.md b/784-insert-into-a-binary-search-tree/README.md deleted file mode 100644 index a0fc67b1..00000000 --- a/784-insert-into-a-binary-search-tree/README.md +++ /dev/null @@ -1,38 +0,0 @@ -

Insert into a Binary Search Tree

Difficulty: Medium

You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

- -

Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

- -

 

-

Example 1:

- -
-Input: root = [4,2,7,1,3], val = 5
-Output: [4,2,7,1,3,5]
-Explanation: Another accepted tree is:
-
-
- -

Example 2:

- -
-Input: root = [40,20,60,10,30,50,70], val = 25
-Output: [40,20,60,10,30,50,70,null,null,25]
-
- -

Example 3:

- -
-Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5
-Output: [4,2,7,1,3,5]
-
- -

 

-

Constraints:

- -
    -
  • The number of nodes in the tree will be in the range [0, 104].
  • -
  • -108 <= Node.val <= 108
  • -
  • All the values Node.val are unique.
  • -
  • -108 <= val <= 108
  • -
  • It's guaranteed that val does not exist in the original BST.
  • -
diff --git a/80-remove-duplicates-from-sorted-array-ii/README.md b/80-remove-duplicates-from-sorted-array-ii/README.md deleted file mode 100644 index ded62415..00000000 --- a/80-remove-duplicates-from-sorted-array-ii/README.md +++ /dev/null @@ -1,53 +0,0 @@ -

Remove Duplicates from Sorted Array II

Difficulty: Medium

Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.

- -

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

- -

Return k after placing the final result in the first k slots of nums.

- -

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

- -

Custom Judge:

- -

The judge will test your solution with the following code:

- -
-int[] nums = [...]; // Input array
-int[] expectedNums = [...]; // The expected answer with correct length
-
-int k = removeDuplicates(nums); // Calls your implementation
-
-assert k == expectedNums.length;
-for (int i = 0; i < k; i++) {
-    assert nums[i] == expectedNums[i];
-}
-
- -

If all assertions pass, then your solution will be accepted.

- -

 

-

Example 1:

- -
-Input: nums = [1,1,1,2,2,3]
-Output: 5, nums = [1,1,2,2,3,_]
-Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
-It does not matter what you leave beyond the returned k (hence they are underscores).
-
- -

Example 2:

- -
-Input: nums = [0,0,1,1,1,1,2,3,3]
-Output: 7, nums = [0,0,1,1,2,3,3,_,_]
-Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.
-It does not matter what you leave beyond the returned k (hence they are underscores).
-
- -

 

-

Constraints:

- -
    -
  • 1 <= nums.length <= 3 * 104
  • -
  • -104 <= nums[i] <= 104
  • -
  • nums is sorted in non-decreasing order.
  • -
diff --git a/80-remove-duplicates-from-sorted-array-ii/remove-duplicates-from-sorted-array-ii.java b/80-remove-duplicates-from-sorted-array-ii/remove-duplicates-from-sorted-array-ii.java deleted file mode 100644 index cb19e9f8..00000000 --- a/80-remove-duplicates-from-sorted-array-ii/remove-duplicates-from-sorted-array-ii.java +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { - public int removeDuplicates(int[] nums) { - Map map=new HashMap<>(); - int ans=0; - int j=0; - for(int i=0;iIs Graph Bipartite? Difficulty: Medium

There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties:

- -
    -
  • There are no self-edges (graph[u] does not contain u).
  • -
  • There are no parallel edges (graph[u] does not contain duplicate values).
  • -
  • If v is in graph[u], then u is in graph[v] (the graph is undirected).
  • -
  • The graph may not be connected, meaning there may be two nodes u and v such that there is no path between them.
  • -
- -

A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.

- -

Return true if and only if it is bipartite.

- -

 

-

Example 1:

- -
-Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
-Output: false
-Explanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.
- -

Example 2:

- -
-Input: graph = [[1,3],[0,2],[1,3],[0,2]]
-Output: true
-Explanation: We can partition the nodes into two sets: {0, 2} and {1, 3}.
- -

 

-

Constraints:

- -
    -
  • graph.length == n
  • -
  • 1 <= n <= 100
  • -
  • 0 <= graph[u].length < n
  • -
  • 0 <= graph[u][i] <= n - 1
  • -
  • graph[u] does not contain u.
  • -
  • All the values of graph[u] are unique.
  • -
  • If graph[u] contains v, then graph[v] contains u.
  • -
diff --git a/801-is-graph-bipartite/is-graph-bipartite.java b/801-is-graph-bipartite/is-graph-bipartite.java deleted file mode 100644 index fb2943c4..00000000 --- a/801-is-graph-bipartite/is-graph-bipartite.java +++ /dev/null @@ -1,33 +0,0 @@ -class Solution { - public boolean isBipartite(int[][] graph) { - int[]vis=new int[graph.length]; - for(int i=0;i q=new LinkedList<>(); - int k=idx; - vis[idx]=1; - q.add(idx); - while(!q.isEmpty()){ - idx=q.poll(); - for(int i=0;iK-th Smallest Prime Fraction Difficulty: Medium

You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k.

- -

For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].

- -

Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].

- -

 

-

Example 1:

- -
-Input: arr = [1,2,3,5], k = 3
-Output: [2,5]
-Explanation: The fractions to be considered in sorted order are:
-1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.
-The third fraction is 2/5.
-
- -

Example 2:

- -
-Input: arr = [1,7], k = 1
-Output: [1,7]
-
- -

 

-

Constraints:

- -
    -
  • 2 <= arr.length <= 1000
  • -
  • 1 <= arr[i] <= 3 * 104
  • -
  • arr[0] == 1
  • -
  • arr[i] is a prime number for i > 0.
  • -
  • All the numbers of arr are unique and sorted in strictly increasing order.
  • -
  • 1 <= k <= arr.length * (arr.length - 1) / 2
  • -
- -

 

-Follow up: Can you solve the problem with better than O(n2) complexity? \ No newline at end of file diff --git a/802-k-th-smallest-prime-fraction/k-th-smallest-prime-fraction.java b/802-k-th-smallest-prime-fraction/k-th-smallest-prime-fraction.java deleted file mode 100644 index af9666a0..00000000 --- a/802-k-th-smallest-prime-fraction/k-th-smallest-prime-fraction.java +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { - public int[] kthSmallestPrimeFraction(int[] arr, int k) { - PriorityQueue pq=new PriorityQueue<>((a,b)->Double.compare(a[0]/a[1], b[0]/b[1])); - for(int i=0;i1){ - pq.poll(); - } - double[] temp=pq.poll(); - int ans[]=new int[]{(int)(temp[0]),(int)(temp[1])}; - return ans; - } -} \ No newline at end of file diff --git a/812-rotate-string/README.md b/812-rotate-string/README.md deleted file mode 100644 index deae25c7..00000000 --- a/812-rotate-string/README.md +++ /dev/null @@ -1,23 +0,0 @@ -

Rotate String

Difficulty: Easy

Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.

- -

A shift on s consists of moving the leftmost character of s to the rightmost position.

- -
    -
  • For example, if s = "abcde", then it will be "bcdea" after one shift.
  • -
- -

 

-

Example 1:

-
Input: s = "abcde", goal = "cdeab"
-Output: true
-

Example 2:

-
Input: s = "abcde", goal = "abced"
-Output: false
-
-

 

-

Constraints:

- -
    -
  • 1 <= s.length, goal.length <= 100
  • -
  • s and goal consist of lowercase English letters.
  • -
diff --git a/812-rotate-string/rotate-string.java b/812-rotate-string/rotate-string.java deleted file mode 100644 index a00069da..00000000 --- a/812-rotate-string/rotate-string.java +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { - public boolean rotateString(String s, String goal) { - int i=0; - while(iLongest Mountain in Array Difficulty: Medium

You may recall that an array arr is a mountain array if and only if:

- -
    -
  • arr.length >= 3
  • -
  • There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: -
      -
    • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
    • -
    • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
    • -
    -
  • -
- -

Given an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray.

- -

 

-

Example 1:

- -
-Input: arr = [2,1,4,7,3,2,5]
-Output: 5
-Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
-
- -

Example 2:

- -
-Input: arr = [2,2,2]
-Output: 0
-Explanation: There is no mountain.
-
- -

 

-

Constraints:

- -
    -
  • 1 <= arr.length <= 104
  • -
  • 0 <= arr[i] <= 104
  • -
- -

 

-

Follow up:

- -
    -
  • Can you solve it using only one pass?
  • -
  • Can you solve it in O(1) space?
  • -
diff --git a/875-longest-mountain-in-array/longest-mountain-in-array.java b/875-longest-mountain-in-array/longest-mountain-in-array.java deleted file mode 100644 index fc40f002..00000000 --- a/875-longest-mountain-in-array/longest-mountain-in-array.java +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { - public int longestMountain(int[] arr) { - if(arr.length<3) return 0; - int ans=0; - for(int i=1;iarr[i+1]){ - int left=i-1; - int right=i+1; - while(left>0 && arr[left]>arr[left-1]) left--; - while(rightarr[right+1]) right++; - ans=Math.max(ans,right-left+1); - i=right; - } - } - return ans; - } -} \ No newline at end of file diff --git a/88-merge-sorted-array/README.md b/88-merge-sorted-array/README.md deleted file mode 100644 index 066a6f84..00000000 --- a/88-merge-sorted-array/README.md +++ /dev/null @@ -1,48 +0,0 @@ -

Merge Sorted Array

Difficulty: Easy

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

- -

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

- -

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

- -

 

-

Example 1:

- -
-Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
-Output: [1,2,2,3,5,6]
-Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
-The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
-
- -

Example 2:

- -
-Input: nums1 = [1], m = 1, nums2 = [], n = 0
-Output: [1]
-Explanation: The arrays we are merging are [1] and [].
-The result of the merge is [1].
-
- -

Example 3:

- -
-Input: nums1 = [0], m = 0, nums2 = [1], n = 1
-Output: [1]
-Explanation: The arrays we are merging are [] and [1].
-The result of the merge is [1].
-Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
-
- -

 

-

Constraints:

- -
    -
  • nums1.length == m + n
  • -
  • nums2.length == n
  • -
  • 0 <= m, n <= 200
  • -
  • 1 <= m + n <= 200
  • -
  • -109 <= nums1[i], nums2[j] <= 109
  • -
- -

 

-

Follow up: Can you come up with an algorithm that runs in O(m + n) time?

diff --git a/88-merge-sorted-array/merge-sorted-array.java b/88-merge-sorted-array/merge-sorted-array.java deleted file mode 100644 index a63dbc53..00000000 --- a/88-merge-sorted-array/merge-sorted-array.java +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { - public static void merge(int[] nums1, int m, int[] nums2, int n) { - int j=0; - for(int i=0;iPeak Index in a Mountain Array Difficulty: Medium

You are given an integer mountain array arr of length n where the values increase to a peak element and then decrease.

- -

Return the index of the peak element.

- -

Your task is to solve it in O(log(n)) time complexity.

- -

 

-

Example 1:

- -
-

Input: arr = [0,1,0]

- -

Output: 1

-
- -

Example 2:

- -
-

Input: arr = [0,2,1,0]

- -

Output: 1

-
- -

Example 3:

- -
-

Input: arr = [0,10,5,2]

- -

Output: 1

-
- -

 

-

Constraints:

- -
    -
  • 3 <= arr.length <= 105
  • -
  • 0 <= arr[i] <= 106
  • -
  • arr is guaranteed to be a mountain array.
  • -
diff --git a/882-peak-index-in-a-mountain-array/peak-index-in-a-mountain-array.java b/882-peak-index-in-a-mountain-array/peak-index-in-a-mountain-array.java deleted file mode 100644 index de2fb471..00000000 --- a/882-peak-index-in-a-mountain-array/peak-index-in-a-mountain-array.java +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { - public int peakIndexInMountainArray(int[] arr) { - int i=0; - int j=arr.length-1; - while(iBuddy Strings Difficulty: Easy

Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.

- -

Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].

- -
    -
  • For example, swapping at indices 0 and 2 in "abcd" results in "cbad".
  • -
- -

 

-

Example 1:

- -
-Input: s = "ab", goal = "ba"
-Output: true
-Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
-
- -

Example 2:

- -
-Input: s = "ab", goal = "ab"
-Output: false
-Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.
-
- -

Example 3:

- -
-Input: s = "aa", goal = "aa"
-Output: true
-Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.
-
- -

 

-

Constraints:

- -
    -
  • 1 <= s.length, goal.length <= 2 * 104
  • -
  • s and goal consist of lowercase letters.
  • -
diff --git a/889-buddy-strings/buddy-strings.java b/889-buddy-strings/buddy-strings.java deleted file mode 100644 index f4a10371..00000000 --- a/889-buddy-strings/buddy-strings.java +++ /dev/null @@ -1,30 +0,0 @@ -class Solution { - public boolean buddyStrings(String s, String goal) { - if(s.length()!=goal.length()) return false; - boolean flag=false; - char[] crr=new char[4]; - int[]arr=new int[26]; - int id=0; - if(s.equals(goal)) flag=true; - for(int i=0;i=2) return true; - } - } - else{ - if(crr[0]!=crr[3] || crr[1]!=crr[2]) return false; - else return true; - } - return false; - } -} \ No newline at end of file diff --git a/890-lemonade-change/README.md b/890-lemonade-change/README.md deleted file mode 100644 index c132dffb..00000000 --- a/890-lemonade-change/README.md +++ /dev/null @@ -1,38 +0,0 @@ -

Lemonade Change

Difficulty: Easy

At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5.

- -

Note that you do not have any change in hand at first.

- -

Given an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise.

- -

 

-

Example 1:

- -
-Input: bills = [5,5,5,10,20]
-Output: true
-Explanation: 
-From the first 3 customers, we collect three $5 bills in order.
-From the fourth customer, we collect a $10 bill and give back a $5.
-From the fifth customer, we give a $10 bill and a $5 bill.
-Since all customers got correct change, we output true.
-
- -

Example 2:

- -
-Input: bills = [5,5,10,10,20]
-Output: false
-Explanation: 
-From the first two customers in order, we collect two $5 bills.
-For the next two customers in order, we collect a $10 bill and give back a $5 bill.
-For the last customer, we can not give the change of $15 back because we only have two $10 bills.
-Since not every customer received the correct change, the answer is false.
-
- -

 

-

Constraints:

- -
    -
  • 1 <= bills.length <= 105
  • -
  • bills[i] is either 5, 10, or 20.
  • -
diff --git a/890-lemonade-change/lemonade-change.java b/890-lemonade-change/lemonade-change.java deleted file mode 100644 index 350bd47a..00000000 --- a/890-lemonade-change/lemonade-change.java +++ /dev/null @@ -1,26 +0,0 @@ -class Solution { - public boolean lemonadeChange(int[] bills) { - int five = 0; - int ten = 0; - for (int a : bills) { - if (a == 20) { - if (five > 0 && ten > 0) { - five--; - ten--; - } else if (five > 2) - five -= 3; - else - return false; - } else if (a == 10) { - if (five > 0) { - five--; - } else - return false; - ten++; - } else { - five++; - } - } - return true; - } -} \ No newline at end of file diff --git a/893-all-nodes-distance-k-in-binary-tree/README.md b/893-all-nodes-distance-k-in-binary-tree/README.md deleted file mode 100644 index 8d8dd100..00000000 --- a/893-all-nodes-distance-k-in-binary-tree/README.md +++ /dev/null @@ -1,30 +0,0 @@ -

All Nodes Distance K in Binary Tree

Difficulty: Medium

Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node.

- -

You can return the answer in any order.

- -

 

-

Example 1:

- -
-Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
-Output: [7,4,1]
-Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
-
- -

Example 2:

- -
-Input: root = [1], target = 1, k = 3
-Output: []
-
- -

 

-

Constraints:

- -
    -
  • The number of nodes in the tree is in the range [1, 500].
  • -
  • 0 <= Node.val <= 500
  • -
  • All the values Node.val are unique.
  • -
  • target is the value of one of the nodes in the tree.
  • -
  • 0 <= k <= 1000
  • -
diff --git a/893-all-nodes-distance-k-in-binary-tree/all-nodes-distance-k-in-binary-tree.java b/893-all-nodes-distance-k-in-binary-tree/all-nodes-distance-k-in-binary-tree.java deleted file mode 100644 index fc135d4a..00000000 --- a/893-all-nodes-distance-k-in-binary-tree/all-nodes-distance-k-in-binary-tree.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -class Solution { - public List distanceK(TreeNode root, TreeNode target, int k) { - Map map=new HashMap<>(); - put_map(root,map); - Map check=new HashMap<>(); - Queue stack=new LinkedList<>(); - stack.offer(target); - check.put(target,true); - int dis=0; - while(!stack.isEmpty()){ - if(dis==k) break; - dis++; - int n=stack.size(); - for(int i=0;i ans=new ArrayList<>(); - while(!stack.isEmpty()){ - ans.add(stack.poll().val); - } - return ans; - - } - public void put_map(TreeNode root,Map map){ - if(root==null) return; - if(root.left!=null) map.put(root.left,root); - if(root.right!=null) map.put(root.right,root); - put_map(root.left,map); - put_map(root.right,map); - } -} \ No newline at end of file diff --git a/9-palindrome-number/README.md b/9-palindrome-number/README.md deleted file mode 100644 index 60ccf187..00000000 --- a/9-palindrome-number/README.md +++ /dev/null @@ -1,36 +0,0 @@ -

Palindrome Number

Difficulty: Easy

Given an integer x, return true if x is a palindrome, and false otherwise.

- -

 

-

Example 1:

- -
-Input: x = 121
-Output: true
-Explanation: 121 reads as 121 from left to right and from right to left.
-
- -

Example 2:

- -
-Input: x = -121
-Output: false
-Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
-
- -

Example 3:

- -
-Input: x = 10
-Output: false
-Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
-
- -

 

-

Constraints:

- -
    -
  • -231 <= x <= 231 - 1
  • -
- -

 

-Follow up: Could you solve it without converting the integer to a string? \ No newline at end of file diff --git a/9-palindrome-number/palindrome-number.java b/9-palindrome-number/palindrome-number.java deleted file mode 100644 index a191ddbd..00000000 --- a/9-palindrome-number/palindrome-number.java +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { - public boolean isPalindrome(int x) { - int y=x; - int new_element=0; - while(y>0){ - int k=y%10; - y=y/10; - new_element=new_element*10+k; - } - if(x==new_element){ - return true; - } - else{ - return false; - } - } -} \ No newline at end of file diff --git a/90-subsets-ii/README.md b/90-subsets-ii/README.md deleted file mode 100644 index 0a771dc0..00000000 --- a/90-subsets-ii/README.md +++ /dev/null @@ -1,19 +0,0 @@ -

Subsets II

Difficulty: Medium

Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

- -

The solution set must not contain duplicate subsets. Return the solution in any order.

- -

 

-

Example 1:

-
Input: nums = [1,2,2]
-Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
-

Example 2:

-
Input: nums = [0]
-Output: [[],[0]]
-
-

 

-

Constraints:

- -
    -
  • 1 <= nums.length <= 10
  • -
  • -10 <= nums[i] <= 10
  • -
diff --git a/90-subsets-ii/subsets-ii.java b/90-subsets-ii/subsets-ii.java deleted file mode 100644 index f01104f9..00000000 --- a/90-subsets-ii/subsets-ii.java +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { - public List> subsetsWithDup(int[] nums) { - List arr=new ArrayList<>(); - List> list=new ArrayList<>(); - Arrays.sort(nums); - func(list,arr,0,nums); - return list; - } - public void func(List> arr,List list,int i,int[] nums){ - arr.add(new ArrayList<>(list)); - for(int j=i;ji && nums[j]==nums[j-1]) continue; - list.add(nums[j]); - func(arr,list,j+1,nums); - list.remove(list.size()-1); - } - } -} \ No newline at end of file diff --git a/94-binary-tree-inorder-traversal/README.md b/94-binary-tree-inorder-traversal/README.md deleted file mode 100644 index 97e71ffb..00000000 --- a/94-binary-tree-inorder-traversal/README.md +++ /dev/null @@ -1,34 +0,0 @@ -

Binary Tree Inorder Traversal

Difficulty: Easy

Given the root of a binary tree, return the inorder traversal of its nodes' values.

- -

 

-

Example 1:

- -
-Input: root = [1,null,2,3]
-Output: [1,3,2]
-
- -

Example 2:

- -
-Input: root = []
-Output: []
-
- -

Example 3:

- -
-Input: root = [1]
-Output: [1]
-
- -

 

-

Constraints:

- -
    -
  • The number of nodes in the tree is in the range [0, 100].
  • -
  • -100 <= Node.val <= 100
  • -
- -

 

-Follow up: Recursive solution is trivial, could you do it iteratively? \ No newline at end of file diff --git a/94-binary-tree-inorder-traversal/binary-tree-inorder-traversal.java b/94-binary-tree-inorder-traversal/binary-tree-inorder-traversal.java deleted file mode 100644 index 1b950d70..00000000 --- a/94-binary-tree-inorder-traversal/binary-tree-inorder-traversal.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public List inorderTraversal(TreeNode root) { - List ans=new ArrayList<>(); - if(root==null) return ans; - Stack stack=new Stack<>(); - while(!stack.isEmpty() || root!=null){ - while(root!=null){ - stack.push(root); - root=root.left; - } - TreeNode temp=stack.pop(); - ans.add(temp.val); - root=temp.right; - } - return ans; - } -} \ No newline at end of file diff --git a/941-sort-array-by-parity/README.md b/941-sort-array-by-parity/README.md deleted file mode 100644 index 456f9e5e..00000000 --- a/941-sort-array-by-parity/README.md +++ /dev/null @@ -1,27 +0,0 @@ -

Sort Array By Parity

Difficulty: Easy

Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.

- -

Return any array that satisfies this condition.

- -

 

-

Example 1:

- -
-Input: nums = [3,1,2,4]
-Output: [2,4,3,1]
-Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
-
- -

Example 2:

- -
-Input: nums = [0]
-Output: [0]
-
- -

 

-

Constraints:

- -
    -
  • 1 <= nums.length <= 5000
  • -
  • 0 <= nums[i] <= 5000
  • -
diff --git a/941-sort-array-by-parity/sort-array-by-parity.java b/941-sort-array-by-parity/sort-array-by-parity.java deleted file mode 100644 index a4a332a6..00000000 --- a/941-sort-array-by-parity/sort-array-by-parity.java +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { - public int[] sortArrayByParity(int[] nums) { - int i=0; - int j=nums.length-1; - while(iMinimum Add to Make Parentheses Valid Difficulty: Medium

A parentheses string is valid if and only if:

- -
    -
  • It is the empty string,
  • -
  • It can be written as AB (A concatenated with B), where A and B are valid strings, or
  • -
  • It can be written as (A), where A is a valid string.
  • -
- -

You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string.

- -
    -
  • For example, if s = "()))", you can insert an opening parenthesis to be "(()))" or a closing parenthesis to be "())))".
  • -
- -

Return the minimum number of moves required to make s valid.

- -

 

-

Example 1:

- -
-Input: s = "())"
-Output: 1
-
- -

Example 2:

- -
-Input: s = "((("
-Output: 3
-
- -

 

-

Constraints:

- -
    -
  • 1 <= s.length <= 1000
  • -
  • s[i] is either '(' or ')'.
  • -
diff --git a/957-minimum-add-to-make-parentheses-valid/minimum-add-to-make-parentheses-valid.java b/957-minimum-add-to-make-parentheses-valid/minimum-add-to-make-parentheses-valid.java deleted file mode 100644 index b441272a..00000000 --- a/957-minimum-add-to-make-parentheses-valid/minimum-add-to-make-parentheses-valid.java +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { - public int minAddToMakeValid(String s) { - Stack stack=new Stack<>(); - for(char c:s.toCharArray()){ - if(!stack.isEmpty()){ - if(stack.peek()=='(' && c==')') stack.pop(); - else stack.push(c); - } - else stack.push(c); - } - return stack.size(); - } -} \ No newline at end of file diff --git a/98-validate-binary-search-tree/README.md b/98-validate-binary-search-tree/README.md deleted file mode 100644 index 93936243..00000000 --- a/98-validate-binary-search-tree/README.md +++ /dev/null @@ -1,33 +0,0 @@ -

Validate Binary Search Tree

Difficulty: Medium

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

- -

A valid BST is defined as follows:

- -
    -
  • The left subtree of a node contains only nodes with keys less than the node's key.
  • -
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • -
  • Both the left and right subtrees must also be binary search trees.
  • -
- -

 

-

Example 1:

- -
-Input: root = [2,1,3]
-Output: true
-
- -

Example 2:

- -
-Input: root = [5,1,4,null,null,3,6]
-Output: false
-Explanation: The root node's value is 5 but its right child's value is 4.
-
- -

 

-

Constraints:

- -
    -
  • The number of nodes in the tree is in the range [1, 104].
  • -
  • -231 <= Node.val <= 231 - 1
  • -
diff --git a/98-validate-binary-search-tree/validate-binary-search-tree.java b/98-validate-binary-search-tree/validate-binary-search-tree.java deleted file mode 100644 index 384d23c6..00000000 --- a/98-validate-binary-search-tree/validate-binary-search-tree.java +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { - public boolean isValidBST(TreeNode root) { - return func(root, Long.MIN_VALUE, Long.MAX_VALUE); - } - - public boolean func(TreeNode root, long min, long max) { - if (root == null) return true; - if (root.val <= min || root.val >= max) return false; - return func(root.left, min, root.val) && func(root.right, root.val, max); - } -} diff --git a/reverseStack.java b/reverseStack.java new file mode 100644 index 00000000..9f10031d --- /dev/null +++ b/reverseStack.java @@ -0,0 +1,34 @@ +import java.util.Stack; +class reverse{ + public static void main(String[] args) { + Stack stack=new Stack<>(); + func(5,stack); + // Stack st=new Stack<>(); + System.out.println(stack.size()); + reverse(stack); + while (!stack.isEmpty()) { + System.out.print(stack.pop()+" "); + } + } + public static void func(int i,Stack st){ + if(i<=0) return; + st.push(i); + func(i-1, st); + } + public static void reverse(Stack st){ + if(st.isEmpty()) return; + int a=st.pop(); + reverse(st); + // st.insertElementAt(a,0); + bottom(st,a); + } + public static void bottom(Stack st,int a){ + if (st.isEmpty()) { + st.push(a); + return; + } + int i=st.pop(); + bottom(st, a); + st.push(i); + } +} \ No newline at end of file From 64e6bf037c05023b14a3e595f005e15016eb4423 Mon Sep 17 00:00:00 2001 From: shivaagaur00 Date: Thu, 14 Nov 2024 20:50:42 +0530 Subject: [PATCH 5/5] more que 11/14/2024 --- CoinChange.java | 17 ++++++++++++ CounttheNumberofFairPairs.java | 49 ++++++++++++++++++++++++++++++++++ Factorial.java | 2 +- NaturalSum.java | 2 +- Nthfibonacii.java | 1 - PowerOf2.java | 2 +- Solution.java | 2 +- Stopwatch.java | 2 +- binarySearch.java | 1 - code1.java | 1 - code4.java | 1 - code5.java | 1 - countElementMaximumSum.java | 2 +- lemonadeChange.java | 2 +- listpair.java | 2 +- searchRange.java | 1 - 16 files changed, 74 insertions(+), 14 deletions(-) create mode 100644 CoinChange.java create mode 100644 CounttheNumberofFairPairs.java diff --git a/CoinChange.java b/CoinChange.java new file mode 100644 index 00000000..1af1897b --- /dev/null +++ b/CoinChange.java @@ -0,0 +1,17 @@ +import java.util.Arrays; + +public class CoinChange { + public int coinChange(int[] coins, int amount) { + int[] dp=new int[amount+1]; + Arrays.fill(dp,amount+1); + dp[0]=0; + for(int i=1;i<=amount;i++){ + for(int j=0;jamount?-1:dp[amount]; + } +} diff --git a/CounttheNumberofFairPairs.java b/CounttheNumberofFairPairs.java new file mode 100644 index 00000000..d3e2d11d --- /dev/null +++ b/CounttheNumberofFairPairs.java @@ -0,0 +1,49 @@ +import java.util.Arrays; + +public class CounttheNumberofFairPairs { + public int left(int nums[], int tar){ + int i =0; + int j = nums.length-1; + int res = -1; + while(i<=j){ + int mid = (i+j)/2; + if(nums[mid]>=tar){ + res = mid; + j = mid-1; + }else i = mid+1; + } + return res; + } + public int right(int nums[], int tar){ + int i =0; + int j = nums.length-1; + int res = -1; + while(i<=j){ + int mid = (i+j)/2; + if(nums[mid]<=tar){ + res = mid; + i = mid+1; + }else j = mid-1; + } + return res; + } + public int solve(int nums[], int l, int r, int i){ + int left = left(nums,l-nums[i]); + if(left==-1) return 0; + int right = right(nums,r-nums[i]); + if(right==-1) return 0; + int diff = (right-left+1); + if(left<=i && right>=i) diff--; + return diff; + + } + public long countFairPairs(int[] nums, int lower, int upper) { + Arrays.sort(nums); + long res= 0; + for(int i=0; i