diff --git a/dsa-solutions/lc-solutions/0000-0099/0001-two-sum.md b/dsa-solutions/lc-solutions/0000-0099/0001-two-sum.md index d2a11bb87..7ae6a93c4 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0001-two-sum.md +++ b/dsa-solutions/lc-solutions/0000-0099/0001-two-sum.md @@ -11,6 +11,7 @@ tags: - JavaScript - TypeScript description: "This is a solution to the Two Sum problem on LeetCode." +sidebar_position: 1 --- In this page, we will solve the Two Sum problem using three different approaches: brute force, hash table, and two-pointer technique. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. diff --git a/dsa-solutions/lc-solutions/0000-0099/0002-Add-Two-Numbers.md b/dsa-solutions/lc-solutions/0000-0099/0002-Add-Two-Numbers.md index cb2ce6fa3..f0af26209 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0002-Add-Two-Numbers.md +++ b/dsa-solutions/lc-solutions/0000-0099/0002-Add-Two-Numbers.md @@ -9,6 +9,7 @@ tags: - Add Two Numbers - LeetCode description: "This is a solution to the Add Two Numbers problem on LeetCode." +sidebar_position: 2 --- In this page, we will solve the Add Two Numbers problem. We will provide an overview of the problem, the intuition and approach to solve it, the implementation, and the code in various languages, along with a detailed explanation of the solution and its complexity analysis. Let's start by understanding the problem. diff --git a/dsa-solutions/lc-solutions/0000-0099/0003-Longest-Substring-Without-Repeating-Characters.md b/dsa-solutions/lc-solutions/0000-0099/0003-Longest-Substring-Without-Repeating-Characters.md index 1ee5bfa85..720031da1 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0003-Longest-Substring-Without-Repeating-Characters.md +++ b/dsa-solutions/lc-solutions/0000-0099/0003-Longest-Substring-Without-Repeating-Characters.md @@ -7,6 +7,7 @@ tags: - String - Sliding Window description: "This is a solution to the Longest Substring Without Repeating Characters problem on LeetCode." +sidebar_position: 3 --- In this page we will solve the problem [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) from LeetCode. diff --git a/dsa-solutions/lc-solutions/0000-0099/0004-Median-of-two-Sorted-Array.md b/dsa-solutions/lc-solutions/0000-0099/0004-Median-of-two-Sorted-Array.md index 4c3e85bb2..fe53f225e 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0004-Median-of-two-Sorted-Array.md +++ b/dsa-solutions/lc-solutions/0000-0099/0004-Median-of-two-Sorted-Array.md @@ -7,7 +7,8 @@ tags: - Binary Search - Divide and Conquer0 - LeetCode -description: Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be $O(log (m+n))$. +description: Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. +sidebar_position: 4 --- In this page, we will solve the problem [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/description/) from LeetCode. We will provide multiple approaches to solve the problem along with the code implementation and the complexity analysis of the code. diff --git a/dsa-solutions/lc-solutions/0000-0099/0005-Longest-palindrome-substring.md b/dsa-solutions/lc-solutions/0000-0099/0005-Longest-palindrome-substring.md index f4f974d63..bf4c44a24 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0005-Longest-palindrome-substring.md +++ b/dsa-solutions/lc-solutions/0000-0099/0005-Longest-palindrome-substring.md @@ -1,19 +1,14 @@ --- id: Longest Palindromic Substring title: Longest Palindromic Substring(LeetCode) -sidebar_label: 0005-Longest Palindrome Substring -tags: - - String - - Dynamic Programming +sidebar_label: 0005-Longest Palindrome Substring +tags: + - String + - Dynamic Programming description: Given a string s, return the longest palindromic substring in s. +sidebar_position: 5 --- -## Problem Description - -| Problem Statement | Solution Link | LeetCode Profile | -| :-------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------- | -| [Longest Palindromic Substring on LeetCode](https://leetcode.com/problems/longest-palindromic-substring/description/) | [Longest Palindromic Substring Solution on LeetCode](https://leetcode.com/problems/longest-palindromic-substring/editorial/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | - ## Problem Statement Given a string `s`, return the longest palindromic substring in `s`. @@ -21,6 +16,7 @@ Given a string `s`, return the longest palindromic substring in `s`. ### Examples **Example 1:** + ```plaintext Input: s = "babad" Output: "bab" @@ -28,12 +24,14 @@ Explanation: "aba" is also a valid answer. ``` **Example 2:** + ```plaintext Input: s = "cbbd" Output: "bb" ``` ### Constraints + - `1 <= s.length <= 1000` - `s` consist of only digits and English letters. @@ -42,9 +40,11 @@ Output: "bb" ### Approach 1: Check All Substrings #### Intuition + We can start with a brute-force approach. We will simply check if each substring is a palindrome, and take the longest one that is. #### Algorithm + 1. Create a helper method `check(i, j)` to determine if a substring is a palindrome. 2. Use two pointers to iterate from the start and end of the substring towards the center. 3. If characters at both pointers are equal, move the pointers inward. @@ -52,6 +52,7 @@ We can start with a brute-force approach. We will simply check if each substring 5. Keep track of the longest palindrome found. #### Implementation + ```python def longestPalindrome(s: str) -> str: def check(l, r): @@ -59,26 +60,29 @@ def longestPalindrome(s: str) -> str: l -= 1 r += 1 return s[l+1:r] - + longest = "" for i in range(len(s)): odd_palindrome = check(i, i) even_palindrome = check(i, i + 1) longest = max(longest, odd_palindrome, even_palindrome, key=len) - + return longest ``` ### Complexity Analysis + - **Time complexity**: $O(n^3)$ - We check each substring, and checking each substring takes $O(n)$ time. - **Space complexity**: $O(1)$ - We use a constant amount of extra space. ### Approach 2: Dynamic Programming #### Intuition + If we know a substring is a palindrome, we can extend it if the characters on both ends match. #### Algorithm + 1. Initialize a 2D DP table with `False`. 2. Mark all single-character substrings as palindromes. 3. Check substrings of length 2 and mark them if characters match. @@ -86,46 +90,51 @@ If we know a substring is a palindrome, we can extend it if the characters on bo 5. Keep track of the longest palindrome found. #### Implementation + ```python def longestPalindrome(s: str) -> str: n = len(s) dp = [[False] * n for _ in range(n)] longest = "" - + for i in range(n): dp[i][i] = True longest = s[i] - + for i in range(n-1): if s[i] == s[i+1]: dp[i][i+1] = True longest = s[i:i+2] - + for length in range(3, n+1): for i in range(n-length+1): j = i + length - 1 if s[i] == s[j] and dp[i+1][j-1]: dp[i][j] = True longest = s[i:j+1] - + return longest ``` ### Complexity Analysis + - **Time complexity**: $O(n^2)$ - We fill an `n * n` table. - **Space complexity**: $O(n^2)$ - We use an `n * n` table to store the DP results. ### Approach 3: Expand From Centers #### Intuition + A palindrome mirrors around its center. We can expand around potential centers to find palindromes. #### Algorithm + 1. Consider each character and pair of characters as potential centers. 2. Expand around each center to find the longest palindrome. 3. Keep track of the longest palindrome found. #### Implementation + ```python def longestPalindrome(s: str) -> str: def expandAroundCenter(s, left, right): @@ -133,62 +142,70 @@ def longestPalindrome(s: str) -> str: left -= 1 right += 1 return s[left + 1:right] - + if not s: return "" - + longest = s[0] - + for i in range(len(s)): odd_palindrome = expandAroundCenter(s, i, i) even_palindrome = expandAroundCenter(s, i, i + 1) longest = max(longest, odd_palindrome, even_palindrome, key=len) - + return longest ``` ### Complexity Analysis -- **Time complexity**: $O(n^2)$ - We expand around each center, which takes $O(n)$ time. + +- **Time complexity**: $O(n^2)$ - We expand around each center, which takes $O(n)$ time. - **Space complexity**: $O(1)$ - We use a constant amount of extra space. ### Approach 4: Manacher's Algorithm #### Intuition + Manacher's algorithm can find the longest palindromic substring in linear time. #### Algorithm + 1. Transform the string to handle even-length palindromes. 2. Use a helper array to store the length of the palindrome at each position. 3. Use the properties of palindromes and the helper array to efficiently find the longest palindrome. #### Implementation + ```python def longestPalindrome(s: str) -> str: if not s: return "" - + # Transform s into new string with inserted boundaries T = '#'.join(f"^{s}$") n = len(T) P = [0] * n C = R = 0 - + for i in range(1, n - 1): P[i] = (R > i) and min(R - i, P[2 * C - i]) while T[i + P[i] + 1] == T[i - P[i] - 1]: P[i] += 1 if i + P[i] > R: C, R = i, i + P[i] - + max_len, center_index = max((n, i) for i, n in enumerate(P)) return s[(center_index - max_len) // 2: (center_index + max_len) // 2] ``` ### Complexity Analysis + - **Time complexity**: $O(n)$ - Manacher's algorithm runs in linear time. - **Space complexity**: $O(n)$ - We use an array of length `n` to store the lengths of palindromes. ### Conclusion + We discussed four approaches to solve the "Longest Palindromic Substring" problem, each with varying complexities and trade-offs. The dynamic programming and center expansion approaches provide a good balance of simplicity and efficiency for practical use cases, while Manacher's algorithm offers the optimal theoretical performance. + ``` +``` diff --git a/dsa-solutions/lc-solutions/0000-0099/0006-ZigZag-Conversion.md b/dsa-solutions/lc-solutions/0000-0099/0006-ZigZag-Conversion.md index dabeb24d3..e8d186237 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0006-ZigZag-Conversion.md +++ b/dsa-solutions/lc-solutions/0000-0099/0006-ZigZag-Conversion.md @@ -2,26 +2,21 @@ id: Zigzag Conversion title: Zigzag Conversion (LeetCode) sidebar_label: 0006-Zigzag Conversion -tags: - - String +tags: + - String description: Convert the given string into a zigzag pattern with a specified number of rows. +sidebar_position: 6 --- -## Problem Description - -| Problem Statement | Solution Link | LeetCode Profile | -| :----------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------- | -| [Zigzag Conversion on LeetCode](https://leetcode.com/problems/zigzag-conversion) | [Median of Two Sorted Arrays Solution on LeetCode Solution on LeetCode](https://leetcode.com/problems/zigzag-conversion/solutions/3133966/easy-explanation-with-pics-and-video-java-c-python/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | - - ## Problem Statement The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: -``` +```plaintext P A H N A P L S I I G Y I R + ``` And then read line by line: "PAHNAPLSIIGYIR" @@ -36,26 +31,34 @@ string convert(string s, int numRows) **Example 1:** -Input: +Input: + ``` s = "PAYPALISHIRING", numRows = 3 ``` -Output: + +Output: + ``` "PAHNAPLSIIGYIR" ``` **Example 2:** -Input: +Input: + ``` s = "PAYPALISHIRING", numRows = 4 ``` -Output: + +Output: + ``` "PINALSIGYAHRPI" ``` + Explanation: + ``` P I N A L S I G @@ -65,11 +68,14 @@ P I **Example 3:** -Input: +Input: + ``` s = "A", numRows = 1 ``` -Output: + +Output: + ``` "A" ``` @@ -87,18 +93,18 @@ Just look at the top row what is the difference between each character, i.e., A The interesting part comes when the character in the diagonal has to be added, but even this has a pattern: - There will be no character in between for row 0 and row n. -- There can be only one diagonal character, and the diagonal difference is original difference - 2 at each step or diff - (rowNumber*2); +- There can be only one diagonal character, and the diagonal difference is original difference - 2 at each step or diff - (rowNumber\*2); ## Approach 1. Create an empty StringBuilder which is our answer. -2. Calculate the difference = numRows*2 - 2. +2. Calculate the difference = numRows\*2 - 2. 3. Iterate over 0 to rowNumber in a for loop. 4. The first character will be row number or i (append to String). 5. Write a while loop in the above for loop: - - The first character will be row number or i (append to String). - - Calculate the diagonal difference if any and append to the String. - - Increase the index by diff and return ans. + - The first character will be row number or i (append to String). + - Calculate the diagonal difference if any and append to the String. + - Increase the index by diff and return ans. ### Java Solution @@ -108,7 +114,7 @@ class Solution { if (numRows == 1) { return s; } - + StringBuilder answer = new StringBuilder(); int n = s.length(); int diff = 2 * (numRows - 1); @@ -123,7 +129,7 @@ class Solution { if (i != 0 && i != numRows - 1) { diagonalDiff = diff-2*i; secondIndex = index + diagonalDiff; - + if (secondIndex < n) { answer.append(s.charAt(secondIndex)); } @@ -131,7 +137,7 @@ class Solution { index += diff; } } - + return answer.toString(); } } @@ -146,7 +152,7 @@ public: if (numRows == 1) { return s; } - + stringstream answer; int n = s.length(); int diff = 2 * (numRows - 1); @@ -161,7 +167,7 @@ public: if (i != 0 && i != numRows - 1) { diagonalDiff = diff-2*i; secondIndex = index + diagonalDiff; - + if (secondIndex < n) { answer << s[secondIndex]; } @@ -169,7 +175,7 @@ public: index += diff; } } - + return answer.str(); } }; @@ -200,6 +206,7 @@ class Solution: index += diff return answer ``` + ### Complexity Analysis #### Approach 1: Iterative Approach diff --git a/dsa-solutions/lc-solutions/0000-0099/0007-Reverse-Integers.md b/dsa-solutions/lc-solutions/0000-0099/0007-Reverse-Integers.md index c7f074cbd..94ab9ff6a 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0007-Reverse-Integers.md +++ b/dsa-solutions/lc-solutions/0000-0099/0007-Reverse-Integers.md @@ -6,14 +6,9 @@ tags: - Math - Simulation description: Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0. +sidebar_position: 7 --- -## Problem Description - -| Problem Statement | Solution Link | LeetCode Profile | -| :--------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------- | -| [Reverse Integer on LeetCode](https://leetcode.com/problems/reverse-integer/description/) | [Reverse Integer Solution on LeetCode](https://leetcode.com/problems/reverse-integer/editorial/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | - ## Problem Statement Given a signed 32-bit integer `x`, return `x` with its digits reversed. If reversing `x` causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0. diff --git a/dsa-solutions/lc-solutions/0000-0099/0008-String-to-Integer.md b/dsa-solutions/lc-solutions/0000-0099/0008-String-to-Integer.md index 3da8437b9..d5d623059 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0008-String-to-Integer.md +++ b/dsa-solutions/lc-solutions/0000-0099/0008-String-to-Integer.md @@ -6,13 +6,9 @@ tags: - String - Math description: Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. +sidebar_position: 8 --- -## Problem Description - -| Problem Statement | Solution Link | LeetCode Profile | -| :--------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------- | -| [String to Integer](https://leetcode.com/problems/string-to-integer-atoi/description/) | [String to Integer Solution on LeetCode](https://leetcode.com/problems/string-to-integer-atoi/solutions/5034425/beats-100-most-in-depth-step-wise-explanation/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | ## Problem Statement Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer. diff --git a/dsa-solutions/lc-solutions/0000-0099/0009-Palindrome-number.md b/dsa-solutions/lc-solutions/0000-0099/0009-Palindrome-number.md index 908decfd9..96f788651 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0009-Palindrome-number.md +++ b/dsa-solutions/lc-solutions/0000-0099/0009-Palindrome-number.md @@ -6,12 +6,8 @@ tags: - Math - Palindrome description: Given an integer x, return true if x is a palindrome, and false otherwise. +sidebar_position: 9 --- -## Problem Description - -| Problem Statement | Solution Link | LeetCode Profile | -| :--------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------- | -| [Palindrome Number](https://leetcode.com/problems/palindrome-number/description/) | [palindrome Number Solution on LeetCode](https://leetcode.com/problems/palindrome-number/solutions/3651712/2-method-s-c-java-python-beginner-friendly/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | ## Problem Statement diff --git a/dsa-solutions/lc-solutions/0000-0099/0010-Regular-Expression-Matching.md b/dsa-solutions/lc-solutions/0000-0099/0010-Regular-Expression-Matching.md index 2506577d2..f4053dd91 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0010-Regular-Expression-Matching.md +++ b/dsa-solutions/lc-solutions/0000-0099/0010-Regular-Expression-Matching.md @@ -7,6 +7,7 @@ tags: - Dynamic Programming - Recursion description: Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where '.' matches any single character and '*' matches zero or more of the preceding element. +sidebar_position: 10 --- ## Problem Description diff --git a/dsa-solutions/lc-solutions/0000-0099/0011-Container-with-most-water.md b/dsa-solutions/lc-solutions/0000-0099/0011-Container-with-most-water.md index f279e4ff9..6acf87fc5 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0011-Container-with-most-water.md +++ b/dsa-solutions/lc-solutions/0000-0099/0011-Container-with-most-water.md @@ -7,6 +7,7 @@ tags: - Two Pointers - Greedy description: Given n non-negative integers representing the heights of vertical lines, find the two lines that together with the x-axis form a container, such that the container contains the most water. +sidebar_position: 11 --- ## Problem Description diff --git a/dsa-solutions/lc-solutions/0000-0099/0012-integer-to-roman.md b/dsa-solutions/lc-solutions/0000-0099/0012-integer-to-roman.md index c4c0ae770..c4b0c999d 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0012-integer-to-roman.md +++ b/dsa-solutions/lc-solutions/0000-0099/0012-integer-to-roman.md @@ -7,14 +7,9 @@ tags: - Math - String description: Convert a given integer to a Roman numeral using specific rules for the Roman numeral system. +sidebar_position: 12 --- -## Problem Description - -| Problem Statement | Solution Link | LeetCode Profile | -| :----------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------- | -| [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [Integer to Roman Solution on LeetCode](https://leetcode.com/problems/integer-to-roman/solutions/3216797/easiest-beginner-friendly-sol-c-java-python/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | - ## Problem Statement Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D`, and `M`. diff --git a/dsa-solutions/lc-solutions/0000-0099/0013-roman-to-integer.md b/dsa-solutions/lc-solutions/0000-0099/0013-roman-to-integer.md index 4bb6f853c..0619199ec 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0013-roman-to-integer.md +++ b/dsa-solutions/lc-solutions/0000-0099/0013-roman-to-integer.md @@ -7,14 +7,9 @@ tags: - Math - String description: Convert a given Roman numeral to an integer using specific rules for the Roman numeral system. +sidebar_position: 13 --- -## Problem Description - -| Problem Statement | Solution Link | LeetCode Profile | -| :----------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------- | -| [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [Roman to Integer Solution on LeetCode](https://leetcode.com/problems/roman-to-integer/solutions/5034425/beats-100-most-in-depth-step-wise-explanation/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | - ## Problem Statement Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D`, and `M`. diff --git a/dsa-solutions/lc-solutions/0000-0099/0014-longest-comman-prefix.md b/dsa-solutions/lc-solutions/0000-0099/0014-longest-comman-prefix.md index 2fe00b0cd..3bfd0e772 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0014-longest-comman-prefix.md +++ b/dsa-solutions/lc-solutions/0000-0099/0014-longest-comman-prefix.md @@ -6,16 +6,11 @@ tags: - Hash Table - Math - String -description: finds logest comman prefix for a given string . +description: finds logest comman prefix for a given string. +sidebar_position: 14 --- -## Problem Description - -| Problem Statement | Solution Link | LeetCode Profile | -| :----------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------- | -| [Longest Comman Prefix](https://leetcode.com/problems/longest-common-prefix/) | [Longest Comman Prefix Solution on LeetCode](https://leetcode.com/problems/longest-common-prefix/editorial/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | - -### Problem Statement +## Problem Statement Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". @@ -30,15 +25,15 @@ Write a function to find the longest common prefix string amongst an array of st - Output: `""` - Explanation: There is no common prefix among the input strings. -#### Constraints: +### Constraints: - `1 <= strs.length <= 200` - `0 <= strs[i].length <= 200` - `strs[i]` consists of only lowercase English letters. -### Approaches and Solutions +## Approaches and Solutions -#### Approach 1: Horizontal Scanning +### Approach 1: Horizontal Scanning **Intuition:** Iteratively find the longest common prefix (LCP) of the first two strings, then find the LCP of the result with the next string, and so on. @@ -103,7 +98,7 @@ class Solution: return prefix ``` -#### Approach 2: Vertical Scanning +### Approach 2: Vertical Scanning **Intuition:** Compare characters from top to bottom on the same column (i.e., same character index across all strings) before moving on to the next column. @@ -166,7 +161,7 @@ class Solution: return strs[0] ``` -#### Approach 3: Divide and Conquer +### Approach 3: Divide and Conquer **Intuition:** Use the divide and conquer technique, where the problem is divided into two subproblems, find their LCP, and then combine their results. @@ -266,6 +261,6 @@ class Solution: return divide_and_conquer(strs, 0, len(strs) - 1) ``` -### Conclusion +## Conclusion We've discussed three different approaches to solving the problem of finding the longest common prefix among an array of strings. Each approach has its own merits, and the choice of which to use depends on the specific requirements and constraints of the problem. The provided implementations in C++, Java, and Python cover horizontal scanning, vertical scanning, and divide and conquer methods. \ No newline at end of file diff --git a/dsa-solutions/lc-solutions/0000-0099/0015-3sum.md b/dsa-solutions/lc-solutions/0000-0099/0015-3sum.md index 1b20e5202..8a6259414 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0015-3sum.md +++ b/dsa-solutions/lc-solutions/0000-0099/0015-3sum.md @@ -3,27 +3,20 @@ id: 3Sum title: 3Sum (LeetCode) sidebar_label: 0015-3Sum tags: - - Hash Table - - Math - - String + - Hash Table + - Math + - String description: find the number of triplets with given sum . +sidebar_position: 15 --- ## Problem Description -| Problem Statement | Solution Link | LeetCode Profile | -| :----------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------- | -| [3Sum](https://leetcode.com/problems/3sum/) | [3Sum Solution on LeetCode](https://leetcode.com/problems/3sum/solutions/5055810/video-two-pointer-solution/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | - -### Problem Description - Given an integer array `nums`, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`. Notice that the solution set must not contain duplicate triplets. -### Examples - -#### Example 1 +### Example 1 - **Input:** `nums = [-1,0,1,2,-1,-4]` - **Output:** `[[-1,-1,2],[-1,0,1]]` @@ -34,13 +27,13 @@ Notice that the solution set must not contain duplicate triplets. - The distinct triplets are `[-1,0,1]` and `[-1,-1,2]`. - Notice that the order of the output and the order of the triplets does not matter. -#### Example 2 +### Example 2 - **Input:** `nums = [0,1,1]` - **Output:** `[]` - **Explanation:** The only possible triplet does not sum up to 0. -#### Example 3 +### Example 3 - **Input:** `nums = [0,0,0]` - **Output:** `[[0,0,0]]` @@ -51,21 +44,25 @@ Notice that the solution set must not contain duplicate triplets. - `3 <= nums.length <= 3000` - `-10^5 <= nums[i] <= 10^5` -### Approach +## Approach To solve the problem, we can use the two-pointer technique combined with sorting. Here is the step-by-step approach: 1. **Sort the Input Array:** + - Sort the array to enable the two-pointer technique and to handle duplicates easily. 2. **Iterate Through the Array:** + - Use a loop to fix the first element (`i`). - Use two pointers (`j` starting from `i + 1` and `k` starting from the end of the array) to find pairs that, along with the element at `i`, sum to zero. 3. **Avoid Duplicates:** + - Skip duplicate elements to avoid duplicate triplets. 4. **Calculate and Adjust Pointers:** + - Calculate the sum of the elements at `i`, `j`, and `k`. - If the sum is zero, add the triplet to the result and move both pointers. - If the sum is greater than zero, move the `k` pointer left to reduce the sum. @@ -87,7 +84,7 @@ class Solution: for i in range(len(nums)): if i > 0 and nums[i] == nums[i-1]: continue - + j = i + 1 k = len(nums) - 1 @@ -104,43 +101,43 @@ class Solution: while j < k and nums[j] == nums[j-1]: j += 1 - + return res ``` #### JavaScript ```javascript -var threeSum = function(nums) { - let res = []; - nums.sort((a, b) => a - b); +var threeSum = function (nums) { + let res = []; + nums.sort((a, b) => a - b); - for (let i = 0; i < nums.length; i++) { - if (i > 0 && nums[i] === nums[i-1]) { - continue; - } - - let j = i + 1; - let k = nums.length - 1; - - while (j < k) { - let total = nums[i] + nums[j] + nums[k]; - - if (total > 0) { - k--; - } else if (total < 0) { - j++; - } else { - res.push([nums[i], nums[j], nums[k]]); - j++; - - while (j < k && nums[j] === nums[j-1]) { - j++; - } - } + for (let i = 0; i < nums.length; i++) { + if (i > 0 && nums[i] === nums[i - 1]) { + continue; + } + + let j = i + 1; + let k = nums.length - 1; + + while (j < k) { + let total = nums[i] + nums[j] + nums[k]; + + if (total > 0) { + k--; + } else if (total < 0) { + j++; + } else { + res.push([nums[i], nums[j], nums[k]]); + j++; + + while (j < k && nums[j] === nums[j - 1]) { + j++; } + } } - return res; + } + return res; }; ``` @@ -160,7 +157,7 @@ class Solution { if (i > 0 && nums[i] == nums[i-1]) { continue; } - + int j = i + 1; int k = nums.length - 1; @@ -181,7 +178,7 @@ class Solution { } } } - return res; + return res; } } ``` @@ -204,7 +201,7 @@ public: if (i > 0 && nums[i] == nums[i-1]) { continue; } - + int j = i + 1; int k = nums.size() - 1; @@ -225,7 +222,7 @@ public: } } } - return res; + return res; } }; ``` @@ -233,61 +230,81 @@ public: ### Step-by-Step Algorithm 1. **Initialize Result List:** + - Create an empty list `res` to store the triplets whose sum is zero. + ```python res = [] ``` 2. **Sort the Input Array:** + - Sort the input array `nums` in non-decreasing order. + ```python nums.sort() ``` 3. **Iterate Through the Array:** + - Iterate through each element in the sorted array `nums`. + ```python for i in range(len(nums)): ``` 4. **Skip Duplicate Elements:** + - Check if the current element is a duplicate of the previous element and skip it if it is. + ```python if i > 0 and nums[i] == nums[i-1]: continue ``` 5. **Initialize Pointers:** + - Initialize two pointers `j` and `k` to point to the elements next to the current element `i` and at the end of the array, respectively. + ```python j = i + 1 k = len(nums) - 1 ``` 6. **Two-Pointer Approach:** + - Use a two-pointer approach with pointers `j` and `k` to find triplets whose sum equals zero. + ```python while j < k: ``` 7. **Calculate Total:** + - Calculate the total sum of the current triplet. + ```python total = nums[i] + nums[j] + nums[k] ``` 8. **Adjust Pointers Based on Total:** + - If the total sum is greater than zero, decrement the `k` pointer to decrease the total sum. + ```python if total > 0: k -= 1 ``` + - If the total sum is less than zero, increment the `j` pointer to increase the total sum. + ```python elif total < 0: j += 1 ``` + - If the total sum equals zero, add the triplet `[nums[i], nums[j], nums[k]]` to the result list `res`. + ```python else: res.append([nums[i], nums[j], nums[k]]) @@ -295,7 +312,9 @@ public: ``` 9. **Handle Duplicate Triplets:** + - Increment the `j` pointer to skip any duplicate elements. + ```python while j < k and nums[j] == nums[j-1]: j += 1 diff --git a/dsa-solutions/lc-solutions/0000-0099/0016-3sum-closest.md b/dsa-solutions/lc-solutions/0000-0099/0016-3sum-closest.md index 822194ce6..bf2207908 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0016-3sum-closest.md +++ b/dsa-solutions/lc-solutions/0000-0099/0016-3sum-closest.md @@ -3,52 +3,51 @@ id: 3Sum Closest title: 3Sum losest (LeetCode) sidebar_label: 0016-3Sum Closest tags: - - Array - - two pointers - - Sorting -description: Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.. + - Array + - two pointers + - Sorting +description: Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. +sidebar_position: 16 --- ## Problem Description -| Problem Statement | Solution Link | LeetCode Profile | -| :----------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------- | -| [3Sum](https://leetcode.com/problems/3sum-closest/) | [3Sum Solution on LeetCode](https://leetcode.com/problems/3sum-closest/solutions/5001229/simple-java-binary-search/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | - -### Problem Description - Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`. Return the sum of the three integers. You may assume that each input would have exactly one solution. -### Examples +### Example 1 -#### Example 1 - **Input:** `nums = [-1,2,1,-4]`, `target = 1` - **Output:** `2` - **Explanation:** The sum that is closest to the target is `2` (`-1 + 2 + 1 = 2`). -#### Example 2 +### Example 2 + - **Input:** `nums = [0,0,0]`, `target = 1` - **Output:** `0` - **Explanation:** The sum that is closest to the target is `0` (`0 + 0 + 0 = 0`). ### Constraints + - `3 <= nums.length <= 500` - `-1000 <= nums[i] <= 1000` - `-10^4 <= target <= 10^4` ### Topics + - Array - Two Pointers - Sorting ### Intuition + - Sorting combined with the two-pointer technique. ### Complexity + - **Time Complexity:** $O(N \log N + N^2)$ approx $O(N^2)$ - **Space Complexity:** $(O(1))$ @@ -173,17 +172,22 @@ class Solution: ### Explanation 1. **Sort the Array:** + - The array `nums` is sorted to facilitate the two-pointer technique. + ```python nums.sort() ``` 2. **Initialize Variables:** + - `mindiff` is initialized to infinity to keep track of the minimum difference found. - `ans` is initialized to 0 to store the closest sum. 3. **Iterate Through the Array:** + - For each element `nums[i]`, use two pointers `j` and `k` to find the other two elements. + ```python for i in range(n): j = i + 1 @@ -191,11 +195,13 @@ class Solution: ``` 4. **Two-Pointer Approach:** + - Calculate the sum of `nums[i]`, `nums[j]`, and `nums[k]`. - If the sum equals the target, return the target immediately. - If the sum does not equal the target, calculate the difference between the target and the sum. - If the difference is less than `mindiff`, update `mindiff` and `ans`. - Adjust the pointers `j` and `k` based on whether the sum is less than or greater than the target. + ```python while j < k: sum_val = nums[i] + nums[j] + nums[k] @@ -223,4 +229,4 @@ class Solution: ### Conclusion -The above solution efficiently finds the sum of three integers in the array `nums` that is closest to the given `target`. It employs a combination of sorting and the two-pointer technique to achieve a time complexity of $(O(N^2))$ and a space complexity of $(O(1))$. This ensures that the algorithm can handle input sizes up to the upper limit specified in the constraints efficiently. \ No newline at end of file +The above solution efficiently finds the sum of three integers in the array `nums` that is closest to the given `target`. It employs a combination of sorting and the two-pointer technique to achieve a time complexity of $(O(N^2))$ and a space complexity of $(O(1))$. This ensures that the algorithm can handle input sizes up to the upper limit specified in the constraints efficiently. diff --git a/dsa-solutions/lc-solutions/0000-0099/0017-letter-combinations-of-a-phone-number.md b/dsa-solutions/lc-solutions/0000-0099/0017-letter-combinations-of-a-phone-number.md index 890c371f1..90b0bd8a5 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0017-letter-combinations-of-a-phone-number.md +++ b/dsa-solutions/lc-solutions/0000-0099/0017-letter-combinations-of-a-phone-number.md @@ -3,21 +3,23 @@ id: letter-combinations-of-a-phone-number title: Letter Combinations of a Phone Number (LeetCode) sidebar_label: 0017 Letter Combinations of a Phone Number tags: - - Back Tracking - - Mapping - - String + - Back Tracking + - Mapping + - String description: The problem requires generating all letter combinations corresponding to given digits (2-9). The solution utilizes backtracking to explore all combinations efficiently, employing a recursive approach in Java. +sidebar_position: 17 --- ## Problem Description -| Problem Statement | Solution Link | LeetCode Profile | -| :----------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------- | -| [Letter Combinations of a Phone Number](https://leetcode.com/problems/Letter Combinations of a Phone Number/) | [Letter Combinations of a Phone Number Solution on LeetCode](https://leetcode.com/problems/Letter Combinations of a Phone Number/solutions/5055810/video-two-pointer-solution/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :----------------------------------------------------- | +| [Letter Combinations of a Phone Number](https://leetcode.com/problems/Letter Combinations of a Phone Number/) | [Letter Combinations of a Phone Number Solution on LeetCode](https://leetcode.com/problems/Letter Combinations of a Phone Number/solutions/5055810/video-two-pointer-solution/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | ### Problem Description ## Problem Statement: + Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. ### Examples @@ -32,7 +34,6 @@ Given a string containing digits from 2-9 inclusive, return all possible letter - **Input:** `digits = ""` - **Output:** `[]` - #### Example 3 - **Input:** `2` @@ -48,9 +49,11 @@ Given a string containing digits from 2-9 inclusive, return all possible letter ### Approach 1. **Mapping Digits to Letters:** + - Define a mapping of digits to their corresponding letters, similar to telephone buttons. 2. **Backtracking Function:** + - Define a recursive backtracking function to generate all possible combinations. - The function takes four parameters: - `index`: The current index in the digits string. @@ -60,6 +63,7 @@ Given a string containing digits from 2-9 inclusive, return all possible letter - After the recursive call, we remove the last character from the combination (backtracking). 3. **Base Case:** + - If the length of the current combination is equal to the length of the input digits string, we add the combination to the result list. 4. **Main Function:** @@ -155,6 +159,7 @@ public class Solution { ``` #### CPP: + ```cpp #include #include @@ -210,40 +215,41 @@ int main() { ``` #### JavaScript + ```js /** * @param {string} digits * @return {string[]} */ -var letterCombinations = function(digits) { - if (digits.length === 0) return []; - - const digitToLetters = { - '2': 'abc', - '3': 'def', - '4': 'ghi', - '5': 'jkl', - '6': 'mno', - '7': 'pqrs', - '8': 'tuv', - '9': 'wxyz' - }; - - const combinations = []; - - const backtrack = (index, path) => { - if (index === digits.length) { - combinations.push(path); - return; - } - const letters = digitToLetters[digits.charAt(index)]; - for (let letter of letters) { - backtrack(index + 1, path + letter); - } - }; - - backtrack(0, ''); - return combinations; +var letterCombinations = function (digits) { + if (digits.length === 0) return []; + + const digitToLetters = { + 2: "abc", + 3: "def", + 4: "ghi", + 5: "jkl", + 6: "mno", + 7: "pqrs", + 8: "tuv", + 9: "wxyz", + }; + + const combinations = []; + + const backtrack = (index, path) => { + if (index === digits.length) { + combinations.push(path); + return; + } + const letters = digitToLetters[digits.charAt(index)]; + for (let letter of letters) { + backtrack(index + 1, path + letter); + } + }; + + backtrack(0, ""); + return combinations; }; // Example usage: @@ -251,39 +257,40 @@ console.log(letterCombinations("23")); // Output: ["ad","ae","af","bd","be","bf" ``` #### TypeScript + ```ts class Solution { - private digitToLetters: { [key: string]: string } = { - '2': 'abc', - '3': 'def', - '4': 'ghi', - '5': 'jkl', - '6': 'mno', - '7': 'pqrs', - '8': 'tuv', - '9': 'wxyz' + private digitToLetters: { [key: string]: string } = { + "2": "abc", + "3": "def", + "4": "ghi", + "5": "jkl", + "6": "mno", + "7": "pqrs", + "8": "tuv", + "9": "wxyz", + }; + + letterCombinations(digits: string): string[] { + const combinations: string[] = []; + + const backtrack = (index: number, path: string): void => { + if (index === digits.length) { + combinations.push(path); + return; + } + const letters = this.digitToLetters[digits.charAt(index)]; + for (let letter of letters) { + backtrack(index + 1, path + letter); + } }; - letterCombinations(digits: string): string[] { - const combinations: string[] = []; - - const backtrack = (index: number, path: string): void => { - if (index === digits.length) { - combinations.push(path); - return; - } - const letters = this.digitToLetters[digits.charAt(index)]; - for (let letter of letters) { - backtrack(index + 1, path + letter); - } - }; - - if (digits.length !== 0) { - backtrack(0, ''); - } - - return combinations; + if (digits.length !== 0) { + backtrack(0, ""); } + + return combinations; + } } // Example usage: @@ -296,9 +303,11 @@ console.log(solution.letterCombinations("23")); // Output: ["ad","ae","af","bd", Here's a step-by-step algorithm for generating all possible letter combinations of a given string of digits using backtracking: 1. **Define a mapping of digits to letters:** + - Create a map where each digit from 2 to 9 is mapped to its corresponding letters on a telephone keypad. 2. **Define a backtracking function:** + - The function will take the following parameters: - `index`: The current index in the digits string. - `path`: The current combination of letters. @@ -307,6 +316,7 @@ Here's a step-by-step algorithm for generating all possible letter combinations - After the recursive call, remove the last character from the combination (backtracking). 3. **Base Case:** + - If the length of the current combination is equal to the length of the input digits string, add the combination to the result list. 4. **Main Function:** @@ -314,4 +324,4 @@ Here's a step-by-step algorithm for generating all possible letter combinations - Call the backtracking function with the initial index set to 0 and an empty string as the initial combination. - Return the list of combinations. -This algorithm ensures that all possible combinations are generated by exploring all valid paths through backtracking. \ No newline at end of file +This algorithm ensures that all possible combinations are generated by exploring all valid paths through backtracking. diff --git a/dsa-solutions/lc-solutions/0000-0099/0018- FourSum.md b/dsa-solutions/lc-solutions/0000-0099/0018- FourSum.md deleted file mode 100644 index 096aafe43..000000000 --- a/dsa-solutions/lc-solutions/0000-0099/0018- FourSum.md +++ /dev/null @@ -1,161 +0,0 @@ ---- -id: FourSum -title: 4Sum (LeetCode) -sidebar_label: 0018-FourSum -tags: - - Two Pointers -description: "Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]]" ---- - -## Problem Description - -| Problem Statement | Solution Link | LeetCode Profile | -| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | -| [4Sum](https://leetcode.com/problems/4sum/description/) | [4Sum Solution on LeetCode](https://leetcode.com/problems/4sum/solutions/) | [Abhinash Singh](https://leetcode.com/u/singhabhinash/) | - -### Problem Description - -Given an array `nums` of `n` integers, return an array of all the unique quadruplets `[nums[a], nums[b], nums[c], nums[d]]` such that: - -- `0 <= a, b, c, d < n` -- `a, b, c, and d are distinct` -- `nums[a] + nums[b] + nums[c] + nums[d] == target` - -You may return the answer in any order. - -### Examples - -#### Example 1 - -- **Input:** `nums = [1,0,-1,0,-2,2], target = 0` -- **Output:** `[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]` - -#### Example 2 - -- **Input:** `nums = [2,2,2,2,2], target = 8` -- **Output:** `[[2,2,2,2]]` - -### Constraints - -- $1 <= nums.length <= 200$ -- $-10^9 <= nums[i] <= 10^9$ -- $-10^9 <= target <= 10^9$ - -### Approach - -To solve the problem, we can use the following approach: - -1. Sort the input array of integers `nums`. -2. Initialize an empty set `s`, and an empty list `output`. -3. Use nested loops to iterate through all possible combinations of quadruplets in `nums`. -4. For each combination, use two pointers (`k` and `l`) to traverse the sub-array between the second and second-to-last elements of the combination. -5. At each iteration of the innermost while loop, calculate the sum of the current quadruplet and check if it is equal to the target. -6. If the sum is equal to the target, insert the quadruplet into the set `s` and increment both pointers (`k` and `l`). -7. If the sum is less than the target, increment the pointer `k`. -8. If the sum is greater than the target, decrement the pointer `l`. -9. After all quadruplets have been checked, iterate through the set `s` and add each quadruplet to the `output` list. -10. Return the `output` list. - -### Solution Code - -#### Python - -```python -class Solution: - def fourSum(self, nums: List[int], target: int) -> List[List[int]]: - nums.sort() - s = set() - output = [] - for i in range(len(nums)): - for j in range(i + 1, len(nums)): - k = j + 1 - l = len(nums) - 1 - while k < l: - sum = nums[i] + nums[j] + nums[k] + nums[l] - if sum == target: - s.add((nums[i], nums[j], nums[k], nums[l])) - k += 1 - l -= 1 - elif sum < target: - k += 1 - else: - l -= 1 - output = list(s) - return output -``` - -#### C++ - -```cpp -class Solution { -public: - vector> fourSum(vector& nums, int target) { - sort(nums.begin(), nums.end()); - set> s; - vector> output; - for (int i = 0; i < nums.size(); i++) { - for(int j = i + 1; j < nums.size(); j++) { - int k = j + 1; - int l = nums.size() - 1; - while (k < l) { - long long sum = nums[i]; - sum += nums[j]; - sum += nums[k]; - sum += nums[l]; - if (sum == target) { - s.insert({nums[i], nums[j], nums[k], nums[l]}); - k++; - l--; - } else if (sum < target) { - k++; - } else { - l--; - } - } - } - } - for(auto quadruplets : s) - output.push_back(quadruplets); - return output; - } -}; -``` - -#### Java - -```java -class Solution { - public List> fourSum(int[] nums, int target) { - Arrays.sort(nums); - Set> s = new HashSet<>(); - List> output = new ArrayList<>(); - for (int i = 0; i < nums.length; i++) { - for (int j = i + 1; j < nums.length; j++) { - int k = j + 1; - int l = nums.length - 1; - while (k < l) { - long sum = nums[i]; - sum += nums[j]; - sum += nums[k]; - sum += nums[l]; - if (sum == target) { - s.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l])); - k++; - l--; - } else if (sum < target) { - k++; - } else { - l--; - } - } - } - } - output.addAll(s); - return output; - } -} -``` - -### Conclusion - -The given solution sorts the input list and uses a nested loop structure with two pointers to find all unique quadruplets that sum up to the target. By using a set to store the quadruplets, it ensures that duplicates are avoided. The solution efficiently narrows down potential combinations by adjusting the pointers based on the current sum relative to the target. This approach is effective for generating the required output while maintaining uniqueness. diff --git a/dsa-solutions/lc-solutions/0000-0099/0018-4Sum.md b/dsa-solutions/lc-solutions/0000-0099/0018-4Sum.md index 273a09179..b143c0150 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0018-4Sum.md +++ b/dsa-solutions/lc-solutions/0000-0099/0018-4Sum.md @@ -1,21 +1,15 @@ --- -id: FourSum +id: four-sum title: 4Sum (LeetCode) -sidebar_label: 0018-FourSum +sidebar_label: 0018-4Sum tags: - Two Pointers description: "Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]]" - +sidebar_position: 18 --- ## Problem Description -| Problem Statement | Solution Link | LeetCode Profile | -| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | -| [4Sum](https://leetcode.com/problems/4sum/description/) | [4Sum Solution on LeetCode](https://leetcode.com/problems/4sum/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | - -### Problem Description - Given an array `nums` of `n` integers, return an array of all the unique quadruplets `[nums[a], nums[b], nums[c], nums[d]]` such that: - `0 <= a, b, c, d < n` @@ -24,37 +18,37 @@ Given an array `nums` of `n` integers, return an array of all the unique quadrup You may return the answer in any order. -### Examples +### Example 1 -#### Example 1 - **Input:** `nums = [1,0,-1,0,-2,2], target = 0` - **Output:** `[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]` -#### Example 2 +### Example 2 + - **Input:** `nums = [2,2,2,2,2], target = 8` - **Output:** `[[2,2,2,2]]` ### Constraints -- $1 <= nums.length <= 200$ -- $-10^9 <= nums[i] <= 10^9$ -- $-10^9 <= target <= 10^9$ +- $1 \leq \text{nums.length} \leq 200$ +- $-10^9 \leq \text{nums[i]} \leq 10^9$ +- $-10^9 \leq \text{target} \leq 10^9$ ### Approach To solve the problem, we can use the following approach: -1: Sort the input array in non-decreasing order. -2: Traverse the array from 0 to n-3 and use a variable i to keep track of the first element in the quadruplet. -3: If the current element is the same as the previous element, skip it to avoid duplicates. -4: Traverse the array from i+1 to n-2 and use a variable j to keep track of the second element in the quadruplet. -5: If the current element is the same as the previous element, skip it to avoid duplicates. -6: Use two pointers, left = j+1 and right = n-1, to find the other two elements in the quadruplet whose sum equals the target value. -7: If the sum of the four elements is less than the target value, increment left pointer. -8: If the sum of the four elements is greater than the target value, decrement right pointer. -9: If the sum of the four elements is equal to the target value, add the quadruplet to the result and increment left and decrement right pointers. -10: Skip duplicate values of left and right pointers to avoid duplicate quadruplets. -11: Return the result. +1. Sort the input array in non-decreasing order. +2. Traverse the array from 0 to n-3 and use a variable i to keep track of the first element in the quadruplet. +3. If the current element is the same as the previous element, skip it to avoid duplicates. +4. Traverse the array from i+1 to n-2 and use a variable j to keep track of the second element in the quadruplet. +5. If the current element is the same as the previous element, skip it to avoid duplicates. +6. Use two pointers, left = j+1 and right = n-1, to find the other two elements in the quadruplet whose sum equals the target value. +7. If the sum of the four elements is less than the target value, increment left pointer. +8. If the sum of the four elements is greater than the target value, decrement right pointer. +9. If the sum of the four elements is equal to the target value, add the quadruplet to the result and increment left and decrement right pointers. +10. Skip duplicate values of left and right pointers to avoid duplicate quadruplets. +11. Return the result. ### Solution Code @@ -202,7 +196,9 @@ class Solution { } } ``` + #### Javascript + ``` var fourSum = function(nums, target) { nums.sort((a, b) => a - b); @@ -241,6 +237,7 @@ var fourSum = function(nums, target) { return quadruplets; }; ``` + ### Conclusion The given solution sorts the input list and uses a nested loop structure with two pointers to find all unique quadruplets that sum up to the target. By using a set to store the quadruplets, it ensures that duplicates are avoided. The solution efficiently narrows down potential combinations by adjusting the pointers based on the current sum relative to the target. This approach is effective for generating the required output while maintaining uniqueness. @@ -263,4 +260,4 @@ The given solution sorts the input list and uses a nested loop structure with tw - Move `right` to the left, skipping duplicates. - If the sum is less than the target, move `left` to the right. - If the sum is greater than the target, move `right` to the left. -7. **Return the Result**: After processing all elements, return the list of quadruplets. \ No newline at end of file +7. **Return the Result**: After processing all elements, return the list of quadruplets. diff --git a/dsa-solutions/lc-solutions/0000-0099/0019-remove-nth-node-from-end-of-list.md b/dsa-solutions/lc-solutions/0000-0099/0019-remove-nth-node-from-end-of-list.md index 15b38f336..8102591c6 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0019-remove-nth-node-from-end-of-list.md +++ b/dsa-solutions/lc-solutions/0000-0099/0019-remove-nth-node-from-end-of-list.md @@ -6,31 +6,24 @@ tags: - Two Pointers - Linked List description: "Given the head of a linked list, remove the nth node from the end of the list and return its head." +sidebar_position: 19 --- ## Problem Description -| Problem Statement | Solution Link | LeetCode Profile | -| :-------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------ | -| [Remove nth node from end of list](https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/) | [Remove nth node from end of list on LeetCode](https://leetcode.com/problems/remove-nth-node-from-end-of-list/solutions/) | [Areetra Halder](https://leetcode.com/u/areetrahalder/) | - -### Problem Description - Given the head of a linked list, remove the nth node from the end of the list and return its head. -### Examples - -#### Example 1 +### Example 1 - **Input:** `head = [1,2,3,4,5], n = 2` - **Output:** `[1,2,3,5]` -#### Example 2 +### Example 2 - **Input:** `head = [1], n = 1` - **Output:** `[]` -#### Example 3 +### Example 3 - **Input:** `head = [1,2], n = 1` - **Output:** `[1]` @@ -42,7 +35,7 @@ Given the head of a linked list, remove the nth node from the end of the list an - $0 <= Node.val <= 100$ - $1 <= n <= sz$ -### Approach +## Approach 1. Calculate the size of the Single Linked List. We need to travel to the prev node of the node to be removed thus we perform reduce size by n 2. If the node to be removed is the first node (size == 0) then we can simply return the next node of head since it will be null if the list has only one node. @@ -50,7 +43,7 @@ Given the head of a linked list, remove the nth node from the end of the list an 4. Skip the next node by linking the prev node to the next of next node. If not present, assign null. 5. Finally return the head. -### Solution Code +## Solution Code #### Python diff --git a/dsa-solutions/lc-solutions/0000-0099/0019.Remove-N-Node-From-end-of-list.md b/dsa-solutions/lc-solutions/0000-0099/0019.Remove-N-Node-From-end-of-list.md deleted file mode 100644 index ac07040df..000000000 --- a/dsa-solutions/lc-solutions/0000-0099/0019.Remove-N-Node-From-end-of-list.md +++ /dev/null @@ -1,173 +0,0 @@ ---- -id: remove-nth-node-from-end-of-list -title: Remove nth node from end of list (LeetCode) -sidebar_label: 0019-remove-nth-node-from-end-of-list -tags: - - Two Pointers - - Linked List -description: "Given the head of a linked list, remove the nth node from the end of the list and return its head." ---- -## Problem Description - -| Problem Statement | Solution Link | LeetCode Profile | -| :-------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------ | -| [Remove nth node from end of list](https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/) | [Remove nth node from end of list on LeetCode](https://leetcode.com/problems/remove-nth-node-from-end-of-list/solutions/) | [Areetra Halder](https://leetcode.com/u/areetrahalder/) | -### Problem Description - -Given the head of a linked list, remove the nth node from the end of the list and return its head. - -### Examples - -#### Example 1 - -- **Input:** `head = [1,2,3,4,5], n = 2` -- **Output:** `[1,2,3,5]` - -#### Example 2 - -- **Input:** `head = [1], n = 1` -- **Output:** `[]` - -#### Example 3 - -- **Input:** `head = [1,2], n = 1` -- **Output:** `[1]` - -### Constraints - -- The number of nodes in the list is sz. -- $1 <= sz <= 30$ -- $0 <= Node.val <= 100$ -- $1 <= n <= sz$ -### Approach -A challenging point of this question is that Linked List doesn't have index number, so we don't know which node is the last Nth node from the last. - -My strategy is to create dummy pointer and create distance dummy pointer and head pointer. -### Solution Code - -#### Python - -```python -class Solution: - def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: - res = ListNode(0, head) - dummy = res - - for _ in range(n): - head = head.next - - while head: - head = head.next - dummy = dummy.next - - dummy.next = dummy.next.next - - return res.next -``` -#### Java - -```java -class Solution { - public ListNode removeNthFromEnd(ListNode head, int n) { - ListNode res = new ListNode(0, head); - ListNode dummy = res; - - for (int i = 0; i < n; i++) { - head = head.next; - } - - while (head != null) { - head = head.next; - dummy = dummy.next; - } - - dummy.next = dummy.next.next; - - return res.next; - } -} -``` -#### C++ - -```cpp -class Solution { -public: - ListNode* removeNthFromEnd(ListNode* head, int n) { - ListNode* res = new ListNode(0, head); - ListNode* dummy = res; - - for (int i = 0; i < n; i++) { - head = head->next; - } - - while (head != nullptr) { - head = head->next; - dummy = dummy->next; - } - - dummy->next = dummy->next->next; - - return res->next; - } -}; -``` -### Javascript -```javascript -var removeNthFromEnd = function(head, n) { - let res = new ListNode(0, head); - let dummy = res; - - for (let i = 0; i < n; i++) { - head = head.next; - } - - while (head) { - head = head.next; - dummy = dummy.next; - } - - dummy.next = dummy.next.next; - - return res.next; -}; -``` -## Step by Step Algorithm -1: Initialize variables: - - - We create a dummy node res with a value of 0 and set its next pointer to the head of the original list. This dummy node helps in handling edge cases when removing the first node. - - We initialize another pointer dummy to the dummy node res. This pointer will be used to traverse the list. -``` -res = ListNode(0, head) -dummy = res -``` -2: Move head pointer forward by n nodes: - - - We iterate n times using a for loop to advance the head pointer n nodes forward. This effectively moves head to the nth node from the beginning. -``` -for _ in range(n): - head = head.next -``` -3: Find the node before the node to be removed: - - - We use a while loop to traverse the list with both head and dummy pointers. - - As long as head is not None, we move both head and dummy pointers one node forward in each iteration. - - After this loop, dummy will be pointing to the node right before the node to be removed. -``` -while head: - head = head.next - dummy = dummy.next -``` -4: Remove the nth node from the end: - - - Once the loop finishes, dummy will be pointing to the node right before the node to be removed. - - We update the next pointer of the node pointed by dummy to skip the next node, effectively removing the nth node from the end. -``` -dummy.next = dummy.next.next -``` -5: Return the modified list: - - - Finally, we return the next node after the dummy node res, which is the head of the modified list. -``` -return res.next -``` -This algorithm effectively removes the nth node from the end of the linked list by traversing it only once. diff --git a/dsa-solutions/lc-solutions/0000-0099/0020-valid-parentheses.md b/dsa-solutions/lc-solutions/0000-0099/0020-valid-parentheses.md index 4d0476993..63d451fa8 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0020-valid-parentheses.md +++ b/dsa-solutions/lc-solutions/0000-0099/0020-valid-parentheses.md @@ -10,9 +10,9 @@ description: "Given a string s containing just the characters '(', ')', '{', '}' ## Problem Description -| Problem Statement | Solution Link | LeetCode Profile | -| :--------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------- | :------------------------------------------------------- | -| [Valid Parentheses ](https://leetcode.com/problems/valid-parentheses/description/) | +| Problem Statement | Solution Link | LeetCode Profile | +| :--------------------------------------------------------------------------------- | :------------ | :--------------- | +| [Valid Parentheses ](https://leetcode.com/problems/valid-parentheses/description/) | ### Problem Description @@ -146,22 +146,27 @@ class Solution { * @param {string} s * @return {boolean} */ -var isValid = function(s) { - let stack = []; // create an empty stack to store opening brackets - for (let c of s) { // loop through each character in the string - if (c === '(' || c === '{' || c === '[') { // if the character is an opening bracket - stack.push(c); // push it onto the stack - } else { // if the character is a closing bracket - if (!stack.length || // if the stack is empty or - (c === ')' && stack[stack.length - 1] !== '(') || // the closing bracket doesn't match the corresponding opening bracket at the top of the stack - (c === '}' && stack[stack.length - 1] !== '{') || - (c === ']' && stack[stack.length - 1] !== '[')) { - return false; // the string is not valid, so return false - } - stack.pop(); // otherwise, pop the opening bracket from the stack - } +var isValid = function (s) { + let stack = []; // create an empty stack to store opening brackets + for (let c of s) { + // loop through each character in the string + if (c === "(" || c === "{" || c === "[") { + // if the character is an opening bracket + stack.push(c); // push it onto the stack + } else { + // if the character is a closing bracket + if ( + !stack.length || // if the stack is empty or + (c === ")" && stack[stack.length - 1] !== "(") || // the closing bracket doesn't match the corresponding opening bracket at the top of the stack + (c === "}" && stack[stack.length - 1] !== "{") || + (c === "]" && stack[stack.length - 1] !== "[") + ) { + return false; // the string is not valid, so return false + } + stack.pop(); // otherwise, pop the opening bracket from the stack } - return !stack.length; // if the stack is empty, all opening brackets have been matched with their corresponding closing brackets, - // so the string is valid, otherwise, there are unmatched opening brackets, so return false + } + return !stack.length; // if the stack is empty, all opening brackets have been matched with their corresponding closing brackets, + // so the string is valid, otherwise, there are unmatched opening brackets, so return false }; ``` diff --git a/dsa-solutions/lc-solutions/0000-0099/0082-remove-duplicates-from-sorted-list-2.md b/dsa-solutions/lc-solutions/0000-0099/0082-remove-duplicates-from-sorted-list-2.md index 16bb2b15b..807813a2c 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0082-remove-duplicates-from-sorted-list-2.md +++ b/dsa-solutions/lc-solutions/0000-0099/0082-remove-duplicates-from-sorted-list-2.md @@ -1,17 +1,11 @@ --- -id: remove-duplicates-from-sorted-list-2 +id: 82-remove-duplicates-from-sorted-list-2 title: Remove Duplicates from Sorted List II (Leetcode) sidebar_label: 0082-RemoveDuplicatesFromSortedListII description: Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. +sidebar_position: 82 --- -## Problem Description - -| Problem Statement | Solution Link | LeetCode Profile | -| :---------------- | :------------ | :--------------- | -| [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/solutions) | [Aaradhya Singh ](https://leetcode.com/u/keira_09/) | - - ## Problem Description Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. diff --git a/dsa-solutions/lc-solutions/0100-0199/0189-rotate-array.md b/dsa-solutions/lc-solutions/0100-0199/0189-rotate-array.md index b27617035..d81429693 100644 --- a/dsa-solutions/lc-solutions/0100-0199/0189-rotate-array.md +++ b/dsa-solutions/lc-solutions/0100-0199/0189-rotate-array.md @@ -1,6 +1,6 @@ --- -id: rotate-array -title: Rotate Array +id: 189-rotate-array +title: Rotate Array (LeetCode) sidebar_label: 0189 Rotate Array tags: - Array diff --git a/src/data/showcase/algo.jpg b/src/data/showcase/algo.jpg new file mode 100644 index 000000000..c601ad69e Binary files /dev/null and b/src/data/showcase/algo.jpg differ diff --git a/src/data/userData.tsx b/src/data/userData.tsx index 7272cb4a5..e323d932d 100644 --- a/src/data/userData.tsx +++ b/src/data/userData.tsx @@ -133,10 +133,18 @@ export const Users: User[] = [ description: "It generates a Captcha code based on the user's input and validates the user's input with the generated Captcha code.", preview: require("./showcase/captcha-code.png"), - website: - "https://50-days-50-web-project.vercel.app/captcha/captcha.html", + website: "https://50-days-50-web-project.vercel.app/captcha/captcha.html", source: "https://github.com/dhairyagothi/50_days_50_web_project/tree/Main/public/captcha", tags: ["html", "css", "javascript"], }, -]; \ No newline at end of file + { + title: "Algo", + description: + "Algo is a modern and responsive web application for learning and practicing algorithms.", + preview: require("./showcase/algo.jpg"), + website: "https://ajay-dhangar.github.io/algo/", + source: "https://github.com/Ajay-Dhangar/algo", + tags: ["opensource", "react", "typescript", "templates", "favorite"], + }, +]; diff --git a/src/pages/index.module.css b/src/pages/index.module.css index ad2b47d4e..c0d9782e5 100644 --- a/src/pages/index.module.css +++ b/src/pages/index.module.css @@ -37,9 +37,10 @@ .tweetContainer { transition: transform 0.3s ease, box-shadow 0.3s ease, background-color 0.3s ease; + margin-bottom: 1rem; } .tweetContainer:hover { - transform: scale(0.8); + transform: scale(1.1); box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); } \ No newline at end of file diff --git a/src/pages/index.tsx b/src/pages/index.tsx index 96be012b7..d1df86c60 100644 --- a/src/pages/index.tsx +++ b/src/pages/index.tsx @@ -48,20 +48,11 @@ function TweetsSection() { spaceBetween={30} autoplay={{ delay: 2000 }} loop={true} - pagination={{ clickable: true }} + // pagination={{ clickable: true }} breakpoints={{ - 640: { - slidesPerView: 2, - spaceBetween: 20, - }, - 768: { - slidesPerView: 3, - spaceBetween: 40, - }, - 1024: { - slidesPerView: 3, - spaceBetween: 50, - }, + 640: { slidesPerView: 1, spaceBetween: 20 }, + 768: { slidesPerView: 2, spaceBetween: 40 }, + 1024: { slidesPerView: 3, spaceBetween: 50 }, }} modules={[Navigation, Pagination, Autoplay]} className={style.tweetsSwiper}