From 8a3cfc2b99932c3e04fa34d08c49bd1fcb0dd51a Mon Sep 17 00:00:00 2001 From: Yashgabani845 Date: Sat, 1 Jun 2024 09:48:41 +0530 Subject: [PATCH 1/3] lc solution 4 to 10 added --- .../0004-Median-of-two-Sorted-Array.md | 137 ++++++++++ .../0005-Longest-palindrome-substring.md | 194 ++++++++++++++ .../0000-0099/0006-ZigZag-Conversion.md | 227 +++++++++++++++++ .../0000-0099/0007-Reverse-Integers.md | 165 ++++++++++++ .../0000-0099/0008-String-to-Integer.md | 149 +++++++++++ .../0000-0099/0009-Palindrome-number.md | 238 +++++++++++++++++ .../0010-Regular-Expression-Matching.md | 239 ++++++++++++++++++ 7 files changed, 1349 insertions(+) create mode 100644 dsa-solutions/lc-solutions/0000-0099/0004-Median-of-two-Sorted-Array.md create mode 100644 dsa-solutions/lc-solutions/0000-0099/0005-Longest-palindrome-substring.md create mode 100644 dsa-solutions/lc-solutions/0000-0099/0006-ZigZag-Conversion.md create mode 100644 dsa-solutions/lc-solutions/0000-0099/0007-Reverse-Integers.md create mode 100644 dsa-solutions/lc-solutions/0000-0099/0008-String-to-Integer.md create mode 100644 dsa-solutions/lc-solutions/0000-0099/0009-Palindrome-number.md create mode 100644 dsa-solutions/lc-solutions/0000-0099/0010-Regular-Expression-Matching.md 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 new file mode 100644 index 000000000..944bc42a7 --- /dev/null +++ b/dsa-solutions/lc-solutions/0000-0099/0004-Median-of-two-Sorted-Array.md @@ -0,0 +1,137 @@ +--- +id: Median of Two Sorted Arrays +title: Median of Two Sorted Arrays(Leetcode) +sidebar_label: 0004 - Median of Two Sorted Arrays +tags: + - Array + - Binary Search + - Divide and Conquer +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)). +--- + + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :----------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------- | +| [Median of Two Sorted Arrays on LeetCode](https://leetcode.com/problems/median-of-two-sorted-arrays/description/) | [Median of Two Sorted Arrays Solution on LeetCode](https://leetcode.com/problems/median-of-two-sorted-arrays/editorial/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | + +### Problem Statement + +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))`. + +**Example 1:** +``` +Input: nums1 = [1,3], nums2 = [2] +Output: 2.00000 +Explanation: merged array = [1,2,3] and median is 2. +``` + +**Example 2:** +``` +Input: nums1 = [1,2], nums2 = [3,4] +Output: 2.50000 +Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. +``` + +### Constraints +- `nums1.length == m` +- `nums2.length == n` +- `0 <= m <= 1000` +- `0 <= n <= 1000` +- `1 <= m + n <= 2000` +- `-10^6 <= nums1[i], nums2[i] <= 10^6` + +### Solution + +#### Approach 1: Merge Sort (O(m + n)) + +**Algorithm:** +1. Merge `nums1` and `nums2` into a single sorted array. +2. Find the median of the merged array: + - If the total number of elements is odd, return the middle element. + - If the total number of elements is even, return the average of the two middle elements. + +**Python Implementation:** +```python +def findMedianSortedArrays(nums1, nums2): + merged = [] + i = j = 0 + while i < len(nums1) and j < len(nums2): + if nums1[i] < nums2[j]: + merged.append(nums1[i]) + i += 1 + else: + merged.append(nums2[j]) + j += 1 + merged.extend(nums1[i:]) + merged.extend(nums2[j:]) + + n = len(merged) + if n % 2 == 1: + return merged[n // 2] + else: + return (merged[n // 2 - 1] + merged[n // 2]) / 2.0 +``` + +#### Approach 2: Binary Search (O(log(min(m, n)))) + +**Intuition:** +To achieve O(log(min(m, n))) complexity, use binary search on the smaller array. The goal is to find a partition where the left half of both arrays combined is less than or equal to the right half. + +**Algorithm:** +1. Ensure `nums1` is the smaller array. +2. Define `imin` and `imax` for binary search on `nums1`. +3. Calculate `partitionX` and `partitionY` such that: + - `partitionX + partitionY = (m + n + 1) // 2` +4. Check conditions to find the correct partition: + - If `maxLeftX <= minRightY` and `maxLeftY <= minRightX`, you've found the correct partition. + - If `maxLeftX > minRightY`, move `imax` to the left. + - If `maxLeftY > minRightX`, move `imin` to the right. +5. Calculate the median based on the combined lengths of the arrays. + +**Python Implementation:** +```python +def findMedianSortedArrays(nums1, nums2): + if len(nums1) > len(nums2): + nums1, nums2 = nums2, nums1 + + m, n = len(nums1), len(nums2) + imin, imax, half_len = 0, m, (m + n + 1) // 2 + + while imin <= imax: + partitionX = (imin + imax) // 2 + partitionY = half_len - partitionX + + maxLeftX = float('-inf') if partitionX == 0 else nums1[partitionX - 1] + minRightX = float('inf') if partitionX == m else nums1[partitionX] + + maxLeftY = float('-inf') if partitionY == 0 else nums2[partitionY - 1] + minRightY = float('inf') if partitionY == n else nums2[partitionY] + + if maxLeftX <= minRightY and maxLeftY <= minRightX: + if (m + n) % 2 == 1: + return max(maxLeftX, maxLeftY) + else: + return (max(maxLeftX, maxLeftY) + min(minRightX, minRightY)) / 2.0 + elif maxLeftX > minRightY: + imax = partitionX - 1 + else: + imin = partitionX + 1 +``` + +### Complexity Analysis + +- **Time Complexity:** + - Approach 1: O(m + n) because it involves merging both arrays into one sorted array. + - Approach 2: O(log(min(m, n))) because it performs binary search on the smaller array. + +- **Space Complexity:** + - Approach 1: O(m + n) due to the additional space needed for the merged array. + - Approach 2: O(1) because it uses only a constant amount of additional space. + +### Summary + +Approach 1 is straightforward but not optimal in terms of time complexity for large input sizes. Approach 2 leverages binary search to efficiently find the median with logarithmic time complexity, making it suitable for large arrays. \ No newline at end of file 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 new file mode 100644 index 000000000..2dcc38bff --- /dev/null +++ b/dsa-solutions/lc-solutions/0000-0099/0005-Longest-palindrome-substring.md @@ -0,0 +1,194 @@ +--- +id: Longest Palindromic Substring +title: Longest Palindromic Substring(LeetCode) +sidebar_label: 0005-Longest Palindrome Substring +tags: + - String + - Dynamic Programming +description: Given a string s, return the longest palindromic substring in s. +--- + +## 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`. + +### Examples + +**Example 1:** +```plaintext +Input: s = "babad" +Output: "bab" +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. + +## Solution + +### 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. +4. Use nested loops to check all possible substrings and use the helper method to determine if they are palindromes. +5. Keep track of the longest palindrome found. + +#### Implementation +```python +def longestPalindrome(s: str) -> str: + def check(l, r): + while l >= 0 and r < len(s) and s[l] == s[r]: + 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. +4. Use the table to extend palindromes to longer substrings. +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): + while left >= 0 and right < len(s) and s[left] == s[right]: + 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. +- **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 new file mode 100644 index 000000000..162bf0a86 --- /dev/null +++ b/dsa-solutions/lc-solutions/0000-0099/0006-ZigZag-Conversion.md @@ -0,0 +1,227 @@ +--- +id: Zigzag Conversion +title: Zigzag Conversion (LeetCode) +sidebar_label: 0006-Zigzag Conversion +tags: + - String +description: Convert the given string into a zigzag pattern with a specified number of rows. +--- + +## 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: + +``` +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: + +```python +string convert(string s, int numRows) +``` + +### Examples + +**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 + +- 0 < s.length < 1001 +- s consists of English letters (lower-case and upper-case), ',' and '.'. +- 0 < numRows < 1000 + +## Intuition + +Just look at the top row what is the difference between each character, i.e., A and I, and I and Q = 8 (5*2-2 == number of rows * 2 - 2, the corner elements are excluded). Similarly for each row, i.e., B and J, the difference is 8. + +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); + +## Approach + +1. Create an empty StringBuilder which is our answer. +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. + +### Java Solution + +```java +class Solution { + public String convert(String s, int numRows) { + if (numRows == 1) { + return s; + } + + StringBuilder answer = new StringBuilder(); + int n = s.length(); + int diff = 2 * (numRows - 1); + int diagonalDiff = diff; + int secondIndex; + int index; + for (int i = 0; i < numRows; i++) { + index = i; + + while (index < n) { + answer.append(s.charAt(index)); + if (i != 0 && i != numRows - 1) { + diagonalDiff = diff-2*i; + secondIndex = index + diagonalDiff; + + if (secondIndex < n) { + answer.append(s.charAt(secondIndex)); + } + } + index += diff; + } + } + + return answer.toString(); + } +} +``` + +### C++ Solution + +```cpp +class Solution { +public: + string convert(string s, int numRows) { + if (numRows == 1) { + return s; + } + + stringstream answer; + int n = s.length(); + int diff = 2 * (numRows - 1); + int diagonalDiff = diff; + int secondIndex; + int index; + for (int i = 0; i < numRows; i++) { + index = i; + + while (index < n) { + answer << s[index]; + if (i != 0 && i != numRows - 1) { + diagonalDiff = diff-2*i; + secondIndex = index + diagonalDiff; + + if (secondIndex < n) { + answer << s[secondIndex]; + } + } + index += diff; + } + } + + return answer.str(); + } +}; +``` + +### Python Solution + +```python +class Solution: + def convert(self, s: str, numRows: int) -> str: + if numRows == 1: + return s + answer = '' + n = len(s) + diff = 2 * (numRows - 1) + diagonal_diff = diff + second_index = 0 + index = 0 + for i in range(numRows): + index = i + while index < n: + answer += s[index] + if i != 0 and i != numRows - 1: + diagonal_diff = diff - 2 * i + second_index = index + diagonal_diff + if second_index < n: + answer += s[second_index] + index += diff + return answer +``` +### Complexity Analysis + +#### Approach 1: Iterative Approach + +- **Time Complexity**: O(n), where n is the length of the input string `s`. We iterate through the entire string once. +- **Space Complexity**: O(n), where n is the length of the input string `s`. We use a StringBuilder to store the output. + +#### Approach 2: Using StringBuilder Rows + +- **Time Complexity**: O(n), where n is the length of the input string `s`. We iterate through the entire string once to fill the rows of the StringBuilder. +- **Space Complexity**: O(n), where n is the length of the input string `s`. We use a StringBuilder to store the output. + +#### Approach 3: Direct Construction + +- **Time Complexity**: O(n), where n is the length of the input string `s`. We iterate through the entire string once to construct the output string. +- **Space Complexity**: O(n), where n is the length of the input string `s`. We use a StringBuilder to store the output. + +#### Approach 4: Using Mathematical Formula + +- **Time Complexity**: O(n), where n is the length of the input string `s`. We iterate through the entire string once to construct the output string. +- **Space Complexity**: O(n), where n is the length of the input string `s`. We use a StringBuilder to store the output. + +### Conclusion + +We explored four different approaches to solve the Zigzag Conversion problem, each offering a unique perspective and trade-offs in terms of simplicity and efficiency. All four approaches have a linear time complexity of O(n), where n is the length of the input string `s`. The space complexity varies slightly among the approaches but remains linear in terms of the input size. diff --git a/dsa-solutions/lc-solutions/0000-0099/0007-Reverse-Integers.md b/dsa-solutions/lc-solutions/0000-0099/0007-Reverse-Integers.md new file mode 100644 index 000000000..2e7bd20c0 --- /dev/null +++ b/dsa-solutions/lc-solutions/0000-0099/0007-Reverse-Integers.md @@ -0,0 +1,165 @@ +--- +id: Reverse Integer +title: Reverse Integer(LeetCode) +sidebar_label: 0007-Reverse Integer +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. +--- + +## 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. + +### Examples + +**Example 1:** + +``` +Input: x = 123 +Output: 321 +``` + +**Example 2:** + +``` +Input: x = -123 +Output: -321 +``` + +**Example 3:** + +``` +Input: x = 120 +Output: 21 +``` + +### Constraints + +- `-2^31 <= x <= 2^31 - 1` + +## Solution + +### Approach 1: Pop and Push Digits & Check before Overflow + +#### Intuition + +We can build up the reverse integer one digit at a time while checking for overflow. + +#### Algorithm + +1. Repeatedly "pop" the last digit off of `x` and "push" it to the back of `rev`. +2. Before pushing, check if appending another digit would cause overflow. + +#### C++ Implementation + +```cpp +class Solution { +public: + int reverse(int x) { + int rev = 0; + while (x != 0) { + int pop = x % 10; + x /= 10; + if (rev > INT_MAX / 10 || (rev == INT_MAX / 10 && pop > 7)) + return 0; + if (rev < INT_MIN / 10 || (rev == INT_MIN / 10 && pop < -8)) + return 0; + rev = rev * 10 + pop; + } + return rev; + } +}; +``` + +#### Java Implementation + +```java +class Solution { + public int reverse(int x) { + int rev = 0; + while (x != 0) { + int pop = x % 10; + x /= 10; + if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) + return 0; + if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) + return 0; + rev = rev * 10 + pop; + } + return rev; + } +} +``` + +#### Python Implementation + +```python +def reverse(x: int) -> int: + rev = 0 + while x != 0: + pop = x % 10 + x //= 10 + if rev > 0 and (rev > 2**31 // 10 or (rev == 2**31 // 10 and pop > 7)): + return 0 + if rev < 0 and (rev < -2**31 // 10 or (rev == -2**31 // 10 and pop < -8)): + return 0 + rev = rev * 10 + pop + return rev +``` + +#### JavaScript Implementation + +```javascript +var reverse = function (x) { + let rev = 0; + while (x !== 0) { + let pop = x % 10; + x = (x - pop) / 10; + if ( + rev > Math.pow(2, 31) / 10 || + (rev == Math.pow(2, 31) / 10 && pop > 7) + ) + return 0; + if ( + rev < Math.pow(-2, 31) / 10 || + (rev == Math.pow(-2, 31) / 10 && pop < -8) + ) + return 0; + rev = rev * 10 + pop; + } + return rev; +}; +``` + +#### Python Class Implementation + +```python +class Solution: + def reverse(self, x: int) -> int: + sign = [1, -1][x < 0] + rev, x = 0, abs(x) + while x: + x, mod = divmod(x, 10) + rev = rev * 10 + mod + if rev > 2**31 - 1: + return 0 + return sign * rev +``` + +### Complexity Analysis + +- **Time Complexity**: O(log(x)). There are roughly log10(x) digits in `x`. +- **Space Complexity**: O(1). + +### Conclusion + +We have successfully solved the "Reverse Integer" problem using a simple approach that reverses the digits of the given integer while handling overflow conditions. This solution provides an efficient way to reverse an integer without the need for any additional data structures. + +``` \ No newline at end of file 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 new file mode 100644 index 000000000..07da36a3a --- /dev/null +++ b/dsa-solutions/lc-solutions/0000-0099/0008-String-to-Integer.md @@ -0,0 +1,149 @@ +--- +id: String to Integer +title: String to Integer(LeetCode) +sidebar_label: 0008-String to Integer +tags: + - String + - Math +description: Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. +--- + +## 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. + +The algorithm for `myAtoi(string s)` is as follows: + +1. **Whitespace:** Ignore any leading whitespace (" "). +2. **Signedness:** Determine the sign by checking if the next character is '-' or '+', assuming positivity is neither present. +3. **Conversion:** Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0. +4. **Rounding:** If the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1], then round the integer to remain in the range. Specifically, integers less than -2^31 should be rounded to -2^31, and integers greater than 2^31 - 1 should be rounded to 2^31 - 1. +5. Return the integer as the final result. + +### Examples + +**Example 1:** + +``` +Input: s = "42" +Output: 42 +``` + +**Example 2:** + +``` +Input: s = " -042" +Output: -42 +``` + +**Example 3:** + +``` +Input: s = "1337c0d3" +Output: 1337 +``` + +**Example 4:** + +``` +Input: s = "0-1" +Output: 0 +``` + +**Example 5:** + +``` +Input: s = "words and 987" +Output: 0 +``` + +### Constraints + +- 0 < s.length < 200 +- s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'. + +## Solution + +### Approach + +#### Intuition + +The function should iterate through the string, handling leading whitespaces, signs, and valid digits. It should accumulate the numerical value while checking for overflow conditions. + +#### Algorithm + +1. **Handling Empty String:** + - If `s.length() == 0`, return 0 as there's no numerical content. + +2. **Skipping Leading Whitespaces:** + - Iterate through characters (`s.charAt(i)`) as long as they are whitespaces (' ') and the index `i` is within the string bounds. This skips any leading whitespaces before the potential number. + +3. **Handling Optional Sign:** + - Check if the first non-whitespace character (`s.charAt(i)`) is a sign ('-' or '+'). + - If it's a minus sign, set the `sign` variable to -1 to indicate a negative number. + +4. **Converting Digits:** + - Iterate through characters as long as they are valid digits (between '0' and '9') and the index `i` is within the string bounds. + - Convert the current character (assumed to be a digit) to its corresponding integer value by subtracting the ASCII value of '0'. + +5. **Overflow Handling:** + - Check for potential overflow situations for positive numbers: + - Compare the current accumulated value (`ans`) with the maximum integer value (`max`) divided by 10 (considering the next digit) and the remainder (`max % 10`). + - If `ans` is already greater than the maximum divided by 10, or if `ans` is equal to the maximum divided by 10 and the current digit is greater than the remainder, it signifies overflow. + - In case of overflow, return the maximum positive value if the sign is positive, or the minimum negative value if the sign is negative. + +6. **Returning the Result:** + - After processing all valid digits, multiply the final `ans` by the `sign` (1 for positive, -1 for negative) and return it as the converted integer value. + +### Code + +#### Java Implementation + +```java +class Solution { + public int myAtoi(String s) { + int ans = 0; + int i = 0; + int sign = 1; + int max = Integer.MAX_VALUE; + int min = Integer.MIN_VALUE; + if (s.length() == 0) { + return 0; + } + while (i < s.length() && s.charAt(i) == ' ') { + i++; + } + if (i < s.length() && (s.charAt(i) == '-' || s.charAt(i) == '+')) { + if (s.charAt(i) == '-') { + sign = -1; + } + i++; + } + while (i < s.length() && s.charAt(i) - '0' <= 9 && s.charAt(i) - '0' >= 0) { + int digit = s.charAt(i) - '0'; + if (ans > max / 10 || (ans == max / 10 && digit > max % 10)) { + return (sign == 1) ? max : min; + } + ans = ans * 10 + digit; + i++; + } + return ans * sign; + } +} +``` + +### Complexity Analysis + +- **Time Complexity**: O(n), where n is the length of the string `s`. +- **Space Complexity**: O(1), due to the constant number of variables used. + +## Conclusion + +We have successfully implemented the `myAtoi` function to convert a string to a 32-bit signed integer. The solution handles leading whitespaces, signs, valid digits, and overflow conditions efficiently, providing a robust string-to-interger(atoi) + +``` \ No newline at end of file diff --git a/dsa-solutions/lc-solutions/0000-0099/0009-Palindrome-number.md b/dsa-solutions/lc-solutions/0000-0099/0009-Palindrome-number.md new file mode 100644 index 000000000..d6999e032 --- /dev/null +++ b/dsa-solutions/lc-solutions/0000-0099/0009-Palindrome-number.md @@ -0,0 +1,238 @@ +--- +id: Palindrome Number +title: Palindrome Number (LeetCode) +sidebar_label: 0009-Palindrome Number +tags: + - Math + - Palindrome +description: Given an integer x, return true if x is a palindrome, and false otherwise. +--- +## 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 + +Given an integer `x`, return `true` if `x` is a palindrome, and `false` otherwise. + +### Examples + +**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 + +- -2^31 < x < 2^31 - 1 + +## Solution + +### Approach 1: Reversing the Entire Number + +#### Intuition + +The intuition behind this approach is to reverse the entire input number and check if the reversed number is equal to the original number. If they are the same, then the number is a palindrome. + +#### Algorithm + +1. **Handling Special Cases:** + - If `x` is negative, return `false`, as negative numbers cannot be palindromes. +2. **Reversing the Number:** + - Initialize two variables: `reversed` and `temp`. + - Enter a loop that continues until `temp` becomes zero: + - Inside the loop: + - Extract the last digit of `temp` using modulo `%` and store it in `digit`. + - Reverse the number by multiplying `reversed` by 10 and adding the extracted `digit`. + - Divide `temp` by 10 to remove the last digit and move to the next iteration. +3. **Comparison:** + - Compare the reversed value `reversed` with the original input value `x`. + - If they are equal, return `true`; otherwise, return `false`. + +#### Code (C++) + +```cpp +class Solution { +public: + bool isPalindrome(int x) { + if (x < 0) { + return false; + } + + long long reversed = 0; + long long temp = x; + + while (temp != 0) { + int digit = temp % 10; + reversed = reversed * 10 + digit; + temp /= 10; + } + + return (reversed == x); + } +}; +``` + +#### Code (Java) + +```java +class Solution { + public boolean isPalindrome(int x) { + if (x < 0) { + return false; + } + + long reversed = 0; + long temp = x; + + while (temp != 0) { + int digit = (int) (temp % 10); + reversed = reversed * 10 + digit; + temp /= 10; + } + + return (reversed == x); + } +} +``` + +#### Code (Python) + +```python +class Solution: + def isPalindrome(self, x: int) -> bool: + if x < 0: + return False + + reversed_num = 0 + temp = x + + while temp != 0: + digit = temp % 10 + reversed_num = reversed_num * 10 + digit + temp //= 10 + + return reversed_num == x +``` + +### Approach 2: Reversing Half of the Number + +#### Intuition + +Instead of reversing the entire number, we can reverse only the last half of the number. This approach is more efficient in terms of time complexity and memory usage. + +#### Algorithm + +1. **Handling Special Cases:** + - If `x` is negative or ends with a zero, return `false`. +2. **Reversing the Second Half:** + - Initialize two variables: `reversed` and `original`. + - Enter a loop that continues until the first half of the digits (represented by `x`) becomes less than or equal to the reversed second half (`reversed`): + - Inside the loop: + - Extract the last digit of `x` using modulo `%` and add it to the `reversed` variable after multiplying it by 10 (shifting the existing digits to the left). + - Divide `x` by 10 to remove the last digit and move towards the center of the number. +3. **Comparison:** + - Compare the first half of the digits (`x`) with the reversed second half (`reversed`) to determine if the number is a palindrome: + - For an even number of digits, compare `x` with `reversed`. + - For an odd number of digits, compare `x` with `reversed / 10` (ignoring the middle digit). + - If the comparison holds true, return `true`; otherwise, return `false`. + +#### Code (C++) + +```cpp +class Solution { +public: + bool isPalindrome(int x) { + if (x < 0 || (x != 0 && x % 10 == 0)) { + return false; + } + + int reversed = 0; + int original = x; + + while (x > reversed) { + reversed = reversed * 10 + x % 10; + x /= 10; + } + + return (x == reversed) || (x == reversed / 10); + } +}; +``` + +#### Code (Java) + +```java +class Solution { + public boolean isPalindrome(int x) { + if (x < 0 || (x != 0 && x % 10 == 0)) { + return false; + } + + int reversed = 0; + int original = x; + + while (x > reversed) { + reversed = reversed * 10 + x % 10; + x /= 10; + } + + return (x == reversed) || (x == reversed / 10); + } +} +``` + +#### Code (Python) + +```python +class Solution: + def isPalindrome(self, x: int) -> bool: + if x < 0 or (x != 0 and x % 10 == 0): + return False + + reversed_num = 0 + original = x + + while x > reversed_num: + reversed_num = reversed_num * 10 + x % 10 + x //= 10 + + return x == reversed_num or x == reversed_num // 10 +``` + +## Complexity Analysis + +### Approach 1: Reversing the Entire Number + +- **Time Complexity**: O(log10(x)), where x is the input number. +- **Space Complexity**: O(1). + +### Approach 2: Reversing Half of the Number + +- **Time Complexity**: O(log10(x)), where x is the input number. +- **Space Complexity**: O(1). + +## Conclusion + +We have explored two approaches to determine whether an integer is a palindrome. Both approaches provide efficient solutions, with the second approach being slightly more optimized in terms of time and space complexity. These solutions offer different perspectives on how \ No newline at end of file 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 new file mode 100644 index 000000000..bb7005534 --- /dev/null +++ b/dsa-solutions/lc-solutions/0000-0099/0010-Regular-Expression-Matching.md @@ -0,0 +1,239 @@ +--- +id: Regular Expression Matching +title: Regular Expression Matching (LeetCode) +sidebar_label: 0010-Regular Expression Matching +tags: + - String + - 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. +--- + +## Problem Description + +Given an input string `s` and a pattern `p`, implement regular expression matching with support for '.' and '*' where: + +- '.' Matches any single character. +- '*' Matches zero or more of the preceding element. + +The matching should cover the entire input string (not partial). + +### Examples + +**Example 1:** + +``` +Input: s = "aa", p = "a" +Output: false +Explanation: "a" does not match the entire string "aa". +``` + +**Example 2:** + +``` +Input: s = "aa", p = "a*" +Output: true +Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". +``` + +**Example 3:** + +``` +Input: s = "ab", p = ".*" +Output: true +Explanation: ".*" means "zero or more (*) of any character (.)". +``` + +### Constraints + +- 1 < s.length < 20 +- 1 < p.length < 20 +- `s` contains osnly lowercase English letters. +- `p` contains only lowercase English letters, '.', and '*'. +- It is guaranteed for each appearance of the character '*', there will be a previous valid character to match. + +## Solution + +### Approach 1: Recursion + +#### Intuition + +If there were no Kleene stars (the * wildcard character for regular expressions), the problem would be easier - we simply check from left to right if each character of the text matches the pattern. + +When a star is present, we may need to check many different suffixes of the text and see if they match the rest of the pattern. A recursive solution is a straightforward way to represent this relationship. + +#### Algorithm + +Without a Kleene star, our solution would look like this: + +```python +def match(text, pattern): + if not pattern: + return not text + first_match = bool(text) and pattern[0] in {text[0], "."} + return first_match and match(text[1:], pattern[1:]) +``` + +If a star is present in the pattern, it will be in the second position `pattern[1]`. Then, we may ignore this part of the pattern, or delete a matching character in the text. If we have a match on the remaining strings after any of these operations, then the initial inputs matched. + +#### Code (Java) + +```java +class Solution { + public boolean isMatch(String text, String pattern) { + if (pattern.isEmpty()) return text.isEmpty(); + boolean first_match = + (!text.isEmpty() && + (pattern.charAt(0) == text.charAt(0) || + pattern.charAt(0) == '.')); + + if (pattern.length() >= 2 && pattern.charAt(1) == '*') { + return ( + isMatch(text, pattern.substring(2)) || + (first_match && isMatch(text.substring(1), pattern)) + ); + } else { + return ( + first_match && isMatch(text.substring(1), pattern.substring(1)) + ); + } + } +} +``` + +#### Code (Python) + +```python +class Solution: + def isMatch(self, text: str, pattern: str) -> bool: + if not pattern: + return not text + + first_match = bool(text) and pattern[0] in {text[0], "."} + + if len(pattern) >= 2 and pattern[1] == "*": + return ( + self.isMatch(text, pattern[2:]) + or first_match + and self.isMatch(text[1:], pattern) + ) + else: + return first_match and self.isMatch(text[1:], pattern[1:]) +``` + +### Approach 2: Dynamic Programming + +#### Intuition + +As the problem has an optimal substructure, it is natural to cache intermediate results. We ask the question `dp(i, j)`: does `text[i:]` and `pattern[j:]` match? We can describe our answer in terms of answers to questions involving smaller strings. + +#### Top-Down Variation (Java) + +```java +enum Result { + TRUE, + FALSE, +} + +class Solution { + Result[][] memo; + + public boolean isMatch(String text, String pattern) { + memo = new Result[text.length() + 1][pattern.length() + 1]; + return dp(0, 0, text, pattern); + } + + public boolean dp(int i, int j, String text, String pattern) { + if (memo[i][j] != null) { + return memo[i][j] == Result.TRUE; + } + boolean ans; + if (j == pattern.length()) { + ans = i == text.length(); + } else { + boolean first_match = + (i < text.length() && + (pattern.charAt(j) == text.charAt(i) || + pattern.charAt(j) == '.')); + + if (j + 1 < pattern.length() && pattern.charAt(j + 1) == '*') { + ans = (dp(i, j + 2, text, pattern) || + (first_match && dp(i + 1, j, text, pattern))); + } else { + ans = first_match && dp(i + 1, j + 1, text, pattern); + } + } + memo[i][j] = ans ? Result.TRUE : Result.FALSE; + return ans; + } +} +``` + +#### Bottom-Up Variation (Java) + +```java +class Solution { + public boolean isMatch(String text, String pattern) { + boolean[][] dp = new boolean[text.length() + 1][pattern.length() + 1]; + dp[text.length()][pattern.length()] = true; + + for (int i = text.length(); i >= 0; i--) { + for (int j = pattern.length() - 1; j >= 0; j--) { + boolean first_match = + (i < text.length() && + (pattern.charAt(j) == text.charAt(i) || + pattern.charAt(j) == '.')); + if (j + 1 < pattern.length() && pattern.charAt(j + 1) == '*') { + dp[i][j] = dp[i][j + 2] || (first_match && dp[i + 1][j]); + } else { + dp[i][j] = first_match && dp[i + 1][j + 1]; + } + } + } + return dp[0][0]; + } +} +``` + +#### Code (Python) + +```python +class Solution: + def isMatch(self, text: str, pattern: str) -> bool: + memo = {} + + def dp(i: int, j: int) -> bool: + if (i, j) not in memo: + if j == len(pattern): + ans = i == len(text) + else: + first_match = i < len(text) and pattern[j] in {text[i], "."} + if j + 1 < len(pattern) and pattern[j + 1] == "*": + ans = dp(i, j + 2) or first_match and dp(i + 1, j) + else: + ans = first_match and dp(i + 1, j + 1) + + memo[i, j] = ans + return memo[i, j] + + return dp(0, 0) +``` +Complexity Analysis +Time Complexity +Let T, P be the lengths of the text and the pattern respectively. The work for every call to dp(i, j) for i=0,...,T; j=0,...,P is done once, and it is O(1) work. Hence, the time complexity is O(TP). + +Space Complexity +The only memory we use is the O(TP) boolean entries in our cache. Hence, the space complexity is O(TP) + + +Now, just as you asked, the last part should include the summary and links to the problem, solution, and profile. Let's add that: + +## Summary + +This problem involves implementing regular expression matching with support for '.' and '*', where '.' matches any single character and '*' matches zero or more of the preceding element. Two approaches are commonly used to solve this problem: + +1. **Recursion**: This approach involves a straightforward recursive solution. If there were no Kleene stars, checking from left to right if each character of the text matches the pattern would suffice. When a star is present, we may need to check many different suffixes of the text and see if they match the rest of the pattern. + +2. **Dynamic Programming**: As the problem has an optimal substructure, we can use dynamic programming to cache intermediate results. We can describe our answer in terms of answers to questions involving smaller strings. + + From 0b47bf6d492f64212934bf20c9da6049d572ad36 Mon Sep 17 00:00:00 2001 From: Gabani yash <127788321+Yashgabani845@users.noreply.github.com> Date: Sat, 1 Jun 2024 10:35:11 +0530 Subject: [PATCH 2/3] Update 0004-Median-of-two-Sorted-Array.md --- .../0004-Median-of-two-Sorted-Array.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) 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 944bc42a7..55446a871 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 @@ -6,7 +6,7 @@ tags: - Array - Binary Search - Divide and Conquer -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. The overall run time complexity should be $O(log (m+n))$. --- @@ -20,7 +20,7 @@ description: Given two sorted arrays nums1 and nums2 of size m and n respectivel 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))`. +The overall run time complexity should be $O(log (m+n))$. **Example 1:** ``` @@ -46,7 +46,7 @@ Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. ### Solution -#### Approach 1: Merge Sort (O(m + n)) +#### Approach 1: Merge Sort $(O(m + n))$ **Algorithm:** 1. Merge `nums1` and `nums2` into a single sorted array. @@ -79,7 +79,7 @@ def findMedianSortedArrays(nums1, nums2): #### Approach 2: Binary Search (O(log(min(m, n)))) **Intuition:** -To achieve O(log(min(m, n))) complexity, use binary search on the smaller array. The goal is to find a partition where the left half of both arrays combined is less than or equal to the right half. +To achieve $O(log(min(m, n)))$ complexity, use binary search on the smaller array. The goal is to find a partition where the left half of both arrays combined is less than or equal to the right half. **Algorithm:** 1. Ensure `nums1` is the smaller array. @@ -125,13 +125,13 @@ def findMedianSortedArrays(nums1, nums2): ### Complexity Analysis - **Time Complexity:** - - Approach 1: O(m + n) because it involves merging both arrays into one sorted array. - - Approach 2: O(log(min(m, n))) because it performs binary search on the smaller array. + - Approach 1:$O(m + n)$ because it involves merging both arrays into one sorted array. + - Approach 2: $O(log(min(m, n)))$ because it performs binary search on the smaller array. - **Space Complexity:** - - Approach 1: O(m + n) due to the additional space needed for the merged array. - - Approach 2: O(1) because it uses only a constant amount of additional space. + - Approach 1: $O(m + n)$ due to the additional space needed for the merged array. + - Approach 2: $O(1)$ because it uses only a constant amount of additional space. ### Summary -Approach 1 is straightforward but not optimal in terms of time complexity for large input sizes. Approach 2 leverages binary search to efficiently find the median with logarithmic time complexity, making it suitable for large arrays. \ No newline at end of file +Approach 1 is straightforward but not optimal in terms of time complexity for large input sizes. Approach 2 leverages binary search to efficiently find the median with logarithmic time complexity, making it suitable for large arrays. From 81a036d22a2935106c3a1e99bd0a06c0b829ac40 Mon Sep 17 00:00:00 2001 From: Yashgabani845 Date: Sat, 1 Jun 2024 10:43:14 +0530 Subject: [PATCH 3/3] all complexity style chnaged --- .../0004-Median-of-two-Sorted-Array.md | 2 +- .../0005-Longest-palindrome-substring.md | 16 ++++++++-------- .../0000-0099/0006-ZigZag-Conversion.md | 18 +++++++++--------- .../0000-0099/0007-Reverse-Integers.md | 4 ++-- .../0000-0099/0008-String-to-Integer.md | 4 ++-- .../0000-0099/0009-Palindrome-number.md | 8 ++++---- .../0010-Regular-Expression-Matching.md | 4 ++-- 7 files changed, 28 insertions(+), 28 deletions(-) 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 55446a871..666f49d3b 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 @@ -76,7 +76,7 @@ def findMedianSortedArrays(nums1, nums2): return (merged[n // 2 - 1] + merged[n // 2]) / 2.0 ``` -#### Approach 2: Binary Search (O(log(min(m, n)))) +#### Approach 2: Binary Search $(O(log(min(m, n))))$ **Intuition:** To achieve $O(log(min(m, n)))$ complexity, use binary search on the smaller array. The goal is to find a partition where the left half of both arrays combined is less than or equal to the right half. 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 2dcc38bff..f4f974d63 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 @@ -70,8 +70,8 @@ def longestPalindrome(s: str) -> str: ``` ### 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. +- **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 @@ -112,8 +112,8 @@ def longestPalindrome(s: str) -> str: ``` ### 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. +- **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 @@ -148,8 +148,8 @@ def longestPalindrome(s: str) -> str: ``` ### Complexity Analysis -- **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. +- **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 @@ -185,8 +185,8 @@ def longestPalindrome(s: str) -> str: ``` ### 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. +- **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 162bf0a86..dabeb24d3 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0006-ZigZag-Conversion.md +++ b/dsa-solutions/lc-solutions/0000-0099/0006-ZigZag-Conversion.md @@ -204,24 +204,24 @@ class Solution: #### Approach 1: Iterative Approach -- **Time Complexity**: O(n), where n is the length of the input string `s`. We iterate through the entire string once. -- **Space Complexity**: O(n), where n is the length of the input string `s`. We use a StringBuilder to store the output. +- **Time Complexity**: $O(n)$, where n is the length of the input string `s`. We iterate through the entire string once. +- **Space Complexity**: $O(n)$, where n is the length of the input string `s`. We use a StringBuilder to store the output. #### Approach 2: Using StringBuilder Rows -- **Time Complexity**: O(n), where n is the length of the input string `s`. We iterate through the entire string once to fill the rows of the StringBuilder. -- **Space Complexity**: O(n), where n is the length of the input string `s`. We use a StringBuilder to store the output. +- **Time Complexity**: $O(n)$, where n is the length of the input string `s`. We iterate through the entire string once to fill the rows of the StringBuilder. +- **Space Complexity**:$O(n)$, where n is the length of the input string `s`. We use a StringBuilder to store the output. #### Approach 3: Direct Construction -- **Time Complexity**: O(n), where n is the length of the input string `s`. We iterate through the entire string once to construct the output string. -- **Space Complexity**: O(n), where n is the length of the input string `s`. We use a StringBuilder to store the output. +- **Time Complexity**: $O(n)$, where n is the length of the input string `s`. We iterate through the entire string once to construct the output string. +- **Space Complexity**: $O(n)$, where n is the length of the input string `s`. We use a StringBuilder to store the output. #### Approach 4: Using Mathematical Formula -- **Time Complexity**: O(n), where n is the length of the input string `s`. We iterate through the entire string once to construct the output string. -- **Space Complexity**: O(n), where n is the length of the input string `s`. We use a StringBuilder to store the output. +- **Time Complexity**: $O(n)$, where n is the length of the input string `s`. We iterate through the entire string once to construct the output string. +- **Space Complexity**: $O(n)$, where n is the length of the input string `s`. We use a StringBuilder to store the output. ### Conclusion -We explored four different approaches to solve the Zigzag Conversion problem, each offering a unique perspective and trade-offs in terms of simplicity and efficiency. All four approaches have a linear time complexity of O(n), where n is the length of the input string `s`. The space complexity varies slightly among the approaches but remains linear in terms of the input size. +We explored four different approaches to solve the Zigzag Conversion problem, each offering a unique perspective and trade-offs in terms of simplicity and efficiency. All four approaches have a linear time complexity of $O(n)$, where n is the length of the input string `s`. The space complexity varies slightly among the approaches but remains linear in terms of the input size. 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 2e7bd20c0..c7f074cbd 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0007-Reverse-Integers.md +++ b/dsa-solutions/lc-solutions/0000-0099/0007-Reverse-Integers.md @@ -155,8 +155,8 @@ class Solution: ### Complexity Analysis -- **Time Complexity**: O(log(x)). There are roughly log10(x) digits in `x`. -- **Space Complexity**: O(1). +- **Time Complexity**: $O(log(x))$. There are roughly log10(x) digits in `x`. +- **Space Complexity**: $O(1)$. ### Conclusion 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 07da36a3a..3da8437b9 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 @@ -139,8 +139,8 @@ class Solution { ### Complexity Analysis -- **Time Complexity**: O(n), where n is the length of the string `s`. -- **Space Complexity**: O(1), due to the constant number of variables used. +- **Time Complexity**: $O(n)$, where n is the length of the string `s`. +- **Space Complexity**: $O(1)$, due to the constant number of variables used. ## Conclusion 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 d6999e032..908decfd9 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0009-Palindrome-number.md +++ b/dsa-solutions/lc-solutions/0000-0099/0009-Palindrome-number.md @@ -225,13 +225,13 @@ class Solution: ### Approach 1: Reversing the Entire Number -- **Time Complexity**: O(log10(x)), where x is the input number. -- **Space Complexity**: O(1). +- **Time Complexity**: $O(log10(x))$, where x is the input number. +- **Space Complexity**: $O(1)$. ### Approach 2: Reversing Half of the Number -- **Time Complexity**: O(log10(x)), where x is the input number. -- **Space Complexity**: O(1). +- **Time Complexity**: $O(log10(x))$, where x is the input number. +- **Space Complexity**: $O(1)$. ## Conclusion 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 bb7005534..2506577d2 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 @@ -220,10 +220,10 @@ class Solution: ``` Complexity Analysis Time Complexity -Let T, P be the lengths of the text and the pattern respectively. The work for every call to dp(i, j) for i=0,...,T; j=0,...,P is done once, and it is O(1) work. Hence, the time complexity is O(TP). +Let T, P be the lengths of the text and the pattern respectively. The work for every call to dp(i, j) for i=0,...,T; j=0,...,P is done once, and it is $O(1)$ work. Hence, the time complexity is $O(TP)$. Space Complexity -The only memory we use is the O(TP) boolean entries in our cache. Hence, the space complexity is O(TP) +The only memory we use is the $O(TP)$ boolean entries in our cache. Hence, the space complexity is $O(TP)$ Now, just as you asked, the last part should include the summary and links to the problem, solution, and profile. Let's add that: