title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
tag
stringclasses
707 values
level
stringclasses
3 values
question_hints
stringlengths
19
3.98k
view_count
int64
8
630k
vote_count
int64
5
10.4k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
61,654
271
Time complexity: $$O(m+n)$$\n\n# Idea\n\n- We create a new array with length that of the **sum of the array lengths**\n- We initialize **i & j = 0**. [i for nums1 & j for nums2]\n- Since the given arrays are already sorted it is easy to compare their elements. We comapre by observing nums1[i] < nums2[j]\n- if the element in $$nums1$$ at $$i^{th}$$ is less than that of element at $$j^{th}$$ index of $$nums2$$, we add $$nums1[i]$$ to new array and increment i; so as to compare the next element of the array to nums2[j].\n- If the opposite case arises, we add $$nums2[j]$$ to the new array as you can guess. And increment j by 1 for the same reasons we did it with i.\n- Depending on the length of new array, we calculate *median*.\n- If the length of array is even, median by rule is the average of the *2 middle elements* of the array\n- If it is off, it is the *middlemost* element\n\nI will try to make a video on this to explain this with illustration soon, I\'m currently on a time crunch \u23F3 so it might take a while \uD83D\uDE2C\n\nBut here is the code, have a look the idea might just click once you see it (for me often the code helps me a lot)\n\n# Code\n``` JAVA []\nclass Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n int n1 = nums1.length;\n int n2 = nums2.length;\n int n = n1 + n2;\n int[] new_arr = new int[n];\n\n int i=0, j=0, k=0;\n\n while (i<=n1 && j<=n2) {\n if (i == n1) {\n while(j<n2) new_arr[k++] = nums2[j++];\n break;\n } else if (j == n2) {\n while (i<n1) new_arr[k++] = nums1[i++];\n break;\n }\n\n if (nums1[i] < nums2[j]) {\n new_arr[k++] = nums1[i++];\n } else {\n new_arr[k++] = nums2[j++];\n }\n }\n\n if (n%2==0) return (float)(new_arr[n/2-1] + new_arr[n/2])/2;\n else return new_arr[n/2];\n }\n}\n```\n\n## Liked the solution? Why not drop a upvote :D\n\n![upvote_me.jpeg]()\n
309
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
15,761
74
# Comprehensive Guide to Solving "Median of Two Sorted Arrays"\n\n## Introduction & Problem Statement\n\n"Median of Two Sorted Arrays" is a classic problem that tests one\'s algorithmic depth and understanding of binary search and two-pointer techniques. The challenge is to find the median of two sorted arrays, `nums1` and `nums2`, with potentially different sizes. The objective is to solve it in logarithmic time complexity in terms of the minimum size of the two arrays.\n\n## Key Concepts and Constraints\n\n### What Makes This Problem Unique?\n\n1. **Array Constraints**: \n - The length of `nums1` (denoted as $$ m $$) can range from 0 to 1000.\n - The length of `nums2` (denoted as $$ n $$) can also vary between 0 and 1000.\n - The combined size (i.e., $$ m + n $$) of both arrays can go up to 2000.\n \n2. **Element Constraints**:\n - Each element in both `nums1` and `nums2` can be any integer from -$$ 10^6 $$ to $$ 10^6 $$.\n\n3. **Runtime Complexity**: \n The primary challenge is to achieve a runtime of $$ O(\\log(\\min(m, n))) $$. This constraint rules out naive solutions that might merge and then find the median.\n\n### Solution Strategies:\n\n1. **Two Pointers Approach**: \n This technique involves iterating through both arrays using two pointers. By comparing the elements at the current pointers, we can merge the two arrays. Once merged, finding the median is straightforward.\n\n2. **Binary Search Approach**: \n Leveraging the properties of sorted arrays, we can apply a binary search on the smaller array, effectively partitioning both arrays. This method ensures we find the median without explicitly merging the arrays, adhering to the desired logarithmic time complexity.\n\n---\n\n## Live Coding Binary Search & Explain \n\n\n## Strategy to Solve the Problem:\n\n## Two Pointers Merging Technique\n\nThe core idea here is to merge the two sorted arrays, nums1 and nums2, using a two-pointer approach. After merging, the median of the combined array can be found directly based on its length.\n\n## Key Data Structures:\n\n- `merged`: An array to store the merged result of `nums1` and `nums2`.\n- `i` and `j`: Two pointers to traverse `nums1` and `nums2` respectively.\n\n## Enhanced Breakdown:\n\n1. **Initialize Pointers**:\n - Set `i` and `j` to 0. These pointers will help traverse `nums1` and `nums2`.\n\n2. **Merging using Two Pointers**:\n - Merge elements of `nums1` and `nums2` in sorted order using two pointers. If an element in `nums1` is smaller, append it to `merged` and move the `i` pointer. Otherwise, append the element from `nums2` and move the `j` pointer.\n\n3. **Handle Remaining Elements**:\n - If there are any remaining elements in `nums1` or `nums2`, append them directly to `merged`.\n\n4. **Calculate Median**:\n - Based on the length of `merged`, compute the median. If the length is even, the median is the average of the two middle elements. Otherwise, it\'s the middle element.\n\n## Complexity Analysis:\n\n**Time Complexity**: \n- The merging process traverses both arrays once, resulting in a time complexity of $$ O(m + n) $$, where $$ m $$ and $$ n $$ are the lengths of `nums1` and `nums2` respectively.\n\n**Space Complexity**: \n- The algorithm creates a merged array of length $$ m + n $$, leading to a space complexity of $$ O(m + n) $$.\n\n\n## Code Two Pointers\n``` Python []\nclass Solution:\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n merged = []\n i, j = 0, 0\n \n while i < len(nums1) and j < len(nums2):\n if nums1[i] < nums2[j]:\n merged.append(nums1[i])\n i += 1\n else:\n merged.append(nums2[j])\n j += 1\n \n while i < len(nums1):\n merged.append(nums1[i])\n i += 1\n \n while j < len(nums2):\n merged.append(nums2[j])\n j += 1\n \n mid = len(merged) // 2\n if len(merged) % 2 == 0:\n return (merged[mid-1] + merged[mid]) / 2\n else:\n return merged[mid]\n\n```\n``` Go []\nfunc findMedianSortedArrays(nums1 []int, nums2 []int) float64 {\n merged := make([]int, 0, len(nums1)+len(nums2))\n i, j := 0, 0\n\n for i < len(nums1) && j < len(nums2) {\n if nums1[i] < nums2[j] {\n merged = append(merged, nums1[i])\n i++\n } else {\n merged = append(merged, nums2[j])\n j++\n }\n }\n\n for i < len(nums1) {\n merged = append(merged, nums1[i])\n i++\n }\n for j < len(nums2) {\n merged = append(merged, nums2[j])\n j++\n }\n\n mid := len(merged) / 2\n if len(merged)%2 == 0 {\n return (float64(merged[mid-1]) + float64(merged[mid])) / 2.0\n } else {\n return float64(merged[mid])\n }\n}\n```\n``` Rust []\nimpl Solution {\n pub fn find_median_sorted_arrays(nums1: Vec<i32>, nums2: Vec<i32>) -> f64 {\n let mut merged: Vec<i32> = Vec::new();\n let (mut i, mut j) = (0, 0);\n \n while i < nums1.len() && j < nums2.len() {\n if nums1[i] < nums2[j] {\n merged.push(nums1[i]);\n i += 1;\n } else {\n merged.push(nums2[j]);\n j += 1;\n }\n }\n \n while i < nums1.len() {\n merged.push(nums1[i]);\n i += 1;\n }\n while j < nums2.len() {\n merged.push(nums2[j]);\n j += 1;\n }\n \n let mid = merged.len() / 2;\n if merged.len() % 2 == 0 {\n return (merged[mid-1] + merged[mid]) as f64 / 2.0;\n } else {\n return merged[mid] as f64;\n }\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n vector<int> merged;\n int i = 0, j = 0;\n \n while (i < nums1.size() && j < nums2.size()) {\n if (nums1[i] < nums2[j]) {\n merged.push_back(nums1[i++]);\n } else {\n merged.push_back(nums2[j++]);\n }\n }\n \n while (i < nums1.size()) merged.push_back(nums1[i++]);\n while (j < nums2.size()) merged.push_back(nums2[j++]);\n \n int mid = merged.size() / 2;\n if (merged.size() % 2 == 0) {\n return (merged[mid-1] + merged[mid]) / 2.0;\n } else {\n return merged[mid];\n }\n }\n};\n```\n``` Java []\npublic class Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n List<Integer> merged = new ArrayList<>();\n int i = 0, j = 0;\n \n while (i < nums1.length && j < nums2.length) {\n if (nums1[i] < nums2[j]) {\n merged.add(nums1[i++]);\n } else {\n merged.add(nums2[j++]);\n }\n }\n \n while (i < nums1.length) merged.add(nums1[i++]);\n while (j < nums2.length) merged.add(nums2[j++]);\n \n int mid = merged.size() / 2;\n if (merged.size() % 2 == 0) {\n return (merged.get(mid-1) + merged.get(mid)) / 2.0;\n } else {\n return merged.get(mid);\n }\n }\n}\n```\n``` C# []\npublic class Solution {\n public double FindMedianSortedArrays(int[] nums1, int[] nums2) {\n List<int> merged = new List<int>();\n int i = 0, j = 0;\n \n while (i < nums1.Length && j < nums2.Length) {\n if (nums1[i] < nums2[j]) {\n merged.Add(nums1[i++]);\n } else {\n merged.Add(nums2[j++]);\n }\n }\n \n while (i < nums1.Length) merged.Add(nums1[i++]);\n while (j < nums2.Length) merged.Add(nums2[j++]);\n \n int mid = merged.Count / 2;\n if (merged.Count % 2 == 0) {\n return (merged[mid-1] + merged[mid]) / 2.0;\n } else {\n return merged[mid];\n }\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nvar findMedianSortedArrays = function(nums1, nums2) {\n let merged = [];\n let i = 0, j = 0;\n\n while (i < nums1.length && j < nums2.length) {\n if (nums1[i] < nums2[j]) {\n merged.push(nums1[i++]);\n } else {\n merged.push(nums2[j++]);\n }\n }\n\n while (i < nums1.length) merged.push(nums1[i++]);\n while (j < nums2.length) merged.push(nums2[j++]);\n\n let mid = Math.floor(merged.length / 2);\n if (merged.length % 2 === 0) {\n return (merged[mid-1] + merged[mid]) / 2;\n } else {\n return merged[mid];\n }\n};\n```\n``` PHP []\nclass Solution {\n\n function findMedianSortedArrays($nums1, $nums2) {\n $merged = array();\n $i = $j = 0;\n\n while ($i < count($nums1) && $j < count($nums2)) {\n if ($nums1[$i] < $nums2[$j]) {\n array_push($merged, $nums1[$i++]);\n } else {\n array_push($merged, $nums2[$j++]);\n }\n }\n\n while ($i < count($nums1)) array_push($merged, $nums1[$i++]);\n while ($j < count($nums2)) array_push($merged, $nums2[$j++]);\n\n $mid = intdiv(count($merged), 2);\n if (count($merged) % 2 == 0) {\n return ($merged[$mid-1] + $merged[$mid]) / 2;\n } else {\n return $merged[$mid];\n }\n }\n}\n```\n\n---\n\n## Binary Search with Partitioning\n\nThe problem can be elegantly solved using binary search by partitioning the two arrays such that elements on the left are smaller or equal to elements on the right.\n\n## Key Data Structures:\n\n- `partitionX` and `partitionY`: To store the partition indices for `nums1` and `nums2` respectively.\n- `maxX`, `minX`, `maxY`, `minY`: To store the values around the partition in both arrays.\n\n## Enhanced Breakdown:\n\n1. **Initialize and Swap Arrays if Needed**:\n - Swap `nums1` and `nums2` if `nums1` is larger. This ensures we always binary search the smaller array, optimizing the time complexity.\n\n2. **Binary Search Setup**:\n - Initialize `low` to 0 and `high` to the size of the smaller array.\n \n3. **Start Binary Search Loop**:\n - The loop continues until `low` is not greater than `high`.\n - Calculate `partitionX` and `partitionY` based on `low` and `high`.\n\n4. **Calculate Partition Values**:\n - Compute `maxX`, `minX`, `maxY`, `minY` based on the partitions.\n \n5. **Check for Correct Partition**:\n - If `maxX <= minY` and `maxY <= minX`, we have found the correct partition.\n - Calculate and return the median based on the values around the partition.\n\n6. **Adjust Binary Search Bounds**:\n - If `maxX > minY`, adjust `high` to `partitionX - 1`.\n - Otherwise, adjust `low` to `partitionX + 1`.\n\n## Complexity Analysis:\n\n**Time Complexity**: \n- The algorithm performs a binary search on the smaller array, leading to a time complexity of $$ O(\\log(\\min(m, n))) $$.\n\n**Space Complexity**: \n- The algorithm uses only a constant amount of extra space, thus having a space complexity of $$ O(1) $$.\n\n# Code Binary Search\n``` Python []\nclass Solution:\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n if len(nums1) > len(nums2):\n nums1, nums2 = nums2, nums1\n \n m, n = len(nums1), len(nums2)\n low, high = 0, m\n \n while low <= high:\n partitionX = (low + high) // 2\n partitionY = (m + n + 1) // 2 - partitionX\n \n maxX = float(\'-inf\') if partitionX == 0 else nums1[partitionX - 1]\n maxY = float(\'-inf\') if partitionY == 0 else nums2[partitionY - 1]\n minX = float(\'inf\') if partitionX == m else nums1[partitionX]\n minY = float(\'inf\') if partitionY == n else nums2[partitionY]\n \n if maxX <= minY and maxY <= minX:\n if (m + n) % 2 == 0:\n return (max(maxX, maxY) + min(minX, minY)) / 2\n else:\n return max(maxX, maxY)\n elif maxX > minY:\n high = partitionX - 1\n else:\n low = partitionX + 1\n```\n``` Go []\nfunc findMedianSortedArrays(nums1 []int, nums2 []int) float64 {\n\tif len(nums1) > len(nums2) {\n\t\tnums1, nums2 = nums2, nums1\n\t}\n\n\tm, n := len(nums1), len(nums2)\n\tlow, high := 0, m\n\n\tfor low <= high {\n\t\tpartitionX := (low + high) / 2\n\t\tpartitionY := (m + n + 1) / 2 - partitionX\n\n\t\tmaxX := math.MinInt64\n\t\tif partitionX > 0 {\n\t\t\tmaxX = nums1[partitionX-1]\n\t\t}\n\n\t\tminX := math.MaxInt64\n\t\tif partitionX < m {\n\t\t\tminX = nums1[partitionX]\n\t\t}\n\n\t\tmaxY := math.MinInt64\n\t\tif partitionY > 0 {\n\t\t\tmaxY = nums2[partitionY-1]\n\t\t}\n\n\t\tminY := math.MaxInt64\n\t\tif partitionY < n {\n\t\t\tminY = nums2[partitionY]\n\t\t}\n\n\t\tif maxX <= minY && maxY <= minX {\n\t\t\tif (m+n)%2 == 0 {\n\t\t\t\treturn (float64(max(maxX, maxY)) + float64(min(minX, minY))) / 2.0\n\t\t\t}\n\t\t\treturn float64(max(maxX, maxY))\n\t\t} else if maxX > minY {\n\t\t\thigh = partitionX - 1\n\t\t} else {\n\t\t\tlow = partitionX + 1\n\t\t}\n\t}\n\n\treturn 0.0\n}\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n```\n``` Rust []\nimpl Solution {\n pub fn find_median_sorted_arrays(nums1: Vec<i32>, nums2: Vec<i32>) -> f64 {\n let (mut nums1, mut nums2) = if nums1.len() > nums2.len() {\n (nums2, nums1)\n } else {\n (nums1, nums2)\n };\n \n let (m, n) = (nums1.len(), nums2.len());\n let (mut low, mut high) = (0, m);\n \n while low <= high {\n let partition_x = (low + high) / 2;\n let partition_y = (m + n + 1) / 2 - partition_x;\n \n let max_x = if partition_x == 0 { i32::MIN } else { nums1[partition_x - 1] };\n let min_x = if partition_x == m { i32::MAX } else { nums1[partition_x] };\n \n let max_y = if partition_y == 0 { i32::MIN } else { nums2[partition_y - 1] };\n let min_y = if partition_y == n { i32::MAX } else { nums2[partition_y] };\n \n if max_x <= min_y && max_y <= min_x {\n if (m + n) % 2 == 0 {\n return (max_x.max(max_y) + min_x.min(min_y)) as f64 / 2.0;\n } else {\n return max_x.max(max_y) as f64;\n }\n } else if max_x > min_y {\n high = partition_x - 1;\n } else {\n low = partition_x + 1;\n }\n }\n \n 0.0\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n if (nums1.size() > nums2.size()) {\n swap(nums1, nums2);\n }\n \n int m = nums1.size();\n int n = nums2.size();\n int low = 0, high = m;\n \n while (low <= high) {\n int partitionX = (low + high) / 2;\n int partitionY = (m + n + 1) / 2 - partitionX;\n \n int maxX = (partitionX == 0) ? INT_MIN : nums1[partitionX - 1];\n int maxY = (partitionY == 0) ? INT_MIN : nums2[partitionY - 1];\n \n int minX = (partitionX == m) ? INT_MAX : nums1[partitionX];\n int minY = (partitionY == n) ? INT_MAX : nums2[partitionY];\n \n if (maxX <= minY && maxY <= minX) {\n if ((m + n) % 2 == 0) {\n return (max(maxX, maxY) + min(minX, minY)) / 2.0;\n } else {\n return max(maxX, maxY);\n }\n } else if (maxX > minY) {\n high = partitionX - 1;\n } else {\n low = partitionX + 1;\n }\n }\n \n throw invalid_argument("Input arrays are not sorted.");\n }\n};\n```\n``` Java []\npublic class Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n if (nums1.length > nums2.length) {\n int[] temp = nums1;\n nums1 = nums2;\n nums2 = temp;\n }\n \n int m = nums1.length;\n int n = nums2.length;\n int low = 0, high = m;\n \n while (low <= high) {\n int partitionX = (low + high) / 2;\n int partitionY = (m + n + 1) / 2 - partitionX;\n \n int maxX = (partitionX == 0) ? Integer.MIN_VALUE : nums1[partitionX - 1];\n int maxY = (partitionY == 0) ? Integer.MIN_VALUE : nums2[partitionY - 1];\n \n int minX = (partitionX == m) ? Integer.MAX_VALUE : nums1[partitionX];\n int minY = (partitionY == n) ? Integer.MAX_VALUE : nums2[partitionY];\n \n if (maxX <= minY && maxY <= minX) {\n if ((m + n) % 2 == 0) {\n return (Math.max(maxX, maxY) + Math.min(minX, minY)) / 2.0;\n } else {\n return Math.max(maxX, maxY);\n }\n } else if (maxX > minY) {\n high = partitionX - 1;\n } else {\n low = partitionX + 1;\n }\n }\n \n throw new IllegalArgumentException("Input arrays are not sorted.");\n }\n}\n```\n``` C# []\npublic class Solution {\n public double FindMedianSortedArrays(int[] nums1, int[] nums2) {\n if (nums1.Length > nums2.Length) {\n int[] temp = nums1;\n nums1 = nums2;\n nums2 = temp;\n }\n \n int m = nums1.Length;\n int n = nums2.Length;\n int low = 0, high = m;\n \n while (low <= high) {\n int partitionX = (low + high) / 2;\n int partitionY = (m + n + 1) / 2 - partitionX;\n \n int maxX = (partitionX == 0) ? int.MinValue : nums1[partitionX - 1];\n int maxY = (partitionY == 0) ? int.MinValue : nums2[partitionY - 1];\n \n int minX = (partitionX == m) ? int.MaxValue : nums1[partitionX];\n int minY = (partitionY == n) ? int.MaxValue : nums2[partitionY];\n \n if (maxX <= minY && maxY <= minX) {\n if ((m + n) % 2 == 0) {\n return (Math.Max(maxX, maxY) + Math.Min(minX, minY)) / 2.0;\n } else {\n return Math.Max(maxX, maxY);\n }\n } else if (maxX > minY) {\n high = partitionX - 1;\n } else {\n low = partitionX + 1;\n }\n }\n \n throw new ArgumentException("Input arrays are not sorted.");\n }\n}\n```\n``` JavaScript []\nvar findMedianSortedArrays = function(nums1, nums2) {\n if (nums1.length > nums2.length) {\n [nums1, nums2] = [nums2, nums1];\n }\n \n const m = nums1.length;\n const n = nums2.length;\n let low = 0, high = m;\n \n while (low <= high) {\n const partitionX = Math.floor((low + high) / 2);\n const partitionY = Math.floor((m + n + 1) / 2) - partitionX;\n \n const maxX = (partitionX === 0) ? Number.MIN_SAFE_INTEGER : nums1[partitionX - 1];\n const maxY = (partitionY === 0) ? Number.MIN_SAFE_INTEGER : nums2[partitionY - 1];\n \n const minX = (partitionX === m) ? Number.MAX_SAFE_INTEGER : nums1[partitionX];\n const minY = (partitionY === n) ? Number.MAX_SAFE_INTEGER : nums2[partitionY];\n \n if (maxX <= minY && maxY <= minX) {\n if ((m + n) % 2 === 0) {\n return (Math.max(maxX, maxY) + Math.min(minX, minY)) / 2;\n } else {\n return Math.max(maxX, maxY);\n }\n } else if (maxX > minY) {\n high = partitionX - 1;\n } else {\n low = partitionX + 1;\n }\n }\n \n throw new Error("Input arrays are not sorted.");\n};\n```\n``` PHP []\nclass Solution {\n function findMedianSortedArrays($nums1, $nums2) {\n if (count($nums1) > count($nums2)) {\n list($nums1, $nums2) = [$nums2, $nums1];\n }\n \n $m = count($nums1);\n $n = count($nums2);\n $low = 0; $high = $m;\n \n while ($low <= $high) {\n $partitionX = intdiv($low + $high, 2);\n $partitionY = intdiv($m + $n + 1, 2) - $partitionX;\n \n $maxX = ($partitionX == 0) ? PHP_INT_MIN : $nums1[$partitionX - 1];\n $maxY = ($partitionY == 0) ? PHP_INT_MIN : $nums2[$partitionY - 1];\n \n $minX = ($partitionX == $m) ? PHP_INT_MAX : $nums1[$partitionX];\n $minY = ($partitionY == $n) ? PHP_INT_MAX : $nums2[$partitionY];\n \n if ($maxX <= $minY && $maxY <= $minX) {\n if (($m + $n) % 2 == 0) {\n return (max($maxX, $maxY) + min($minX, $minY)) / 2.0;\n } else {\n return max($maxX, $maxY);\n }\n } elseif ($maxX > $minY) {\n $high = $partitionX - 1;\n } else {\n $low = $partitionX + 1;\n }\n }\n \n throw new Exception("Input arrays are not sorted.");\n }\n}\n```\n\n## Performance\n\n| Language | Execution Time (ms) | Memory Usage (MB) |\n|-----------|---------------------|--------------------|\n| Rust | 0 | 2 |\n| Java | 1 | 44.5 |\n| Go | 9 | 5.1 |\n| C++ | 16 | 89.6 |\n| PHP | 28 | 18.9 |\n| Python3 | 80 | 16.5 |\n| JavaScript| 85 | 46.6 |\n| Python3 (Two Pointers) | 93 | 16.5 |\n| C# | 98 | 52.1 |\n\n![v45.png]()\n\n\n## Live Coding in Rust - 0 ms \n\n\n## Conclusion\n\nBoth strategies have their own unique benefits. While the two-pointers approach offers simplicity and clarity, the binary search approach showcases efficiency and mastery over the properties of sorted arrays. Choosing between them depends on the specific constraints and requirements of a given scenario.
328
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
404,445
1,877
This problem is notoriously hard to implement due to all the corner cases. Most implementations consider odd-lengthed and even-lengthed arrays as two different cases and treat them separately. As a matter of fact, with a little mind twist. These two cases can be combined as one, leading to a very simple solution where (almost) no special treatment is needed.\n\nFirst, let\'s see the concept of \'MEDIAN\' in a slightly unconventional way. That is: \n\n> "**if we cut the sorted array to two halves of EQUAL LENGTHS, then\n> median is the AVERAGE OF Max(lower_half) and Min(upper_half), i.e. the\n> two numbers immediately next to the cut**".\n\nFor example, for [2 3 5 7], we make the cut between 3 and 5:\n\n [2 3 / 5 7]\n\nthen the median = (3+5)/2. **Note that I\'ll use \'/\' to represent a cut, and (number / number) to represent a cut made through a number in this article**.\n\nfor [2 3 4 5 6], we make the cut right through 4 like this:\n\n[2 3 (4/4) 5 7]\n\nSince we split 4 into two halves, we say now both the lower and upper subarray contain 4. This notion also leads to the correct answer: (4 + 4) / 2 = 4;\n\nFor convenience, let\'s use L to represent the number immediately left to the cut, and R the right counterpart. In [2 3 5 7], for instance, we have L = 3 and R = 5, respectively. \n\nWe observe the index of L and R have the following relationship with the length of the array N:\n\n N Index of L / R\n 1 0 / 0\n 2 0 / 1\n 3 1 / 1 \n 4 1 / 2 \n 5 2 / 2\n 6 2 / 3\n 7 3 / 3\n 8 3 / 4\n\nIt is not hard to conclude that index of L = (N-1)/2, and R is at N/2. Thus, the median can be represented as \n\n (L + R)/2 = (A[(N-1)/2] + A[N/2])/2\n\n----------------\n\nTo get ready for the two array situation, let\'s add a few imaginary \'positions\' (represented as #\'s) in between numbers, and treat numbers as \'positions\' as well. \n\n [6 9 13 18] -> [# 6 # 9 # 13 # 18 #] (N = 4)\n position index 0 1 2 3 4 5 6 7 8 (N_Position = 9)\n\t\t\t \n [6 9 11 13 18]-> [# 6 # 9 # 11 # 13 # 18 #] (N = 5)\n position index 0 1 2 3 4 5 6 7 8 9 10 (N_Position = 11)\n\nAs you can see, there are always exactly 2*N+1 \'positions\' regardless of length N. Therefore, the middle cut should always be made on the Nth position (0-based). Since index(L) = (N-1)/2 and index(R) = N/2 in this situation, we can infer that **index(L) = (CutPosition-1)/2, index(R) = (CutPosition)/2**. \n\n------------------------\n\nNow for the two-array case:\n\n A1: [# 1 # 2 # 3 # 4 # 5 #] (N1 = 5, N1_positions = 11)\n \n A2: [# 1 # 1 # 1 # 1 #] (N2 = 4, N2_positions = 9)\n\nSimilar to the one-array problem, we need to find a cut that divides the two arrays each into two halves such that \n\n> "any number in the two left halves" <= "any number in the two right\n> halves".\n\nWe can also make the following observations\uFF1A\n\n1. There are 2*N1 + 2*N2 + 2 position altogether. Therefore, there must be exactly N1 + N2 positions on each side of the cut, and 2 positions directly on the cut.\n\n2. Therefore, when we cut at position C2 = K in A2, then the cut position in A1 must be C1 = N1 + N2 - k. For instance, if C2 = 2, then we must have C1 = 4 + 5 - C2 = 7.\n\n [# 1 # 2 # 3 # (4/4) # 5 #] \n \n [# 1 / 1 # 1 # 1 #] \n\n3. When the cuts are made, we\'d have two L\'s and two R\'s. They are\n\n L1 = A1[(C1-1)/2]; R1 = A1[C1/2];\n L2 = A2[(C2-1)/2]; R2 = A2[C2/2];\n\nIn the above example, \n\n L1 = A1[(7-1)/2] = A1[3] = 4; R1 = A1[7/2] = A1[3] = 4;\n L2 = A2[(2-1)/2] = A2[0] = 1; R2 = A1[2/2] = A1[1] = 1;\n\n\nNow how do we decide if this cut is the cut we want? Because L1, L2 are the greatest numbers on the left halves and R1, R2 are the smallest numbers on the right, we only need\n\n L1 <= R1 && L1 <= R2 && L2 <= R1 && L2 <= R2\n\nto make sure that any number in lower halves <= any number in upper halves. As a matter of fact, since \nL1 <= R1 and L2 <= R2 are naturally guaranteed because A1 and A2 are sorted, we only need to make sure:\n\nL1 <= R2 and L2 <= R1.\n\nNow we can use simple binary search to find out the result.\n\n If we have L1 > R2, it means there are too many large numbers on the left half of A1, then we must move C1 to the left (i.e. move C2 to the right); \n If L2 > R1, then there are too many large numbers on the left half of A2, and we must move C2 to the left.\n Otherwise, this cut is the right one. \n After we find the cut, the medium can be computed as (max(L1, L2) + min(R1, R2)) / 2;\n\nTwo side notes: \n\nA. Since C1 and C2 can be mutually determined from each other, we can just move one of them first, then calculate the other accordingly. However, it is much more practical to move C2 (the one on the shorter array) first. The reason is that on the shorter array, all positions are possible cut locations for median, but on the longer array, the positions that are too far left or right are simply impossible for a legitimate cut. For instance, [1], [2 3 4 5 6 7 8]. Clearly the cut between 2 and 3 is impossible, because the shorter array does not have that many elements to balance out the [3 4 5 6 7 8] part if you make the cut this way. Therefore, for the longer array to be used as the basis for the first cut, a range check must be performed. It would be just easier to do it on the shorter array, which requires no checks whatsoever. Also, moving only on the shorter array gives a run-time complexity of O(log(min(N1, N2))) (edited as suggested by @baselRus)\n\nB. The only edge case is when a cut falls on the 0th(first) or the 2*Nth(last) position. For instance, if C2 = 2*N2, then R2 = A2[2*N2/2] = A2[N2], which exceeds the boundary of the array. To solve this problem, we can imagine that both A1 and A2 actually have two extra elements, INT_MAX at A[-1] and INT_MAX at A[N]. These additions don\'t change the result, but make the implementation easier: If any L falls out of the left boundary of the array, then L = INT_MIN, and if any R falls out of the right boundary, then R = INT_MAX.\n\n-----------------\n\nI know that was not very easy to understand, but all the above reasoning eventually boils down to the following concise code:\n\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n int N1 = nums1.size();\n int N2 = nums2.size();\n if (N1 < N2) return findMedianSortedArrays(nums2, nums1);\t// Make sure A2 is the shorter one.\n \n int lo = 0, hi = N2 * 2;\n while (lo <= hi) {\n int mid2 = (lo + hi) / 2; // Try Cut 2 \n int mid1 = N1 + N2 - mid2; // Calculate Cut 1 accordingly\n \n double L1 = (mid1 == 0) ? INT_MIN : nums1[(mid1-1)/2];\t// Get L1, R1, L2, R2 respectively\n double L2 = (mid2 == 0) ? INT_MIN : nums2[(mid2-1)/2];\n double R1 = (mid1 == N1 * 2) ? INT_MAX : nums1[(mid1)/2];\n double R2 = (mid2 == N2 * 2) ? INT_MAX : nums2[(mid2)/2];\n \n if (L1 > R2) lo = mid2 + 1;\t\t// A1\'s lower half is too big; need to move C1 left (C2 right)\n else if (L2 > R1) hi = mid2 - 1;\t// A2\'s lower half too big; need to move C2 left.\n else return (max(L1,L2) + min(R1, R2)) / 2;\t// Otherwise, that\'s the right cut.\n }\n return -1;\n } \nIf you have any suggestions to make the logic and implementation even more cleaner. Please do let me know!
331
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
1,205
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\nclass Solution {\n private:\n int dop_num1(vector<int>& nums1) {\n if (nums1.size() == 0) {\n return 0;\n } else if (nums1.size()/2 > nums1.size() -1 && nums1.size() > 1) {\n return nums1[nums1.size()/2 -1];\n } else {\n return nums1[nums1.size()/2];\n }\n }\n int dop_num2(vector<int>& nums2) {\n if (nums2.size() == 0) {\n return 0;\n } else if (nums2.size() > 1){\n return nums2[nums2.size()/2 - 1];\n } else {\n return nums2[nums2.size()/2];\n }\n }\n\n public:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n vector<int> all;\n all = nums1;\n for (int i = 0; i < nums2.size(); i++) all.push_back(nums2[i]);\n std::sort(all.begin(), all.end());\n if (all.size() % 2 == 0) {\n return (double)(dop_num1(all)+dop_num2(all))/2;\n } else {\n return (double)dop_num1(all);\n } \n }\n};\n```
335
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
2,830
32
# Annnoumement\nWe are statrting leetcode 75 days chellange (25 easy,25 medium ,25 hard)So Join us with this journy on Linkdin and instagram check leetcode profile for that . Let\'s continue our journey of problem-solving and exploration together.\n\n# Intuition\nGiven two sorted arrays nums1 and nums2 of size m and n respectively, return the **median of the two sorted arrays**.\nInput: nums1 = [1,2], nums2 = [3,4]\nOutput: **2.50000**\nExplanation: **merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.**\n\n\n# Approach\nTo find the median of two sorted arrays without extra space, we can optimize by considering only the border elements of the arrays. \n- We have to Calculate the **total number of elements in both arrays** (the sum of their lengths).\n- We have to find how many elements from the first array should appear before the median by subtracting half of the total elements from the number of elements selected from the first array.\n- When we are finding the median, **we have to keep track of two middle elements for an even number of elements or one middle element for an odd number**.\n- During merging, compare border elements (left value of one array with right value of the other). Since** arrays are sorted**, left values will always be less than right values within their respective arrays. This approach saves space and efficiently finds the median.\n\n# Code explaination\nCertainly, here\'s the modified algorithm presented in plain text:\n\n1. First we will Initialize two variables: `l` and `r`, where `l` is set to 0, and `r` is set to `m` (the size of the smaller array).\n\n2. Then we will enter a loop while( `l <= r`)\n\n3. After that In each iteration, partition the range by finding the middle point and select the elements before the partition from the first array, which we\'ll call `fir`. The remaining elements belong to the second array and are called $$\'sec\'$$ here fir means first and sec means second .\n\n4. Determine the values of the border elements of the elements taken from both arrays:\n - `l1`: The leftmost element from the first array.\n - `l2`: The leftmost element from the second array.\n - `r1`: The rightmost element from the first array.\n - `r2`: The rightmost element from the second array.\n\n5. After that We will Compare the border elements to ensure the sorting order of the elements, which means checking if `l1 <= r2` and `l2 <= r1`.\n\n6. If the above condition is true, and the total number of elements in both arrays is even, then calculate the median as follows: `median = (max(l1, l2) + min(r1, r2)) / 2`. Otherwise, if the total number of elements is odd, set `median` to `max(l1, l2)`.\n\n7. If `l1 > r2`, we will reduce the right limit `r` to `fir - 1`.\n\n8. Otherwise, we will increment the left limit `l` to `fir + 1`.\n\n\n# Complexity\n- Time complexity:**O(log(min(m,n)))**\n- Space complexity:**O(1)**\n\n# Code\n```\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n \n int m = nums1.size();\n int n = nums2.size();\n \n if(m > n)\n return findMedianSortedArrays(nums2, nums1);\n \n int l=0, r= m;\n int total = m+n+1;\n \n while(l<=r)\n {\n int fir = l + (r-l)/2;\n int sec = total/2 - fir;\n \n int l1=INT_MIN, l2=INT_MIN;\n int r1=INT_MAX, r2=INT_MAX;\n \n if(fir > 0)\n l1 = nums1[fir-1];\n if(sec>0)\n l2 = nums2[sec-1];\n if((fir>=0) && (fir<m))\n r1 = nums1[fir];\n if((sec>=0) && (sec<n))\n r2 = nums2[sec];\n if(l1<=r2 && l2<=r1){\n if((n+m)%2 == 0)\n return (max(l1, l2)+min(r1, r2))/2.0;\n else\n return max(l1, l2);\n }\n else if(l1> r2)\n r = fir-1;\n else\n l = fir+1;\n } \n return 0; \n }\n};\n```\nIf you really found my solution helpful **please upvote it**, as it motivates me to post such kind of codes.\n**Let me know in comment if i can do better.**\n![upvote.jfif]()
336
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
2,160
34
# Intuition\nWelcome to my article! This starts with `What is median?`. Understanding `median` is a key to solve this quesiton.\n\n---\n\n# Solution Video\n\nToday, I\'m going on business trip. This article is written in a train. lol\nIf I have a time tonight, I will create a solution video for this question.\n\nInstead of the video, I added more comments to the codes.\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\n\n\nSubscribers: 2,423\nMy initial goal is 10,000\nThank you for your support!\n\n---\n\n# Approach\n\n## My thought process - How I think about a solution\n\n### What is `median`?\n\nFirst and foremost, we must understand what `median` is. Without this understanding, we cannot write a program.\n\n`The median is one of the measures of central tendency for data or a set, representing the value that is at the middle position.`\n\n- In the case of an even-sized data set\n\nHowever, in the case of an even-sized data set, the arithmetic mean of the two middle values is taken.\n\nFor example, in a data set consisting of the ages of 6 individuals: `1, 2, 3, 5, 9, 11`, the median is `4 years old` (taking two middle values `3 + 5` and divide by `2`)\n\n- In the case of an odd-sized data set\n\nIn the case of an odd-sized data set, for example, in a data set consisting of the ages of 5 individuals: `10, 32, 96, 100, 105` years old, the median is `96 years old`, which is the value at the 3rd position from both the top and the bottom. If there are 2 more children aged `0`, making a total of 7 individuals `0, 0, 10, 32, 96, 100, 105`, the median becomes `32 years old`.\n\n### My first thought\nNow, I hope you understand what `median` is. Simply, when we convert `median` to program, we can write it like this.\n\nThis is Python code.\n```\nclass Solution:\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n # Merge the two sorted arrays\n merged = sorted(nums1 + nums2)\n length = len(merged)\n \n # Check if the total length is even or odd\n if length % 2 == 0:\n # If even, return the average of the two middle elements\n return (merged[length // 2 - 1] + merged[length // 2]) / 2\n else:\n # If odd, return the middle element\n return merged[length // 2]\n```\nIt\'s very simple right? In fact, this program passed all cases and execution time is not bad. Beats 68% when I ran the code. If we can use this code for this question. this is acutually easy problem.\n\nThat is my first thought.\n\n### We have a constraint\n\nBut we have a constrant about time complexity. Description says "The overall run time complexity should be `O(log(m+n))`", so we can\'t use my simple solution for this question, even if the simple solution passed all cases.\n\nWe need to find another solution.\n\nLet\'s focus on time complexity of the constraint. Time complexity of `O(log(m+n))` is a constraint, on the other hand, it should be a hint to solve the question. If you know time complexity well, you can guess a solution from `O(log(something))`.\n\nThat is time complexity of `binary search`. That\'s why I stated to focus on a binary search-based solution to find the median of two arrays.\n\nThat is my thoguht process to reach `binary search-based solution`.\n\n---\n\n# Solution\n\n### Algorithm overview:\n1. Ensure that nums1 is the smaller array.\n2. Calculate the lengths of the input arrays nums1 and nums2.\n3. Set the initial range for binary search on nums1 using the variables left and right.\n\n### Detailed Explanation:\n1. Check and swap nums1 and nums2 if nums1 is longer than nums2 to ensure nums1 is the smaller array.\n2. Calculate the lengths of nums1 and nums2 and store them in len1 and len2.\n3. Initialize the binary search range using left (0) and right (length of nums1).\n4. Enter a while loop that continues as long as the left pointer is less than or equal to the right pointer.\n5. Inside the loop:\n a. Calculate the partition points for nums1 and nums2 based on the binary search.\n b. Determine the maximum elements on the left side (max_left) and minimum elements on the right side (min_right) for both arrays.\n c. Check if the current partition is correct by comparing max_left and min_right.\n d. If the partition is correct:\n - If the total length is even, return the average of max_left and min_right.\n - If the total length is odd, return max_left.\n e. If the partition is not correct, adjust the binary search range based on the comparison of max_left1 and min_right2.\n\nThis algorithm efficiently finds the median of two sorted arrays using a binary search approach to adjust the partition points and determine the correct position for the median.\n\n\n---\n\n\n# Complexity\n- Time complexity: O(log(min(N, M)))\nThe while loop performs binary search, and each iteration divides the search range in half. Thus, the time complexity is O(log(min(N, M))), where `N` is the length of nums1 and `M` is the length of nums2.\n\n- Space complexity: O(1)\nThe algorithm uses a constant amount of extra space for variables like `left`, `right`, `partition1`, `partition2`, `max_left1`, `max_left2`, `max_left`, `min_right1`, `min_right2`, and `min_right`. Therefore, the space complexity is O(1), indicating constant space usage irrespective of the input size.\n\n\n```python []\nclass Solution:\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n # Ensure nums1 is the smaller array\n if len(nums1) > len(nums2):\n nums1, nums2 = nums2, nums1\n \n # Get the lengths of the two arrays\n len1, len2 = len(nums1), len(nums2)\n \n # Set the range for binary search on nums1\n left, right = 0, len1\n \n while left <= right:\n # Partition nums1 and nums2\n partition1 = (left + right) // 2\n partition2 = (len1 + len2 + 1) // 2 - partition1\n \n # Find the maximum elements on the left of the partition\n max_left1 = nums1[partition1-1] if partition1 > 0 else float(\'-inf\')\n max_left2 = nums2[partition2-1] if partition2 > 0 else float(\'-inf\')\n max_left = max(max_left1, max_left2)\n \n # Find the minimum elements on the right of the partition\n min_right1 = nums1[partition1] if partition1 < len1 else float(\'inf\')\n min_right2 = nums2[partition2] if partition2 < len2 else float(\'inf\')\n min_right = min(min_right1, min_right2)\n \n # Check if the partition is correct\n if max_left <= min_right:\n # If the total length is even, return the average of the two middle elements\n if (len1 + len2) % 2 == 0:\n return (max_left + min_right) / 2\n # If the total length is odd, return the middle element\n else:\n return max_left\n elif max_left1 > min_right2:\n right = partition1 - 1\n else:\n left = partition1 + 1\n```\n```javascript []\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nvar findMedianSortedArrays = function(nums1, nums2) {\n // Ensure nums1 is the smaller array\n if (nums1.length > nums2.length) {\n [nums1, nums2] = [nums2, nums1];\n }\n\n // Get the lengths of the two arrays\n const len1 = nums1.length;\n const len2 = nums2.length;\n\n // Set the range for binary search on nums1\n let left = 0;\n let right = len1;\n\n while (left <= right) {\n // Partition nums1 and nums2\n const partition1 = Math.floor((left + right) / 2);\n const partition2 = Math.floor((len1 + len2 + 1) / 2) - partition1;\n\n // Find the maximum elements on the left of the partition\n const maxLeft1 = partition1 > 0 ? nums1[partition1 - 1] : Number.NEGATIVE_INFINITY;\n const maxLeft2 = partition2 > 0 ? nums2[partition2 - 1] : Number.NEGATIVE_INFINITY;\n const maxLeft = Math.max(maxLeft1, maxLeft2);\n\n // Find the minimum elements on the right of the partition\n const minRight1 = partition1 < len1 ? nums1[partition1] : Number.POSITIVE_INFINITY;\n const minRight2 = partition2 < len2 ? nums2[partition2] : Number.POSITIVE_INFINITY;\n const minRight = Math.min(minRight1, minRight2);\n\n // Check if the partition is correct\n if (maxLeft <= minRight) {\n // If the total length is even, return the average of the two middle elements\n if ((len1 + len2) % 2 === 0) {\n return (maxLeft + minRight) / 2;\n }\n // If the total length is odd, return the middle element\n else {\n return maxLeft;\n }\n } else if (maxLeft1 > minRight2) {\n right = partition1 - 1;\n } else {\n left = partition1 + 1;\n }\n } \n};\n```\n```java []\nclass Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n // Ensure nums1 is the smaller array\n if (nums1.length > nums2.length) {\n int[] temp = nums1;\n nums1 = nums2;\n nums2 = temp;\n }\n\n // Get the lengths of the two arrays\n int len1 = nums1.length;\n int len2 = nums2.length;\n\n // Set the range for binary search on nums1\n int left = 0;\n int right = len1;\n\n while (left <= right) {\n // Partition nums1 and nums2\n int partition1 = (left + right) / 2;\n int partition2 = (len1 + len2 + 1) / 2 - partition1;\n\n // Find the maximum elements on the left of the partition\n int maxLeft1 = partition1 > 0 ? nums1[partition1 - 1] : Integer.MIN_VALUE;\n int maxLeft2 = partition2 > 0 ? nums2[partition2 - 1] : Integer.MIN_VALUE;\n int maxLeft = Math.max(maxLeft1, maxLeft2);\n\n // Find the minimum elements on the right of the partition\n int minRight1 = partition1 < len1 ? nums1[partition1] : Integer.MAX_VALUE;\n int minRight2 = partition2 < len2 ? nums2[partition2] : Integer.MAX_VALUE;\n int minRight = Math.min(minRight1, minRight2);\n\n // Check if the partition is correct\n if (maxLeft <= minRight) {\n // If the total length is even, return the average of the two middle elements\n if ((len1 + len2) % 2 == 0) {\n return (maxLeft + minRight) / 2.0;\n }\n // If the total length is odd, return the middle element\n else {\n return maxLeft;\n }\n } else if (maxLeft1 > minRight2) {\n right = partition1 - 1;\n } else {\n left = partition1 + 1;\n }\n }\n\n return 0.0; // This should not be reached, just to satisfy Java\'s return requirements\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n // Ensure nums1 is the smaller array\n if (nums1.size() > nums2.size()) {\n nums1.swap(nums2);\n }\n\n // Get the lengths of the two arrays\n int len1 = nums1.size();\n int len2 = nums2.size();\n\n // Set the range for binary search on nums1\n int left = 0;\n int right = len1;\n\n while (left <= right) {\n // Partition nums1 and nums2\n int partition1 = (left + right) / 2;\n int partition2 = (len1 + len2 + 1) / 2 - partition1;\n\n // Find the maximum elements on the left of the partition\n int maxLeft1 = partition1 > 0 ? nums1[partition1 - 1] : INT_MIN;\n int maxLeft2 = partition2 > 0 ? nums2[partition2 - 1] : INT_MIN;\n int maxLeft = max(maxLeft1, maxLeft2);\n\n // Find the minimum elements on the right of the partition\n int minRight1 = partition1 < len1 ? nums1[partition1] : INT_MAX;\n int minRight2 = partition2 < len2 ? nums2[partition2] : INT_MAX;\n int minRight = min(minRight1, minRight2);\n\n // Check if the partition is correct\n if (maxLeft <= minRight) {\n // If the total length is even, return the average of the two middle elements\n if ((len1 + len2) % 2 == 0) {\n return (maxLeft + minRight) / 2.0;\n }\n // If the total length is odd, return the middle element\n else {\n return maxLeft;\n }\n } else if (maxLeft1 > minRight2) {\n right = partition1 - 1;\n } else {\n left = partition1 + 1;\n }\n }\n\n return 0.0; // This should not be reached, just to satisfy C++\'s return requirements \n }\n};\n```\n\n---\n\n\nThank you for reading such a long article.\n\n\u2B50\uFE0F If you learn something from the article, please upvote it and don\'t forget to subscribe to my channel!\n\nMy next post for daily coding challenge on Sep 22, 2023\n\n
345
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
2,042
5
# Approach\nBinary Search\n\n# Complexity\n- Time complexity:\n$$O(log(min(n1,n2))$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n int n1 = nums1.size(), n2 = nums2.size();\n if (n1 > n2)\n return findMedianSortedArrays(nums2, nums1);\n \n int low = 0, high = n1;\n while (low <= high) {\n int cut1 = (low + high) / 2;\n int cut2 = (n1 + n2 + 1) / 2 - cut1;\n\n int left1 = (cut1 == 0) ? -1e7 : nums1[cut1 - 1];\n int left2 = (cut2 == 0) ? -1e7 : nums2[cut2 - 1];\n int right1 = (cut1 == n1) ? 1e7 : nums1[cut1];\n int right2 = (cut2 == n2) ? 1e7 : nums2[cut2];\n\n if (left1 <= right2 && left2 <= right1) {\n if ((n1 + n2) % 2 == 1)\n return max (left1, left2);\n else\n return (max (left1, left2) + min (right1, right2)) / 2.0; \n } \n else if (left1 > right2) \n high = cut1 - 1;\n else \n low = cut1 + 1;\n } \n return 0.0;\n }\n};\n```
346
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
3,339
17
# Intuition\nFirst ever Hard problem which i solved in my life so if you like it then please upvote\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n int n1 =nums1.size(),n2=nums2.size(),count =0;\n float sum;\n map<int, int> m;\n vector<int> v;\n for(int i=0;i<n1;i++){\n v.push_back(nums1[i]);\n }\n for(int i=0;i<n2;i++){\n v.push_back(nums2[i]);\n }\n sort(v.begin(),v.end()); \n for(auto i:v){\n count++;\n }\n float n= v.size();\n int start =0, end = n-1;\n float mid =start + (end -start)/2;\n if (count%2==1){\n \n return v[mid];\n }\n \n else if(count%2==0){\n float sum = (float)((v[mid])+(v[mid+1]))/2;\n return sum; \n }\n \n return {};\n }\n};\n```\n![upvote 1.jpeg]()\n\n\n
349
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
1,797
6
**Connect with me on LinkedIn**: \n\n<b>Linear Search</b>\n```\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& a, vector<int>& b) {\n int n=a.size(), m=b.size();\n int len=n+m;\n \n int i=0, j=0, k=0;\n bool found_first=false, found_second=false;\n int first, second;\n while(i<n || j<m){\n k++; // length of merged array\n int val1 = (i<n ? a[i]:INT_MAX);\n int val2 = (j<m ? b[j]:INT_MAX);\n \n int cur;\n if(val1<=val2){\n cur=val1;\n i++;\n }else{\n cur=val2;\n j++;\n }\n \n if(len%2 && k==(len+1)/2) return cur;\n if(len%2==0){\n if(k==len/2) first=cur, found_first=true;\n if(k==len/2 +1) second=cur, found_second=true;\n \n if(found_first && found_second) return (first + second)/(double)2;\n }\n }\n \n return -1;\n }\n};\n```\n\n<b>Binary Search</b>\n```\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int> &a, vector<int> &b) {\n if(b.size() < a.size()) return findMedianSortedArrays(b,a); // to reduce range for Binary Seacrh \n int n=a.size(), m=b.size();\n \n int low=0, high=n;\n \n while(low<=high){\n int cut1=(high+low)/2; // no. of elements taken on left from a\n int cut2=(n+m+1)/2 - cut1; // no. of elements taken on left from b\n \n int left1=(cut1==0 ? INT_MIN:a[cut1-1]);\n int left2=(cut2==0 ? INT_MIN:b[cut2-1]);\n int right1=(cut1==n ? INT_MAX:a[cut1]);\n int right2=(cut2==m ? INT_MAX:b[cut2]);\n \n // left1<=right2 && left2<=right1\n if(max(left1, left2) <= min(right1, right2)){\n if((n+m)%2==0) return (max(left1,left2)+min(right1,right2))/2.0;\n return max(left1,left2);\n }else if(left1>right2){\n high=cut1-1;\n }else{\n low=cut1+1;\n }\n }\n return 0.0;\n }\n};\n```
352
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
9
7
\n# Code\n```\nclass Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n int m = nums1.length;\n int n = nums2.length;\n List<Integer> ls = new ArrayList<>();\n int i = 0, j = 0;\n \n while (i < m && j < n) {\n if (nums1[i] < nums2[j]) {\n ls.add(nums1[i++]);\n } else {\n ls.add(nums2[j++]);\n }\n }\n \n while (i < m) ls.add(nums1[i++]);\n while (j < n) ls.add(nums2[j++]);\n\n int mid = ls.size()/2;\n if(ls.size() % 2 == 0){\n return (ls.get(mid-1) + ls.get(mid))/2.0;\n }else{\n return ls.get(mid);\n }\n }\n}\n```
353
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
697
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nvar findMedianSortedArrays = function(nums1, nums2) {\n let fullsorted =[]\n\n if(nums1.length >=1 && nums2.length >=1){\n fullsorted = [...nums1,...nums2]\n fullsorted = fullsorted.sort((a,b)=>a-b)\n }else{\n if(nums1.length ==0){\n fullsorted =[...nums2]\n }\n else if(nums2.length ==0){\n fullsorted=[...nums1]\n }\n }\n \n \n if(fullsorted.length%2 ===1){\n return fullsorted[(fullsorted.length-1)/2]\n }else{\n let mean = (fullsorted[(fullsorted.length/2)-1] + fullsorted[(fullsorted.length/2)])/2\n\n return mean\n }\n};\n```
354
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
909
6
\n# Code\n```\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n int n = nums1.size();\n int m = nums2.size();\n if(n > m) return findMedianSortedArrays(nums2,nums1);\n\n int half = (n+m+1)/2;\n int left = 0;\n int right = n;\n\n while(left<= right){\n int mid = left + (right-left)/2;\n int lefA = mid;\n int lefB = half-mid;\n int leftA = (lefA > 0)?nums1[lefA-1]:INT_MIN;\n int leftB = (lefB > 0)?nums2[lefB-1]:INT_MIN;\n int rightA = (lefA <n)?nums1[lefA]:INT_MAX;\n int rightB = (lefB < m)?nums2[lefB]:INT_MAX;\n\n if(leftA <= rightB && leftB <= rightA) {\n if((n+m)%2 == 0) {\n double ans = max(leftA,leftB)+min(rightA,rightB);\n \n return ans/double(2); }\n return max(leftA,leftB);\n }\n else if(leftA > rightB) right = mid-1;\n else left = mid +1;\n }\n return 0;\n }\n};\n```
355
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
4,924
12
\n public int findKth(int[] nums1, int s1, int[] nums2, int s2, int k) {\n if (s1 >= nums1.length) {\n return nums2[s2 + k - 1];\n } \n if (s2 >= nums2.length) {\n return nums1[s1 + k - 1];\n }\n if (k == 1) {\n return Math.min(nums1[s1], nums2[s2]);\n }\n int m1 = s1 + k / 2 - 1;\n int m2 = s2 + k / 2 - 1;\n int mid1 = 0;\n int mid2 = 0;\n if (m1 >= nums1.length) {\n mid1 = Integer.MAX_VALUE;\n }\n else {\n mid1 = nums1[m1];\n }\n if (m2 >= nums2.length) {\n mid2 = Integer.MAX_VALUE;\n }\n else {\n mid2 = nums2[m2];\n }\n if (mid1 < mid2) {\n return findKth(nums1, m1 + 1, nums2, s2, k - k/2);\n }\n else {\n return findKth(nums1, s1, nums2, m2 + 1, k - k/2);\n }\n }\n\tpublic double findMedianSortedArrays(int[] nums1, int[] nums2) {\n int n = nums1.length + nums2.length;\n int one = findKth(nums1, 0, nums2, 0, (n + 1)/2);\n int two = findKth(nums1, 0, nums2, 0, (n + 2)/2);\n return ((double)one + (double)two )/ 2.0;\n }\n\n\n\t\n\n\n\t\n\t\n\t
362
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
3,056
22
# Problem Description\nGiven two sorted arrays, `nums1` and `nums2`, each of sizes `M` and `N` respectively. The **goal** is to find the **median** of the **combined** array formed by merging `nums1` and `nums2`.\n\nThe **task** is to design an algorithm with an overall run time complexity of `O(log(min(m, n)))` to calculate the median of the combined sorted array.\n\n**The median** of an array is the **middle** element when the array is **sorted**. If the combined array has an even number of elements, the median is the **average** of the two middle elements.\n\n![image.png]()\n\n\n\n---\n\n\n# Intuition\nHello There\uD83D\uDE00\nLet\'s take a look on our today\'s interesting problem\uD83D\uDE80\n\nIn our today\'s problem we have, two **sorted** arrays and a **median** to find but the **median** is for the array that **results** from **merging** both of the arrays.\nSounds like a **neat** problem.\uD83E\uDD29\n\n## Two Pointers\nThe **first** solution that would pop in mind is Why don\'t we **merge** the two arrays.\uD83E\uDD14\nWe can do this in **linear** time since the two arrays are **sorted** then we will have `2` pointer each of them on a **different** array from the other and put the **smaller** number in the **available** position in our **new** array.\n![image.png]()\n\nThe **tricky** part here that this solution has **complexity** of `O(m + n)` and still get **accepted** although the problem said it wants an algorithm with `O(log(min(m, n)))`\uD83E\uDD2F\nBut I had `100%` solution in **Java** with **Two Pointers** solution exactly like the next solution that I will discuss.\n\n\n\n## Divide And Conquer\n\n**Divide and Conquer** in a great technique in the world of computer science.\uD83D\uDE80\nIt **shares** something important with **dynamic programming** that both of them **break** the problem into smaller **subproblems**.\nThe **diffrenece** between the two approaches that the subproblems are **independent** in divide and conquer but in dynamic programming there is some **overlapping** between the subproblems.\uD83E\uDD2F\n\n- The **essence** of this solution that two things :\n - **drop** the part of the two arrays that we are sure that our median **won\'t be in it**.\n - **choose** the median when one array has **no elements** in it.\n\nlet\'s look at the **base case**, when we have one array is **empty**\nif you have two arrays `a` , `b` and I told you to get the median of their merge like that:\n```\n-> a = [1, 4, 10]\n-> b = []\n\n-> index median of a + b = 1\n-> median of a + b = 4\n``` \nWe can note here that since `b` is empty then the median is in a with the same **index** we are searching for.\uD83E\uDD2F\n\nLet\'s look at another example:\n```\n-> a = [1, 4, 10]\n-> b = [2, 4, 7, 15]\n-> index median of a + b = 3\n-> mid of a = 1\n-> mid of b = 2\n```\n```\nnew a and b to search in:\n-> a = [1, 4, 10]\n-> b = [2, 4]\n-> index median of a + b = 3\n-> mid of a = 1\n-> mid of b = 1\n```\n```\nnew a and b to search in\n-> a = [10]\n-> b = [2, 4]\n-> index median of a + b = 1\n-> mid of a = 0\n-> mid of b = 1\n```\n```\nnew a and b to search in\n-> a = []\n-> b = [2, 4]\n-> index median of a + b = 1\n```\nWow, we can see now we reached our **base** case that a is **empty** then the solution is the `1` **index** of our new array of b which is `4`.\n\nWe can see in the last example that we applied divide and conquer by **dropping** the **half** of the array that we are sure that our median won\'t be inside it then recursively search in our new arrays until we reach our base case.\uD83D\uDE80\n\nAnd this is the solution for our today problem I hope that you understood it\uD83D\uDE80\uD83D\uDE80\n\n\n---\n# Approach\n## 1. Two Pointers\n1. **Create** a new array `mergedArray` with a size equal to the **sum** of the sizes of `nums1` and `nums2`.\n2. **Initialize** two pointers `idxNums1` and `idxNums2` to `0`, representing the indices for `nums1` and `nums2`.\n3. **Iterate** through mergedArray from `0` to its `size`.\n - **Compare** the elements pointed by `idxNums1` in `nums1` and `idxNums2` in `nums2`.\n - Place the **smaller** element in `mergedArray` and **increment** the respective pointer (`idxNums1` or `idxNums2`).\n4. Check if the **size** of `mergedArray` is **odd** or **even**.\n - If **odd**, return the **middle** element of `mergedArray`.\n - If **even**, return the **average** of the two middle elements in `mergedArray`.\n\n## Complexity\n- **Time complexity:** $$O(N + M)$$ \nSince we are iterating over the big array which has size of `N + M`.\n- **Space complexity:** $$O(N + M)$$\nSince we are storing the new merged array with size of `N + M`.\n\n\n---\n\n## 2. Divide And Conquer\n1. **findKthElement** Function.\n - Handle **base cases** where one of the arrays is **exhausted**.\n - Return the kth element from the remaining array accordingly.\n - **Calculate** mid indices for both arrays to divide and conquer.\n - Based on mid elements, decide which **portion** of the arrays to **discard** and recurse accordingly.\n2. **findMedianSortedArrays** Function.\n - Calculate the **total size** of the merged arrays. \n - If the total size is **odd**, return the kth element where `k = total_size // 2`.\n - If the total size is **even**, find the `kth and (kth - 1)` elements and return their **average**.\n\n## Complexity\n- **Time complexity:** $$O(log(min(M, N)))$$ \nThe **logarithmic** term is because we are using **Divide And Conquer** then each call we divide the size of the two arrays into half.\nThe **minimum** term since the base case is when the size of one of the arrays is `0` and the array which will be faster to reach `0` is the smaller array which is `min(M, N)`\nSo total complexity is `O(log(min(M, N)))` .\n- **Space complexity:** $$O(1)$$\nSince we are only store constant number of variables then complexity is `O(1)`.\n\n\n\n---\n\n\n\n# Code\n## 1. Two Pointers\n```C++ []\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n // Merge the sorted arrays into a single array\n vector<int> mergedArray(nums1.size() + nums2.size());\n \n int idxNums1 = 0; // Index for nums1\n int idxNums2 = 0; // Index for nums2\n \n // Merge the arrays while maintaining the sorted order\n for(int i = 0; i < mergedArray.size(); i++) {\n if (idxNums2 != nums2.size() && (idxNums1 == nums1.size() || nums2[idxNums2] < nums1[idxNums1])) {\n mergedArray[i] = nums2[idxNums2++];\n } else {\n mergedArray[i] = nums1[idxNums1++];\n }\n }\n \n // Calculate the median of the merged array\n if (mergedArray.size() % 2 == 1) {\n return mergedArray[mergedArray.size() / 2];\n } else {\n return ((mergedArray[mergedArray.size() / 2]) + (mergedArray[mergedArray.size() / 2 - 1])) / 2.0;\n }\n }\n};\n```\n```Java []\nclass Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n // Merge the sorted arrays into a single array\n int[] mergedArray = new int[nums1.length + nums2.length];\n\n int idxNums1 = 0; // Index for nums1\n int idxNums2 = 0; // Index for nums2\n\n // Merge the arrays while maintaining the sorted order\n for (int i = 0; i < mergedArray.length; i++) {\n if (idxNums2 < nums2.length && (idxNums1 == nums1.length || nums2[idxNums2] < nums1[idxNums1])) {\n mergedArray[i] = nums2[idxNums2++];\n } else {\n mergedArray[i] = nums1[idxNums1++];\n }\n }\n\n // Calculate the median of the merged array\n if (mergedArray.length % 2 == 1) {\n return mergedArray[mergedArray.length / 2];\n } else {\n return (mergedArray[mergedArray.length / 2] + mergedArray[mergedArray.length / 2 - 1]) / 2.0;\n }\n }\n}\n```\n```Python []\nclass Solution:\n def findMedianSortedArrays(self, nums1, nums2) -> float:\n merged_array = [0] * (len(nums1) + len(nums2))\n idx_nums1 = 0 # Index for nums1\n idx_nums2 = 0 # Index for nums2\n\n # Merge the arrays while maintaining the sorted order\n for i in range(len(merged_array)):\n if idx_nums2 < len(nums2) and (idx_nums1 == len(nums1) or nums2[idx_nums2] < nums1[idx_nums1]):\n merged_array[i] = nums2[idx_nums2]\n idx_nums2 += 1\n else:\n merged_array[i] = nums1[idx_nums1]\n idx_nums1 += 1\n\n # Calculate the median of the merged array\n if len(merged_array) % 2 == 1:\n return merged_array[len(merged_array) // 2]\n else:\n return (merged_array[len(merged_array) // 2] + merged_array[len(merged_array) // 2 - 1]) / 2.0\n```\n\n## 2. Divide And Conquer\n```C++ []\nclass Solution {\npublic:\n // Helper function to find the kth element in merged sorted arrays\n double findKthElement(int k, vector<int>& nums1, vector<int>& nums2, int start1, int end1, int start2, int end2) {\n // Base cases when one array is exhausted\n if (start1 >= end1)\n return nums2[start2 + k];\n if (start2 >= end2)\n return nums1[start1 + k];\n\n // Calculate mid indices\n int mid1 = (end1 - start1) / 2;\n int mid2 = (end2 - start2) / 2;\n\n // Compare mid elements and recurse accordingly\n if (mid1 + mid2 < k) {\n if (nums1[start1 + mid1] > nums2[start2 + mid2])\n // Discard elements before mid2 and search in the remaining array\n return findKthElement(k - mid2 - 1, nums1, nums2, start1, end1, start2 + mid2 + 1, end2);\n else\n // Discard elements before mid1 and search in the remaining array\n return findKthElement(k - mid1 - 1, nums1, nums2, start1 + mid1 + 1, end1, start2, end2);\n } else {\n if (nums1[start1 + mid1] > nums2[start2 + mid2])\n // Discard elements after mid1 and search in the remaining array\n return findKthElement(k, nums1, nums2, start1, start1 + mid1, start2, end2);\n else\n // Discard elements after mid2 and search in the remaining array\n return findKthElement(k, nums1, nums2, start1, end1, start2, start2 + mid2);\n }\n }\n\n // Function to find the median of merged sorted arrays\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n int size1 = nums1.size();\n int size2 = nums2.size();\n int totalSize = size1 + size2;\n\n // Check if the total size is odd or even and find the median accordingly\n if (totalSize % 2 == 1)\n // For odd total size, median is the kth element where k = total_size // 2\n return findKthElement(totalSize / 2, nums1, nums2, 0, size1, 0, size2);\n else {\n // For even total size, median is the average of kth and (kth - 1) elements\n int num1 = findKthElement(totalSize / 2, nums1, nums2, 0, size1, 0, size2);\n int num2 = findKthElement(totalSize / 2 - 1, nums1, nums2, 0, size1, 0, size2);\n\n return (num1 + num2) / 2.0;\n }\n }\n};\n```\n```Java []\nclass Solution {\n // Helper function to find the kth element in merged sorted arrays\n private double findKthElement(int k, int[] nums1, int[] nums2, int start1, int end1, int start2, int end2) {\n // Base cases when one array is exhausted\n if (start1 >= end1)\n return nums2[start2 + k];\n if (start2 >= end2)\n return nums1[start1 + k];\n\n // Calculate mid indices\n int mid1 = (end1 - start1) / 2;\n int mid2 = (end2 - start2) / 2;\n\n // Compare mid elements and recurse accordingly\n if (mid1 + mid2 < k) {\n if (nums1[start1 + mid1] > nums2[start2 + mid2])\n // Discard elements before mid2 and search in the remaining array\n return findKthElement(k - mid2 - 1, nums1, nums2, start1, end1, start2 + mid2 + 1, end2);\n else\n // Discard elements before mid1 and search in the remaining array\n return findKthElement(k - mid1 - 1, nums1, nums2, start1 + mid1 + 1, end1, start2, end2);\n } else {\n if (nums1[start1 + mid1] > nums2[start2 + mid2])\n // Discard elements after mid1 and search in the remaining array\n return findKthElement(k, nums1, nums2, start1, start1 + mid1, start2, end2);\n else\n // Discard elements after mid2 and search in the remaining array\n return findKthElement(k, nums1, nums2, start1, end1, start2, start2 + mid2);\n }\n }\n\n // Function to find the median of merged sorted arrays\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n int size1 = nums1.length;\n int size2 = nums2.length;\n int totalSize = size1 + size2;\n\n // Check if the total size is odd or even and find the median accordingly\n if (totalSize % 2 == 1)\n // For odd total size, median is the kth element where k = total_size // 2\n return findKthElement(totalSize / 2, nums1, nums2, 0, size1, 0, size2);\n else {\n // For even total size, median is the average of kth and (kth - 1) elements\n double num1 = findKthElement(totalSize / 2, nums1, nums2, 0, size1, 0, size2);\n double num2 = findKthElement(totalSize / 2 - 1, nums1, nums2, 0, size1, 0, size2);\n\n return (num1 + num2) / 2.0;\n }\n }\n}\n```\n```Python []\nclass Solution:\n def find_kth_element(self, k, nums1, nums2):\n # Base cases when one array is exhausted\n if not nums1:\n return nums2[k]\n if not nums2:\n return nums1[k]\n\n mid1 = len(nums1) // 2 # Midpoint of nums1\n mid2 = len(nums2) // 2 # Midpoint of nums2\n\n if mid1 + mid2 < k:\n if nums1[mid1] > nums2[mid2]:\n # Discard elements before mid2 and search in the remaining array\n return self.find_kth_element(k - mid2 - 1, nums1, nums2[mid2 + 1:])\n else:\n # Discard elements before mid1 and search in the remaining array\n return self.find_kth_element(k - mid1 - 1, nums1[mid1 + 1:], nums2)\n else:\n if nums1[mid1] > nums2[mid2]:\n # Discard elements after mid1 and search in the remaining array\n return self.find_kth_element(k, nums1[:mid1], nums2)\n else:\n # Discard elements after mid2 and search in the remaining array\n return self.find_kth_element(k, nums1, nums2[:mid2])\n\n def findMedianSortedArrays(self, nums1, nums2):\n total_size = len(nums1) + len(nums2)\n\n if total_size % 2 == 1:\n # For odd total size, median is the kth element where k = total_size // 2\n return self.find_kth_element(total_size // 2, nums1, nums2)\n else:\n # For even total size, median is the average of kth and (kth - 1) elements\n k1 = total_size // 2\n k2 = total_size // 2 - 1\n num1 = self.find_kth_element(k1, nums1, nums2)\n num2 = self.find_kth_element(k2, nums1, nums2)\n return (num1 + num2) / 2.0\n```\n\n \n![leet_sol.jpg]()\n\n
368
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
4,160
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n int n= nums1.size();\n int m= nums2.size();\n vector<int> nums(n+m);\n\n int index=0;\n int l=0;\n int r=0;\n while(l<n && r<m){\n if(nums1[l]<=nums2[r]){\n nums[index++]=nums1[l++];\n }\n else{\n nums[index++]=nums2[r++];\n }\n }\n while(l<n){\n nums[index++]=nums1[l++];\n }\n while(r<m){\n nums[index++]=nums2[r++];\n }\n\n double ans;\n int mid = (n+m)/2;\n if((n+m)%2==0){\n ans= (nums[mid] + nums[mid-1])/2.0;\n }\n else{\n ans= nums[mid];\n }\n return ans;\n }\n};\n```\n
391
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
2,450
27
# Intuition & Approach\n- Beautifully Explained in the code.\n\n# Code\n```\nclass Solution\n{\n public:\n \tLOGIC\n\n \tAPPROACH-1(NAIVE)\n \t1. Merge Sort\u2753 (Kyoki hame 2 sorted array dikh gaye), Ab median kyoki hame merge karke hi milega.\n \tO(M+N)\n\n \tAPPROACH-2(BINARY SEARCH)\n\n \t1.Why\u2753 Sorted array se hame Binary Search strike karega.\n\n \t2.Ab isme Binary Search lagayenge kaise\u2753\n\n \t3.We will partition both the arrays lets say Left part of both into L1,L2\n \tand Right part of both into R1,R2.\n\n \t4.Left part and Right part se matlab?->Left part (L1+L2) wo hoga joki agar \n \tmerge karte arrays ko to median ke left part wala hota aur Right part (R1+R2)\n \tjo median ke right mein hota.\n\n \t5.Now main action of BINARY SEARCH \uD83D\uDE0E is \uD83D\uDD25PARTITIONING\uD83D\uDD25.\n\n \t6.Implement kaise karenge\u2753\n \t- We will do the Binary Search in the array having shortest size.\n\n \t- Why shortest\u2753TC less hoga \n\n \t- median = (n+m+1)/2, low=0, high=n\n\n \t- PARTITION -> cut1 = (low+high)/2 {Pehle array ke kitne elem L1 mein honge}\n \tcut2= median - cut1 {Dusre array ke kitne elem L2 mein honge}.\n\n \t- Ab L1,L2 ki border values jo ki median ke just left = l1,l2 and R1,R2 ki \n \tborder values jo ki median ke just right will r1,r2\n\n \tAb sara khel inhi ka hain\n\n \t- If cut1!=0 take l1=nums1[cut1-1],cut2!=0 l2=nums2[cut2-1],cut1!=n \n \tr1=nums1[cut1],cut2!=m r2=nums2[cut2].\n\n \tNow the \uD83D\uDD25VALIDITY\uD83D\uDD25 of Partition is when l1<=r2 and l2<=r1\n\n \t- Agar aisa hua to hame hamara merged array mil gaya nahin to aur even \n \todd ke hisab se median nikal lenge.\n\n \t- if(l1>r2) to high=cut1-1(Hame L1 mein number ghatane padenge)\n\n \t- if(l2>r1) to low=cut1+1(Matlan cut2 kam hoga means L2 se number ghatayenge).\n\n \t- Aur fir dobara ghumenge loop mein.\n\n \t- TC: O(log(min(m,n)))\n//------------------------------------------------------------------------------------------------\n double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2)\n {\n int n = nums1.size();\n int m = nums2.size();\n if (m < n)\n return findMedianSortedArrays(nums2, nums1);\n \t//Shortest Array finding\n int medianPos = (n + m + 1) / 2;\n \t//Median Pos in merged array\n int low = 0;\n \t//low of shortest array\n int high = n;\n \t//high of shortest array\n while (low <= high)\n {\n int cut1 = (low + high) / 2;\n \t//L1 array - 0 to cut1,R1 array - cut1 to n\n int cut2 = medianPos - cut1;\n \t//L2 array - 0 to cut2,R2 array - cut2 to m\n\n int l1 = cut1 == 0 ? INT_MIN : nums1[cut1 - 1];\n int l2 = cut2 == 0 ? INT_MIN : nums2[cut2 - 1];\n int r1 = cut1 == n ? INT_MAX : nums1[cut1];\n int r2 = cut2 == m ? INT_MAX : nums2[cut2];\n \t//Above are boundary values of L1,L2,R1,R2\n \t//---------l1 r1--------\n \t//---------l2 r2--------\n\n if (l1 <= r2 && l2 <= r1)\n \t//Validity of Partition\n {\n if ((n + m) % 2 == 0)\n \t//Even no merged array\n return (max(l1, l2) + min(r1, r2)) / 2.0;\n else\n \t//Odd no merged array\n return max(l1, l2);\n }\n else if (l1 > r2)\n \t//Invalid case\n high = cut1 - 1;\n \t//L1 ki boundary se piche jayenge\n else\n \t//L2 ki boundary se piche jayenge\n low = cut1 + 1;\n }\n return 0.0;\n }\n};\n```\n\n# Complexity\n- Time complexity: $O(log(min(m,n)))$ Binary Search on Shortest array.\n\n- Space complexity: $O(1)$\n\nIf you *like* \uD83D\uDC4D this solution do *upvote* \u2B06\uFE0F and if there is any *improvement or suggestion* do mention it in the *comment* section \uD83D\uDE0A.\n\n<p align="center">\n<img src="" width=\'350\' alt="Upvote Image">\n</p>\n\n
392
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
630
7
\nFor Newbies\n# Complexity\n- Time complexity:\n O((m+n) log(m+n)) \n\n\n# Code\n```\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n double flag=0;\n \n nums1.insert(nums1.end(),nums2.begin(),nums2.end());\n sort(nums1.begin(),nums1.end());\n \n \n if(nums1.size() % 2==0) return flag=(nums1[nums1.size()/2.0]+nums1[(nums1.size()/2.0)-1])/2.0;\n else return flag=nums1[nums1.size()/2.0];\n \n \n }\n\n};\n```
393
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
18,118
50
\n# Intuition:\nGiven two sorted arrays nums1 and nums2 of size n1 and n2 respectively, the median of the combined sorted array can be found by dividing the elements of the combined sorted array into two halves of equal length such that one half is always greater than the other. The median is then the average of the maximum element of the left half and the minimum element of the right half if the total number of elements is even, or the maximum element of the left half if the total number of elements is odd.\n\n# Approach:\nWe can use binary search to find the partition of both arrays such that the number of elements on the left side of the combined array is equal to the number of elements on the right side of the combined array. The partition of nums1 and nums2 is represented by mid1 and mid2 respectively, such that mid1 + mid2 = (n1 + n2 + 1) / 2. We divide the combined sorted array into two halves such that the left half contains all elements before the partition and the right half contains all elements after the partition.\n\nWe then check if the maximum element of the left half of nums1 is less than or equal to the minimum element of the right half of nums2 and the maximum element of the left half of nums2 is less than or equal to the minimum element of the right half of nums1. If this condition is true, we have found the partition such that the number of elements on the left side of the combined array is equal to the number of elements on the right side of the combined array. We can then calculate the median using the approach mentioned in the intuition section.\n\nIf the condition is false, we adjust the partition of nums1 by changing l to mid1 + 1 if the maximum element of the left half of nums1 is greater than the minimum element of the right half of nums2, or by changing r to mid1 - 1 otherwise. We continue the binary search until we find the partition such that the condition is true or until the search space is exhausted.\n\n# Complexity:\n- The time complexity of the solution is O(log(min(n1, n2))), where n1 and n2 are the sizes of nums1 and nums2 respectively, since we are performing binary search on the smaller array. \n- The space complexity of the solution is O(1) since we are not using any extra space apart from a few variables to keep track of the search space and the partition of both arrays.\n\n---\n# C++\n```\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n int n1 = nums1.size();\n int n2 = nums2.size();\n \n // If nums1 is larger than nums2, swap them to ensure n1 is smaller than n2.\n if (n1 > n2) {\n return findMedianSortedArrays(nums2, nums1);\n }\n \n int l = 0;\n int r = n1;\n while (l <= r) {\n int mid1 = (l + r) / 2;\n int mid2 = (n1 + n2 + 1) / 2 - mid1;\n \n int maxLeft1 = (mid1 == 0) ? INT_MIN : nums1[mid1-1];\n int minRight1 = (mid1 == n1) ? INT_MAX : nums1[mid1];\n \n int maxLeft2 = (mid2 == 0) ? INT_MIN : nums2[mid2-1];\n int minRight2 = (mid2 == n2) ? INT_MAX : nums2[mid2];\n \n if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {\n if ((n1 + n2) % 2 == 0) {\n return (double)(max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) / 2;\n } else {\n return (double)max(maxLeft1, maxLeft2);\n }\n } else if (maxLeft1 > minRight2) {\n r = mid1 - 1;\n } else {\n l = mid1 + 1;\n }\n }\n \n return -1;\n }\n};\n\n```\n---\n# JavaScript\n```\nvar findMedianSortedArrays = function(nums1, nums2) {\n let n1 = nums1.length;\n let n2 = nums2.length;\n \n // If nums1 is larger than nums2, swap them to ensure n1 is smaller than n2.\n if (n1 > n2) {\n return findMedianSortedArrays(nums2, nums1);\n }\n \n let l = 0;\n let r = n1;\n while (l <= r) {\n let mid1 = Math.floor((l + r) / 2);\n let mid2 = Math.floor((n1 + n2 + 1) / 2 - mid1);\n \n let maxLeft1 = (mid1 == 0) ? Number.MIN_SAFE_INTEGER : nums1[mid1-1];\n let minRight1 = (mid1 == n1) ? Number.MAX_SAFE_INTEGER : nums1[mid1];\n \n let maxLeft2 = (mid2 == 0) ? Number.MIN_SAFE_INTEGER : nums2[mid2-1];\n let minRight2 = (mid2 == n2) ? Number.MAX_SAFE_INTEGER : nums2[mid2];\n \n if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {\n if ((n1 + n2) % 2 == 0) {\n return (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) / 2;\n } else {\n return Math.max(maxLeft1, maxLeft2);\n }\n } else if (maxLeft1 > minRight2) {\n r = mid1 - 1;\n } else {\n l = mid1 + 1;\n }\n }\n \n return -1;\n};\n\n```\n\n---\n# JAVA\n```\nclass Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n int n1 = nums1.length;\n int n2 = nums2.length;\n\n // If nums1 is larger than nums2, swap them to ensure n1 is smaller than n2.\n if (n1 > n2) {\n return findMedianSortedArrays(nums2, nums1);\n }\n\n int l = 0;\n int r = n1;\n while (l <= r) {\n int mid1 = (l + r) / 2;\n int mid2 = (n1 + n2 + 1) / 2 - mid1;\n\n int maxLeft1 = (mid1 == 0) ? Integer.MIN_VALUE : nums1[mid1 - 1];\n int minRight1 = (mid1 == n1) ? Integer.MAX_VALUE : nums1[mid1];\n\n int maxLeft2 = (mid2 == 0) ? Integer.MIN_VALUE : nums2[mid2 - 1];\n int minRight2 = (mid2 == n2) ? Integer.MAX_VALUE : nums2[mid2];\n\n if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {\n if ((n1 + n2) % 2 == 0) {\n return (double) (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) / 2;\n } else {\n return (double) Math.max(maxLeft1, maxLeft2);\n }\n } else if (maxLeft1 > minRight2) {\n r = mid1 - 1;\n } else {\n l = mid1 + 1;\n }\n }\n\n return -1;\n }\n}\n\n```\n\n---\n# Python\n```\nclass Solution(object):\n def findMedianSortedArrays(self, nums1, nums2):\n n1 = len(nums1)\n n2 = len(nums2)\n\n # If nums1 is larger than nums2, swap them to ensure n1 is smaller than n2.\n if n1 > n2:\n return self.findMedianSortedArrays(nums2, nums1)\n\n l = 0\n r = n1\n while l <= r:\n mid1 = (l + r) / 2\n mid2 = (n1 + n2 + 1) / 2 - mid1\n\n maxLeft1 = nums1[mid1-1] if mid1 != 0 else float(\'-inf\')\n minRight1 = nums1[mid1] if mid1 != n1 else float(\'inf\')\n\n maxLeft2 = nums2[mid2-1] if mid2 != 0 else float(\'-inf\')\n minRight2 = nums2[mid2] if mid2 != n2 else float(\'inf\')\n\n if maxLeft1 <= minRight2 and maxLeft2 <= minRight1:\n if (n1 + n2) % 2 == 0:\n return float(max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) / 2\n else:\n return float(max(maxLeft1, maxLeft2))\n elif maxLeft1 > minRight2:\n r = mid1 - 1\n else:\n l = mid1 + 1\n\n return -1\n\n```
394
Median of Two Sorted Arrays
median-of-two-sorted-arrays
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)).
Array,Binary Search,Divide and Conquer
Hard
null
5,784
8
\uD83D\uDCA1The problem \'Median of two sorted arrays\' is a classic computer science problem that involves finding the median value in a set of numbers, where the numbers are split between two sorted arrays. The median is the middle value in a set of numbers, or if there are an even numbers of values, the average of the two middle values.\n\nThe purpose of finding the median of two sorted arrays is to effciently locate the middle value(s) in a combined set of numbers without having to first merge the arrays. This is useful when working with large arrays,as mergin two large arrays can be time-consuming. By using the sorting information of the arrays, it is possible to find the median in O(log(min(m,n))) time, where m and n are the lengths of the two arryas.\n\n---\n\n# Approach\n1. Determine the length of both arrays \'nums1\' and \'nums2\'. Let \'m\' be the length of \'nums1\' and \'n\' be the length of \'nums2\'.\n2. Choose The array with the smaller length to be the first array. This is because binary search requires that we divide the array into two parts and compare values on both sides. If we start with the larger array, it would take longer to find the partion points because there would be more values to search through. By starting with the smaller array,we reduce the search space and make the process more efficent.\n3. Initialize two variables, \'imin\' and \'imax\', to keep track of the range of possible values for \'i\', the partition point in \'nums1\'. Set \'imin\' to 0 and \'imax\' to \'m\'/\n4. Calculate the desired length of elements on both sides on the partition points. let \'half_len\' be equal to \'(m+n+1)//2\n5. Use a while loop to perform binary search. while \'imin\' is less than or equal to \'imax\',do the following:\na. Calculate the partition point in \'nums1\' by finding the average of \'imin\' and \'imax\' and rounding down. Let \'i =(imin +imax) //2\'\nb. Calculate the corresponding partion point in \'nums2\' by substracting \'i\' from \'half_len\' . Let \'j =half_len -i\'\nc. Compare the values on both sides of the partition points. If \'i<m\' abd \'nums2[j-1] > nums1[i], it means that \'i\' is too small, so we need to increase it. Update \'imin\' to \'i+1\'. If \'i>0\' and \'nums1[i-1] > nums2[j]\', It means that \'i\' is too large, so we need to decrease it. Update \'imax\' to \'i-1\'.\nd. If \'i\' is such that the number of elements on both sides of the partion points is roughly equal, we have found the partion points. Go to step 6\n6. Calculate the median based on the values on both sides of the partion points. If the total number of elements \'(m+n)\' is odd, the median is simply the maximun value on the left side of the partition points.If the total number of element is even, the median is the average of the maximun value on the left side and the mimimun value on the right side of the partition points.\n7. Return the median as the result.\n\n# Code\n```\nclass Solution(object):\n def findMedianSortedArrays(self,nums1, nums2):\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m\n\n imin, imax, half_len = 0, m, (m + n + 1) // 2\n while imin <= imax:\n i = (imin + imax) // 2\n j = half_len - i\n if i < m and nums2[j-1] > nums1[i]:\n imin = i + 1\n elif i > 0 and nums1[i-1] > nums2[j]:\n imax = i - 1\n else:\n if i == 0: max_of_left = nums2[j-1]\n elif j == 0: max_of_left = nums1[i-1]\n else: max_of_left = max(nums1[i-1], nums2[j-1])\n\n if (m + n) % 2 == 1:\n return max_of_left\n\n if i == m: min_of_right = nums2[j]\n elif j == n: min_of_right = nums1[i]\n else: min_of_right = min(nums1[i], nums2[j])\n\n return (max_of_left + min_of_right) / 2.0\n```
395
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
33,434
350
### It takes a lot of efforts to write such long explanatinon, so please UpVote \u2B06\uFE0F if this helps you.\n\n# Approach 1: Brute Force\n\n![image.png]()\n\n# Intuition :\n\n**The obvious brute force solution is to pick all possible starting and ending positions for a substring, and verify if it is a palindrome. There are a total of n^2 such substrings (excluding the trivial solution where a character itself is a palindrome). Since verifying each substring takes O(n) time, the run time complexity is O(n^3).**\n\n# Algorithm :\n1. Pick a starting index for the current substring which is every index from 0 to n-2.\n2. Now, pick the ending index for the current substring which is every index from i+1 to n-1.\n3. Check if the substring from ith index to jth index is a palindrome.\n4. If step 3 is true and length of substring is greater than maximum length so far, update maximum length and maximum substring. \n5. Print the maximum substring.\n\n# Complexity Analysis\n- Time complexity : ***O(n^3)***. Assume that n is the length of the input string, there are a total of C(n, 2) = n(n-1)/2 substrings (excluding the trivial solution where a character itself is a palindrome). Since verifying each substring takes O(n) time, the run time complexity is O(n^3).\n\n- Space complexity : ***O(1)***.\n\n# Code\n``` Python []\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n if len(s) <= 1:\n return s\n \n Max_Len=1\n Max_Str=s[0]\n for i in range(len(s)-1):\n for j in range(i+1,len(s)):\n if j-i+1 > Max_Len and s[i:j+1] == s[i:j+1][::-1]:\n Max_Len = j-i+1\n Max_Str = s[i:j+1]\n\n return Max_Str\n```\n``` C++ []\nclass Solution {\npublic:\n std::string longestPalindrome(std::string s) {\n if (s.length() <= 1) {\n return s;\n }\n \n int max_len = 1;\n std::string max_str = s.substr(0, 1);\n \n for (int i = 0; i < s.length(); ++i) {\n for (int j = i + max_len; j <= s.length(); ++j) {\n if (j - i > max_len && isPalindrome(s.substr(i, j - i))) {\n max_len = j - i;\n max_str = s.substr(i, j - i);\n }\n }\n }\n\n return max_str;\n }\n\nprivate:\n bool isPalindrome(const std::string& str) {\n int left = 0;\n int right = str.length() - 1;\n \n while (left < right) {\n if (str[left] != str[right]) {\n return false;\n }\n ++left;\n --right;\n }\n \n return true;\n }\n};\n```\n``` Java []\npublic class Solution {\n public String longestPalindrome(String s) {\n if (s.length() <= 1) {\n return s;\n }\n\n int maxLen = 1;\n String maxStr = s.substring(0, 1);\n\n for (int i = 0; i < s.length(); i++) {\n for (int j = i + maxLen; j <= s.length(); j++) {\n if (j - i > maxLen && isPalindrome(s.substring(i, j))) {\n maxLen = j - i;\n maxStr = s.substring(i, j);\n }\n }\n }\n\n return maxStr;\n }\n\n private boolean isPalindrome(String str) {\n int left = 0;\n int right = str.length() - 1;\n\n while (left < right) {\n if (str.charAt(left) != str.charAt(right)) {\n return false;\n }\n left++;\n right--;\n }\n\n return true;\n }\n}\n```\n# Approach 2: Expand Around Center\n![Screenshot 2023-10-27 at 8.15.36\u202FAM.png]()\n\n# Intuition :\n\n**To enumerate all palindromic substrings of a given string, we first expand a given string at each possible starting position of a palindrome and also at each possible ending position of a palindrome and keep track of the length of the longest palindrome we found so far.**\n\n# Approach :\n1. We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only 2n - 1 such centers.\n2. You might be asking why there are 2n - 1 but not n centers? The reason is the center of a palindrome can be in between two letters. Such palindromes have even number of letters (such as "abba") and its center are between the two \'b\'s.\'\n3. Since expanding a palindrome around its center could take O(n) time, the overall complexity is O(n^2).\n\n# Algorithm :\n1. At starting we have maz_str = s[0] and max_len = 1 as every single character is a palindrome.\n2. Now, we will iterate over the string and for every character we will expand around its center.\n3. For odd length palindrome, we will consider the current character as the center and expand around it.\n4. For even length palindrome, we will consider the current character and the next character as the center and expand around it.\n5. We will keep track of the maximum length and the maximum substring.\n6. Print the maximum substring.\n\n# Complexity Analysis\n- Time complexity : ***O(n^2)***. Since expanding a palindrome around its center could take O(n) time, the overall complexity is O(n^2).\n\n- Space complexity : ***O(1)***.\n\n# Code\n\n``` Python []\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n if len(s) <= 1:\n return s\n\n def expand_from_center(left, right):\n while left >= 0 and right < len(s) and s[left] == s[right]:\n left -= 1\n right += 1\n return s[left + 1:right]\n\n max_str = s[0]\n\n for i in range(len(s) - 1):\n odd = expand_from_center(i, i)\n even = expand_from_center(i, i + 1)\n\n if len(odd) > len(max_str):\n max_str = odd\n if len(even) > len(max_str):\n max_str = even\n\n return max_str\n```\n``` C++ []\nclass Solution {\npublic:\n std::string longestPalindrome(std::string s) {\n if (s.length() <= 1) {\n return s;\n }\n\n auto expand_from_center = [&](int left, int right) {\n while (left >= 0 && right < s.length() && s[left] == s[right]) {\n left--;\n right++;\n }\n return s.substr(left + 1, right - left - 1);\n };\n\n std::string max_str = s.substr(0, 1);\n\n for (int i = 0; i < s.length() - 1; i++) {\n std::string odd = expand_from_center(i, i);\n std::string even = expand_from_center(i, i + 1);\n\n if (odd.length() > max_str.length()) {\n max_str = odd;\n }\n if (even.length() > max_str.length()) {\n max_str = even;\n }\n }\n\n return max_str;\n }\n};\n```\n``` Java []\npublic class Solution {\n public String longestPalindrome(String s) {\n if (s.length() <= 1) {\n return s;\n }\n\n String maxStr = s.substring(0, 1);\n\n for (int i = 0; i < s.length() - 1; i++) {\n String odd = expandFromCenter(s, i, i);\n String even = expandFromCenter(s, i, i + 1);\n\n if (odd.length() > maxStr.length()) {\n maxStr = odd;\n }\n if (even.length() > maxStr.length()) {\n maxStr = even;\n }\n }\n\n return maxStr;\n }\n\n private String expandFromCenter(String s, int left, int right) {\n while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {\n left--;\n right++;\n }\n return s.substring(left + 1, right);\n }\n}\n\n```\n# Approach 3: Dynamic Programming\n\n\n\n# Intuition :\n![image.png]()\n\n**To improve over the brute force solution, we first observe how we can avoid unnecessary re-computation while validating palindromes. Consider the case "ababa". If we already knew that "bab" is a palindrome, it is obvious that "ababa" must be a palindrome since the two left and right end letters are the same.**\n\n# Algorithm :\n1. We initialize a boolean table dp and mark all the values as false.\n2. We will use a variable max_len to keep track of the maximum length of the palindrome.\n3. We will iterate over the string and mark the diagonal elements as true as every single character is a palindrome.\n4. Now, we will iterate over the string and for every character we will expand around its center.\n5. For odd length palindrome, we will consider the current character as the center and expand around it.\n6. For even length palindrome, we will consider the current character and the next character as the center and expand around it.\n7. We will keep track of the maximum length and the maximum substring.\n8. Print the maximum substring.\n\n# Complexity Analysis\n- Time complexity : ***O(n^2)***. This gives us a runtime complexity of O(n^2).\n\n- Space complexity : ***O(n^2)***. It uses O(n^2) space to store the table.\n# Code\n``` Python []\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n if len(s) <= 1:\n return s\n \n Max_Len=1\n Max_Str=s[0]\n dp = [[False for _ in range(len(s))] for _ in range(len(s))]\n for i in range(len(s)):\n dp[i][i] = True\n for j in range(i):\n if s[j] == s[i] and (i-j <= 2 or dp[j+1][i-1]):\n dp[j][i] = True\n if i-j+1 > Max_Len:\n Max_Len = i-j+1\n Max_Str = s[j:i+1]\n return Max_Str\n```\n``` C++ []\nclass Solution {\npublic:\n std::string longestPalindrome(std::string s) {\n if (s.length() <= 1) {\n return s;\n }\n \n int max_len = 1;\n int start = 0;\n int end = 0;\n std::vector<std::vector<bool>> dp(s.length(), std::vector<bool>(s.length(), false));\n \n for (int i = 0; i < s.length(); ++i) {\n dp[i][i] = true;\n for (int j = 0; j < i; ++j) {\n if (s[j] == s[i] && (i - j <= 2 || dp[j + 1][i - 1])) {\n dp[j][i] = true;\n if (i - j + 1 > max_len) {\n max_len = i - j + 1;\n start = j;\n end = i;\n }\n }\n }\n }\n \n return s.substr(start, end - start + 1);\n }\n};\n\n```\n``` Java []\npublic class Solution {\n public String longestPalindrome(String s) {\n if (s.length() <= 1) {\n return s;\n }\n\n int maxLen = 1;\n int start = 0;\n int end = 0;\n boolean[][] dp = new boolean[s.length()][s.length()];\n\n for (int i = 0; i < s.length(); ++i) {\n dp[i][i] = true;\n for (int j = 0; j < i; ++j) {\n if (s.charAt(j) == s.charAt(i) && (i - j <= 2 || dp[j + 1][i - 1])) {\n dp[j][i] = true;\n if (i - j + 1 > maxLen) {\n maxLen = i - j + 1;\n start = j;\n end = i;\n }\n }\n }\n }\n\n return s.substring(start, end + 1);\n }\n}\n\n```\n\n# Approach 4: Manacher\'s Algorithm\n![image.png]()\n\n# Intuition :\n\n**To avoid the unnecessary validation of palindromes, we can use Manacher\'s algorithm. The algorithm is explained brilliantly in this article. The idea is to use palindrome property to avoid unnecessary validations. We maintain a center and right boundary of a palindrome. We use previously calculated values to determine if we can expand around the center or not. If we can expand, we expand and update the center and right boundary. Otherwise, we move to the next character and repeat the process. We also maintain a variable max_len to keep track of the maximum length of the palindrome. We also maintain a variable max_str to keep track of the maximum substring.**\n\n# Algorithm :\n1. We initialize a boolean table dp and mark all the values as false.\n2. We will use a variable max_len to keep track of the maximum length of the palindrome.\n3. We will iterate over the string and mark the diagonal elements as true as every single character is a palindrome.\n4. Now, we will iterate over the string and for every character we will expand around its center.\n5. For odd length palindrome, we will consider the current character as the center and expand around it.\n6. For even length palindrome, we will consider the current character and the next character as the center and expand around it.\n7. We will keep track of the maximum length and the maximum substring.\n8. Print the maximum substring.\n\n# Complexity Analysis\n- Time complexity : ***O(n)***. Since expanding a palindrome around its center could take O(n) time, the overall complexity is O(n).\n\n- Space complexity : ***O(n)***. It uses O(n) space to store the table.\n\n# Code\n``` Python []\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n if len(s) <= 1:\n return s\n \n Max_Len=1\n Max_Str=s[0]\n s = \'#\' + \'#\'.join(s) + \'#\'\n dp = [0 for _ in range(len(s))]\n center = 0\n right = 0\n for i in range(len(s)):\n if i < right:\n dp[i] = min(right-i, dp[2*center-i])\n while i-dp[i]-1 >= 0 and i+dp[i]+1 < len(s) and s[i-dp[i]-1] == s[i+dp[i]+1]:\n dp[i] += 1\n if i+dp[i] > right:\n center = i\n right = i+dp[i]\n if dp[i] > Max_Len:\n Max_Len = dp[i]\n Max_Str = s[i-dp[i]:i+dp[i]+1].replace(\'#\',\'\')\n return Max_Str\n```\n``` C++ []\nclass Solution {\npublic:\n std::string longestPalindrome(std::string s) {\n if (s.length() <= 1) {\n return s;\n }\n \n int maxLen = 1;\n std::string maxStr = s.substr(0, 1);\n s = "#" + std::regex_replace(s, std::regex(""), "#") + "#";\n std::vector<int> dp(s.length(), 0);\n int center = 0;\n int right = 0;\n \n for (int i = 0; i < s.length(); ++i) {\n if (i < right) {\n dp[i] = std::min(right - i, dp[2 * center - i]);\n }\n \n while (i - dp[i] - 1 >= 0 && i + dp[i] + 1 < s.length() && s[i - dp[i] - 1] == s[i + dp[i] + 1]) {\n dp[i]++;\n }\n \n if (i + dp[i] > right) {\n center = i;\n right = i + dp[i];\n }\n \n if (dp[i] > maxLen) {\n maxLen = dp[i];\n maxStr = s.substr(i - dp[i], 2 * dp[i] + 1);\n maxStr.erase(std::remove(maxStr.begin(), maxStr.end(), \'#\'), maxStr.end());\n }\n }\n \n return maxStr;\n }\n};\n\n```\n``` Java []\npublic class Solution {\n public String longestPalindrome(String s) {\n if (s.length() <= 1) {\n return s;\n }\n\n int maxLen = 1;\n String maxStr = s.substring(0, 1);\n s = "#" + s.replaceAll("", "#") + "#";\n int[] dp = new int[s.length()];\n int center = 0;\n int right = 0;\n\n for (int i = 0; i < s.length(); i++) {\n if (i < right) {\n dp[i] = Math.min(right - i, dp[2 * center - i]);\n }\n\n while (i - dp[i] - 1 >= 0 && i + dp[i] + 1 < s.length() && s.charAt(i - dp[i] - 1) == s.charAt(i + dp[i] + 1)) {\n dp[i]++;\n }\n\n if (i + dp[i] > right) {\n center = i;\n right = i + dp[i];\n }\n\n if (dp[i] > maxLen) {\n maxLen = dp[i];\n maxStr = s.substring(i - dp[i], i + dp[i] + 1).replaceAll("#", "");\n }\n }\n\n return maxStr;\n }\n}\n```\n\n# Approach 5: Recursive TLE(Time Limit Exceeded)\n\n# Intuition :\n\n**The obvious brute force solution is to pick all possible starting and ending positions for a substring, and verify if it is a palindrome. There are a total of n^2 such substrings (excluding the trivial solution where a character itself is a palindrome). Since verifying each substring takes O(n) time, the run time complexity is O(n^3). But in this approach we will use recursion to solve the problem. We will check if the string is a palindrome or not. If it is a palindrome, we will return the string. Otherwise, we will recursively call the function for the string excluding the first character and for the string excluding the last character. We will check the length of the returned strings and return the string with the maximum length.**\n\n# Algorithm :\n1. If the string is a palindrome, we will return the string.\n2. Otherwise, we will recursively call the function for the string excluding the first character and for the string excluding the last character.\n3. We will check the length of the returned strings and return the string with the maximum length.\n\n# Complexity Analysis \n- Time complexity : ***O(n^3)***. Assume that n is the length of the input string, there are a total of C(n, 2) = n(n-1)/2 substrings (excluding the trivial solution where a character itself is a palindrome). Since verifying each substring takes O(n) time, the run time complexity is O(n^3).\n\n- Space complexity : ***O(n)***. The recursion stack may go up to n levels deep.\n# Code\n``` Python []\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n\n if s==s[::-1]: \n return s\n left = self.longestPalindrome(s[1:])\n right = self.longestPalindrome(s[:-1])\n\n if len(left)>len(right):\n return left\n else:\n return right\n```\n``` C++ []\nclass Solution {\npublic:\n string longestPalindrome(string s) {\n if (s == string(s.rbegin(), s.rend())) {\n return s;\n }\n\n string left = longestPalindrome(s.substr(1));\n string right = longestPalindrome(s.substr(0, s.size() - 1));\n\n if (left.length() > right.length()) {\n return left;\n } else {\n return right;\n }\n }\n};\n\n```\n``` Java []\npublic class Solution {\n public String longestPalindrome(String s) {\n if (s.equals(new StringBuilder(s).reverse().toString())) {\n return s;\n }\n\n String left = longestPalindrome(s.substring(1));\n String right = longestPalindrome(s.substring(0, s.length() - 1));\n\n if (left.length() > right.length()) {\n return left;\n } else {\n return right;\n }\n }\n}\n```\n\n![image.png]()\n
400
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
117,603
641
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve this question using Multiple Approaches. (Here I have explained all the possible solutions of this problem).\n\n1. Solved using string(Three Nested Loop). Brute Force Approach.\n2. Solved using string(TwoNested Loop). Brute Force Approach.\n3. Solved using Dynamic Programming Approach(tabulation). Optimized Approach.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can easily understand the All the approaches by seeing the code which is easy to understand with comments.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime complexity is given in code comment.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace complexity is given in code comment.\n\n# Code\n```\n/*\n\n Time Complexity : O(N^3), Here three nested loop creates the time complexity. Where N is the size of the\n string(s).\n\n Space Complexity : O(1), Constant space.\n\n Solved using string(Three Nested Loop). Brute Force Approach.\n\n Note : this may give TLE.\n\n*/\n\n\n/***************************************** Approach 1 *****************************************/\n\nclass Solution {\nprivate: \n bool check(string &s, int i, int j){\n while(i<j){\n if(s[i] != s[j]){\n return false;\n }\n i++;\n j--;\n }\n return true;\n } \npublic:\n string longestPalindrome(string s) {\n int n = s.size();\n int starting_index = 0;\n int max_len = 0;\n for(int i=0; i<n; i++){\n for(int j=i; j<n; j++){\n if(check(s, i, j)){\n if(j-i+1 > max_len){\n max_len = j-i+1;\n starting_index = i;\n }\n }\n }\n }\n return s.substr(starting_index, max_len);\n }\n}; \n\n\n\n\n\n\n/*\n\n Time Complexity : O(N^2), Here Two nested loop creates the time complexity. Where N is the size of the\n string(s).\n\n Space Complexity : O(N^2*N), vector(substring) space.\n\n Solved using string(TwoNested Loop). Brute Force Approach.\n\n Note : this may give TLE.\n\n*/\n\n\n/***************************************** Approach 2 *****************************************/\n\nclass Solution { \nprivate: \n bool check(string &s, int i, int j){\n while(i<j){\n if(s[i] != s[j]){\n return false;\n }\n i++;\n j--;\n }\n return true;\n }\npublic:\n string longestPalindrome(string s) {\n int n = s.size();\n vector<string> substring;\n for(int i=0; i<n; i++){\n string temp = "";\n for(int j=i; j<n; j++){\n temp += s[j];\n substring.push_back(temp);\n }\n }\n int max_len = 0;\n string finalans = substring[0];\n int m = substring.size();\n for(int i=0; i<m; i++){\n int s = substring[i].size();\n if(check(substring[i], 0, s-1)){\n if(s > max_len){\n max_len = s;\n finalans = substring[i];\n }\n } \n }\n return finalans;\n }\n};\n\n\n\n\n\n\n/*\n\n Time Complexity : O(N^2), The time complexity of the above code is O(N^2) because we are traversing over all\n the substrings and then checking each substring if it is a palindrome or not. There are N^2 substrings and\n checking a substring takes O(1) time, so total time complexity is O(N^2).\n\n Space Complexity : (N^2), The space complexity of the above code is O(N^2) because we are using the dp array\n in which we are storing whether a substring is a palindrome or not.\n\n Solved using Dynamic Programming Approach(tabulation). Optimized Approach.\n\n*/\n\n\n/***************************************** Approach 3 *****************************************/\n\nclass Solution {\nprivate: \n bool solve(vector<vector<bool>> &dp, int i, int j, string &s){\n if(i == j){\n return dp[i][j] = true;\n }\n if(j-i == 1){\n if(s[i] == s[j]){\n return dp[i][j] = true;\n }\n else{\n return dp[i][j] = false;\n }\n }\n if(s[i] == s[j] && dp[i+1][j-1] == true){\n return dp[i][j] = true;\n } else {\n return dp[i][j] = false;\n }\n }\npublic:\n string longestPalindrome(string s) {\n int n = s.size();\n int startIndex = 0; int maxlen = 0;\n vector<vector<bool>> dp(n, vector<bool>(n, false));\n for(int g=0; g<n; g++){\n for(int i=0, j=g; j<n; i++, j++){\n solve(dp, i, j, s);\n if(dp[i][j] == true){\n if(j-i+1 > maxlen){\n startIndex = i;\n maxlen = j-i+1;\n }\n }\n }\n }\n return s.substr(startIndex, maxlen);\n }\n};\n\n```\n\n***IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.***\n\n![WhatsApp Image 2023-02-10 at 19.01.02.jpeg]()
402
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
58,694
344
# Approach\n[![LPS0.png]()]()\n\n\n\n\n\n>The only tricky thing is that you have to be sure the right substring is returned in `expand()`. The loop ends only after expanding the range by 1 on both sides, so you have to remove those in the final returned string.\n\n>Here we basically choose each centre and try expanding from each and every specific node thus we call expand functionas `expand(i,i)` and `expand(i,i+1)` and later we apply two pointers on each node to find the longest palindrome \n\n\n\n\n\n\n![LPS.png]()\n\n\n\n\n\n> In fact, we could solve it in $$O(n^2)$$ time using only constant space.\n\nWe observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only $$2n\u22121$$ such centers.\n\nYou might be asking why there are $$2n - 1$$ but not $$n$$ centers? The reason is the center of a palindrome can be in between two letters. Such palindromes have even number of letters (such as "abba") and its center are between the two \'b\'s.\n\n\n---\n\n# Code\n\n```C++ []\nclass Solution {\npublic:\n string ans = "";\n void expand(string &s , int left ,int right)\n {\n while(left >= 0 && right < s.size())\n {\n if(s[left] != s[right])\n break;\n left--,right++;\n }\n if(ans.size() < right - left )\n ans = s.substr(left + 1 , right - left - 1);\n }\n string longestPalindrome(string s) {\n for(int i = 0 ; i < s.size() ; i++)\n {\n expand(s , i , i);\n expand(s , i , i+1);\n }\n return ans;\n }\n};\n```\n```java []\nclass Solution {\n int maxLen = 0;\n int lo = 0;\n public String longestPalindrome(String s) {\n char[] input = s.toCharArray();\n if(s.length() < 2) {\n return s;\n }\n \n for(int i = 0; i<input.length; i++) {\n expandPalindrome(input, i, i);\n expandPalindrome(input, i, i+1);\n }\n return s.substring(lo, lo+maxLen);\n }\n \n public void expandPalindrome(char[] s, int j, int k) {\n while(j >= 0 && k < s.length && s[j] == s[k]) {\n j--;\n k++;\n }\n if(maxLen < k - j - 1) {\n maxLen = k - j - 1;\n lo = j+1;\n }\n }\n}\n```\n```python []\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n ans=\'\'\n for i in range(len(s)):\n ans=max(ans,expand(s,i,i), expand(s,i,i+1), key=len)\n return ans\n \ndef expand(s,i,j):\n while i>=0 and j<len(s) and s[i]==s[j]:\n i-=1\n j+=1\n return s[i+1:j]\n```\n```c []\nint maxVal(int a, int b) {\n return a > b ? a : b;\n}\n\nint extend(char *s, int start, int end) {\n int len = strlen(s);\n for(; start >= 0 && end < len; start--, end++) {\n if(*(s + start) != *(s + end))\n break;\n }\n return end - start - 1;\n}\n\nchar * longestPalindrome(char * s){\n int max = 0, idx = 0, len = strlen(s);\n for(int i = 0; i < len; i++) {\n int len1 = extend(s, i, i); /* For even string */\n int len2 = extend(s, i, i + 1); /* For odd string */\n if (max < maxVal(len1, len2)) {\n idx = (len1 > len2) ? (i - len1 / 2) : (i - len2 / 2 + 1);\n max = maxVal(len1, len2);\n }\n }\n char *res = malloc((max+1) *sizeof(char));\n memcpy(res, &s[idx], max);\n res[max] = \'\\0\';\n return res;\n}\n```\n---\n# Complexity\n> **Time Complexity:** $$O(n^2)$$ as there is two recursion calls which are applied as two pointers so here Complexity would be$$ O(n^2).$$\n\n> **Space Complexity:** $$O(n)$$ which is nothing but the storage consumed in this process.\n\n---\n**IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.**\n\n![UPVOTE.jpg]()\n\n
405
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
334
6
\n\nA brute force solution would first require generating every possible substring, which runs in O(n<sup>2</sup>) time. Then, <i>for each</i> of those substrings, we have to check if they are a palindrome. Since palindromes read the same forwards and backwards, we know that they have to be mirrored across the center. So one way of testing for palindromes is to start in the middle of the string and work outwards, checking at each step to see if the characters are equal. Since each palindrome check runs in O(n), the overall algorithm ends up running in O(n<sup>3</sup>) time.\n\nInstead, we can reduce this to O(n<sup>2</sup>) time by eliminating some redundant steps. This is because we can find the longest palindromic substring for <i>all</i> substrings that have the <i>same</i> center in a single O(n) pass. For example, if the string is `abcdedcfa`, and since we know that `e` is a palindrome by itself, then when we test `ded`, we don\'t need to start from the center again. We can only test the outer characters, the `d`. And when we test `cdedc`, then since we know `ded` is a palindrome, again, we don\'t need to start from the middle again. We can just confirm that the `c`\'s match up.\n\nNow if we expanded one more character, we would see that `b` does NOT equal `f`. Not only does this mean that this substring is not a palindrome, it also means that all other longer palindromes centered on `e` won\'t be palindromes either, so we don\'t need to test the other substrings and we can just exit early.\n\nSo now the question is, how many different centers can a string have? If the length of the substring is odd, then the center could be any of the characters. If the length of the substring is even, then the center could lie <i>between</i> any two characters. So in total, there are 2n - 1 centers (please see the video for a visualization of this).\n\nSo if visiting each center is O(n) and each palindrome check is O(n), then the algorithm now runs in O(n<sup>2</sup>) time.\n\n# Code\n```\nclass Solution:\n def longestPalindrome(self, s):\n def expand(l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]:\n l -= 1\n r += 1\n return s[l+1:r]\n\n result = ""\n for i in range(len(s)):\n sub1 = expand(i, i)\n if len(sub1) > len(result):\n result = sub1\n sub2 = expand(i, i+1)\n if len(sub2) > len(result):\n result = sub2\n return result\n```
432
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
1,669
33
# Intuition\nUsing two pointers\n\n---\n\n# Solution Video\n\n\n\n\u25A0 Timeline of the video\n`0:04` How did you find longest palindromic substring?\n`0:59` What is start point?\n`1:44` Demonstrate how it works with odd case\n`4:36` How do you calculate length of palindrome we found?\n`7:35` Will you pass all test cases?\n`7:53` Consider even case\n`9:03` How to deal with even case\n`11:26` Coding\n`14:52` Explain how to calculate range of palindrome substring\n`17:18` Time Complexity and Space Complexity\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\n\n\nSubscribers: 2,844\nMy initial goal is 10,000\nThank you for your support!\n\n---\n\n# Approach\n\n### How we think about a solution\n\n---\n\n\nFirst of all, Manacher\'s Algorithm solves this question with $$O(n)$$ time. But in real interviews, nobody will come up with such a solution, so I think $$O(n^2)$$ time is enough to pass the interviews.\n\nIf interviewers ask you about a solution with $$O(n)$$. just leave the room. lol\n\n---\n\nSeriously from here, first of all, we need to understand Palindromic Substring.\n\nWhen I think about a solution, I usually start with the small and simple input, because it\'s easy to understand and find a solution. But this time let\'s start with a big input.\n\n```\nInput: "xkarqzghhgfedcbabcdefgzdekx"\n```\n\n---\n\n\u25A0 Question\n\nHow did you find longest palindromic substring?\n\n---\n\nI believe you choose one character, then expand the range to left and right at the same time. If you find longest palindromic substring directly, you are not a human. lol\n\nActually, that is main idea of my solution today. But problem is that we don\'t know where to start. That\'s why we need to shift start point one by one.\n\n---\n\n\u2B50\uFE0F Points\n\nWe need to shift a start point one by one to check longest palindromic substring.\n\n- What is the start point?\n\nSince palindromic substring is like a mirror from some character, it\'s good idea to consider current index as a center of palindromic substring and expand left and right at the same time.\n\nFor example,\n\n```\nInput = "abcba"\n```\nIf we start from `c`, then\n\n```\n"ab" "c" "ba"\n i\n\ni = curerent index\n```\n"ab" and "ba" is a mirror when "c" is center.\n\n---\n\nLet\'s see one by one.\n\n```\nInput = "abcba"\n```\nWe use `left` and `right` pointers. The both pointers start from index `i` but let me start from next to index `i` to make my explanation short. A single character is definitely a palindrome which is length of `1`.\n```\ni = 0\n\n"abcba"\nlir\n \nCheck left(= out of bounds) and right(= "b")\nmax_length = 1 (= "a")\n\n```\n```\ni = 1\n\n"abcba"\n lir\n\nCheck left(= "a") and right(= "c")\nmax_length = 1 (= "a" or "b")\n\n```\n```\ni = 2\n\n"abcba"\n lir\n\nl = 1\nr = 3\nCheck left(= "b") and right(= "b") \u2192 "bcb" is a palindrome.\uD83D\uDE06\n\nLet\'s expand the range!\n\n"abcba"\n l i r\n\nl = 0\nr = 4\nCheck left(= "a") and right(= "a") \u2192 "abcba" is a palindrome.\uD83D\uDE06\nmax_length = 5 (= "abcba")\n\n "abcba"\n l i r\n\nl = -1\nr = 5\nNow left and right are out of bounds, so we finish iteration.\n\n```\n\nLet me skip the cases where we start from later "b" and "a". We already found the max length. (of course solution code will check the later part)\n\n- How do you calculate length of palindrome we found?\n\nFrom the example above, we found `5` as a max length. how do you calculate it? Simply\n\n```\nright - left\n```\nRight? So,\n```\nright - left\n5 - (-1)\n= 6\n```\n\nWait? It\'s longer than max length we found. The reason why this happens is because the two pointers stop at the next position of max length of palindrome.\n\n```\n"abcba"\n l i r\n```\nWhen `i = 2 left = 0 and right = 4`, we found `5` as a max length, but we don\'t know `5` is the max length in the current iteration, so we try to move to the next place to find longer palindrome, even if we don\'t find it in the end.\n\nThat\'s why, left and right pointer always `overrun` and stop at max length in current iteration + 1, so we need to subtract -1 from right - left.\n```\n\u274C right - left\n\uD83D\uDD34 right - left - 1\n```\nBut still you don\'t get it because we have two pointers expanding at the same time? you think we should subtract `-2`?\n\nThis is calculation of index number, so index number usually starts from `0` not `1`, so right - left includes `-1` already. For example,\n\n```\n"aba"\n l r\n```\nActual length is `3`, but if we calculate the length with index number, that should be `2`(index 2 - index 0), so it\'s already including `-1` compared with actual length. That\'s why when we have two pointers and calculate actual length, right - left - 1 works well.\n\nNow you understand main idea of my solution, but I\'m sure you will not pass all cases. Can you geuss why?\n\nThe answer is I explain the case where we have odd length of input string.\n\n---\n\n\u2B50\uFE0F Points\n\nWe have to care about both odd length of input string and even length of input string\n\n---\n\n```\nInput: "abbc"\n ```\nLet\'s see one by one. we can use the same idea. Let me write briefly.\n\n```\n"abbc"\nlir\n\nmax length = 1\n```\n```\n"abbc"\n lir\n\nmax length = 1\n```\n```\n"abbc"\n lir\n\nmax length = 1\n```\n```\n"abbc"\n lir\n\nmax length = 1\n```\n```\n\u274C Output: "a" or "b" or "c" \n```\nOutput should be\n```\n\uD83D\uDD34 Output: "bb" \n```\n- Why this happens?\n\nRegarding odd length of input array, center position of palindrome is definitely on some charcter.\n```\n"abcba", center is "c"\n```\nHow about even length of input string\n```\n"abbc"\nCenter of palindrome is "b | b" \n```\n`|` is center of palindrome. Not on some character.\n\n- So how can you avoid this?\n\nMy idea to avoid this is we start left with current index and right with current index + 1, so we start interation as if we are coming from between the characters. Let me write only when index = 1.\n```\ncurrent index = 1\n\n lr\n"abbc"\n i\n\nWe found palindrome "bb"\n\n l r\n"abbc"\n i\n\nFinish iteration.\n```\nThen\n```\nright - left - 1\n3 - 0 - 1\n= 2(= length of "bb")\n```\n\nWe can use the same idea for both cases but start position is different, that\'s why we call the same function twice in one iteration.\n\nLet\'s see a real algorithm!\n\n### Algorithm Overview:\n1. Initialize `start` and `end` variables to keep track of the starting and ending indices of the longest palindromic substring.\n2. Iterate through each character of the input string `s`.\n3. For each character, expand around it by calling the `expand_around_center` function with two different center possibilities: (i) the current character as the center (odd length palindrome), and (ii) the current character and the next character as the center (even length palindrome).\n4. Compare the lengths of the two expanded palindromes and update `start` and `end` if a longer palindrome is found.\n5. Finally, return the longest palindromic substring by slicing the input string `s` based on the `start` and `end` indices.\n\n### Detailed Explanation:\n1. Check if the input string `s` is empty. If it is, return an empty string, as there can be no palindromic substring in an empty string.\n\n2. Define a helper function `expand_around_center` that takes three arguments: the input string `s`, and two indices `left` and `right`. This function is responsible for expanding the palindrome around the center indices and returns the length of the palindrome.\n\n3. Initialize `start` and `end` variables to 0. These variables will be used to keep track of the indices of the longest palindromic substring found so far.\n\n4. Iterate through each character of the input string `s` using a for loop.\n\n5. Inside the loop, call the `expand_around_center` function twice: once with `i` as the center for an odd length palindrome and once with `i` and `i + 1` as the center for an even length palindrome.\n\n6. Calculate the length of the palindrome for both cases (odd and even) and store them in the `odd` and `even` variables.\n\n7. Calculate the maximum of the lengths of the two palindromes and store it in the `max_len` variable.\n\n8. Check if the `max_len` is greater than the length of the current longest palindromic substring (`end - start`). If it is, update the `start` and `end` variables to include the new longest palindromic substring. The new `start` is set to `i - (max_len - 1) // 2`, and the new `end` is set to `i + max_len // 2`.\n\n9. Continue the loop until all characters in the input string have been processed.\n\n10. After the loop, return the longest palindromic substring by slicing the input string `s` using the `start` and `end` indices. This substring is inclusive of the characters at the `start` and `end` indices.\n\n\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n\n "n" is the length of the input string "s." This is because the code uses nested loops. The outer loop runs for each character in the string, and the inner loop, expand_around_center, can potentially run for the entire length of the string in the worst case, leading to a quadratic time complexity.\n\n- Space complexity: $$O(1)$$\n\nthe code uses a constant amount of extra space for variables like "start," "end," "left," "right," and function parameters. The space used does not depend on the size of the input string.\n\n```python []\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n if not s:\n return ""\n\n def expand_around_center(s: str, left: int, right: int):\n while left >= 0 and right < len(s) and s[left] == s[right]:\n left -= 1\n right += 1\n return right - left - 1\n\n\n start = 0\n end = 0\n\n for i in range(len(s)):\n odd = expand_around_center(s, i, i)\n even = expand_around_center(s, i, i + 1)\n max_len = max(odd, even)\n \n if max_len > end - start:\n start = i - (max_len - 1) // 2\n end = i + max_len // 2\n \n return s[start:end+1]\n```\n```javascript []\n/**\n * @param {string} s\n * @return {string}\n */\nvar longestPalindrome = function(s) {\n if (!s) {\n return "";\n }\n\n function expandAroundCenter(s, left, right) {\n while (left >= 0 && right < s.length && s[left] === s[right]) {\n left--;\n right++;\n }\n return right - left - 1;\n }\n\n let start = 0;\n let end = 0;\n\n for (let i = 0; i < s.length; i++) {\n const odd = expandAroundCenter(s, i, i);\n const even = expandAroundCenter(s, i, i + 1);\n const max_len = Math.max(odd, even);\n\n if (max_len > end - start) {\n start = i - Math.floor((max_len - 1) / 2);\n end = i + Math.floor(max_len / 2);\n }\n }\n\n return s.substring(start, end + 1); \n};\n```\n```java []\nclass Solution {\n public String longestPalindrome(String s) {\n if (s == null || s.length() == 0) {\n return "";\n }\n\n int start = 0;\n int end = 0;\n\n for (int i = 0; i < s.length(); i++) {\n int odd = expandAroundCenter(s, i, i);\n int even = expandAroundCenter(s, i, i + 1);\n int max_len = Math.max(odd, even);\n\n if (max_len > end - start) {\n start = i - (max_len - 1) / 2;\n end = i + max_len / 2;\n }\n }\n\n return s.substring(start, end + 1); \n }\n\n private int expandAroundCenter(String s, int left, int right) {\n while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {\n left--;\n right++;\n }\n return right - left - 1;\n } \n}\n```\n```C++ []\nclass Solution {\npublic:\n string longestPalindrome(string s) {\n if (s.empty()) {\n return "";\n }\n\n int start = 0;\n int end = 0;\n\n for (int i = 0; i < s.length(); i++) {\n int odd = expandAroundCenter(s, i, i);\n int even = expandAroundCenter(s, i, i + 1);\n int max_len = max(odd, even);\n\n if (max_len > end - start) {\n start = i - (max_len - 1) / 2;\n end = i + max_len / 2;\n }\n }\n\n return s.substr(start, end - start + 1); \n }\n\nprivate:\n int expandAroundCenter(string s, int left, int right) {\n while (left >= 0 && right < s.length() && s[left] == s[right]) {\n left--;\n right++;\n }\n return right - left - 1;\n } \n};\n```\n\nLet me explain this.\n```[]\nif max_len > end - start:\n start = i - (max_len - 1) // 2\n end = i + max_len // 2\n```\nif statement means just when we find longer length.\n\nLet\'s use the same example again.\n```\nInput = "abcba"\n\n```\nWhen `i = 2`, we find 5 as a max length. Let\'s see what will happen.\n\n```[]\nstart = i(2) - (max_len(5) - 1) // 2\nend = i(2) + max_len(5) // 2\n\u2193\nstart = 2 - 2\nend = 2 + 2\n\u2193\nstart = 0\nend = 4\n```\n- Why -1?\n\nThe `-1` is used to calculate the length of the palindrome correctly based on whether it is of odd or even length.\n\nHere, we try to get length of half palindrome except center chracters.\n\nRegarding odd case, actually it works if we don\'t subtract `-1`, because we have only one center chracter and we start from the character.\n\nFor example\n```\n"abcba"\n \u2191\nCenter of palindrome is "c" \n```\nWe will get length of "ab"\n```[]\nno -1 case, 5 // 2 = 2\n-1 case, 4 // 2 = 2\n```\nThe result is the same.\n\nBut regarding even case we start from between characters.\n```\n"abbc"\nCenter of palindrome is "bb" \n```\n\nWe will get length of ""(empty = 0), because center character "bb" itself is whole length of palindrome.\n\n```[]\nno -1 case, 2 // 2 = 1\n-1 case, 1 // 2 = 0\n```\nThe result is different.\n\nIn this case, we have two center charcters, if we remove one character, we can create the same odd case situation from even situaiton, so that we can get correct length except center charcters.\n\nIn this case, i = 1, we get 2 as a max length.\n```\n"abbc"\n```\n\n```[]\nstart = i(1) - (max_len(2) - 1) // 2\nend = i(1) + max_len(2) // 2\n\u2193\nstart = 1 - 0\nend = 1 + 1\n\u2193\nstart = 1\nend = 2\n```\n\nLooks good! \uD83D\uDE06\n\nSince the result is not affected by `-1` in odd case, we subtract `-1` both odd case and even case.\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\n\n\n### My next daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n`0:04` Convert rules to a diagram\n`1:14` How do you count strings with length of n?\n`3:58` Coding\n`7:39` Time Complexity and Space Complexity\n\n### My previous daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of video\n`0:04` Understand question exactly and approach to solve this question\n`1:33` How can you calculate number of subtrees?\n`4:12` Demonstrate how it works\n`8:40` Coding\n`11:32` Time Complexity and Space Complexity
433
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
8,178
45
# 1st Method :- Expand Around Center \uD83D\uDEA9\n## Intuition \uD83D\uDE80:\n\nThe intuition behind this code is to find the longest palindromic substring within a given input string `s`. A palindromic substring is a string that reads the same forwards and backward. To achieve this, the code explores the input string character by character, checking both odd and even-length palindromes by expanding around the center of each character and updating the longest palindrome found so far.\n\n## Approach \uD83D\uDE80:\n\n1. **Initialization**: \n - Check if the input string `s` is empty. If it is, return an empty string because there can\'t be any palindromes in an empty string.\n - Initialize a variable `longestPalindromeIndices` to store the indices of the longest palindrome found. Initially, it\'s set to [0, 0].\n\n2. **Main Loop**:\n - Iterate through the characters of the input string `s` using a for loop.\n\n3. **Odd-Length Palindromes**:\n - For each character at position `i`, check if there is a palindrome centered at that character. This is done by calling the `expandAroundCenter` function with `i` as both the start and end positions.\n - If a longer palindrome is found than the current longest one, update `longestPalindromeIndices` with the new indices.\n\n4. **Even-Length Palindromes**:\n - Check if there is a palindrome centered between the characters at positions `i` and `i + 1`. This is done by calling the `expandAroundCenter` function with `i` as the start position and `i + 1` as the end position.\n - If a longer even-length palindrome is found, update `longestPalindromeIndices` with the new indices.\n\n5. **Continuation**:\n - Continue this process for all characters in the input string. By the end of the loop, you will have identified the indices of the longest palindromic substring.\n\n6. **Result Extraction**:\n - Finally, extract the longest palindromic substring from the input string `s` using the indices obtained in `longestPalindromeIndices`.\n - Return this extracted substring as the result.\n\nThe key idea is to systematically explore the input string, checking both odd and even-length palindromes by expanding around the center of each character and maintaining the information about the longest palindrome found throughout the process. This approach ensures that you find the maximum length palindromic substring within the input string.\n## Complexity \uD83D\uDE81\n### \uD83C\uDFF9 Time complexity: O(N^2)\n\n1. The `expandAroundCenter` function has a time complexity of O(N), where N is the length of the input string `s`. This is because in the worst case, it can expand all the way to the ends of the string.\n2. The `longestPalindrome` function iterates through the characters of the string, and for each character, it may call `expandAroundCenter` once or twice (in the case of even-length palindromes). Therefore, the time complexity of the `longestPalindrome` function is O(N^2).\n\nSo, the overall time complexity of the code is O(N^2) due to the nested loops in the `longestPalindrome` function.\n\n### \uD83C\uDFF9 Space complexity: O(1)\n\nThe space complexity is primarily determined by the additional space used for variables and the recursive call stack.\n\n1. The `expandAroundCenter` function uses a constant amount of extra space, so its space complexity is O(1).\n2. The `longestPalindrome` function uses a few additional integer variables to store indices, but the space used by these variables is also constant, so its space complexity is O(1).\n3. The recursive calls in the `expandAroundCenter` function do not use significant additional space because they are tail-recursive. The stack space used by these calls is O(1).\n\nSo, the overall space complexity of the code is O(1).\n\n## Code \u2712\uFE0F\n``` Java []\nclass Solution {\n public String longestPalindrome(String s) {\n // Check if the input string is empty, return an empty string if so\n if (s.isEmpty())\n return "";\n\n // Initialize variables to store the indices of the longest palindrome found\n int[] longestPalindromeIndices = { 0, 0 };\n\n // Loop through the characters in the input string\n for (int i = 0; i < s.length(); ++i) {\n // Find the indices of the longest palindrome centered at character i\n int[] currentIndices = expandAroundCenter(s, i, i);\n\n // Compare the length of the current palindrome with the longest found so far\n if (currentIndices[1] - currentIndices[0] > longestPalindromeIndices[1] - longestPalindromeIndices[0]) {\n // Update the longest palindrome indices if the current one is longer\n longestPalindromeIndices = currentIndices;\n }\n\n // Check if there is a possibility of an even-length palindrome centered at\n // character i and i+1\n if (i + 1 < s.length() && s.charAt(i) == s.charAt(i + 1)) {\n // Find the indices of the longest even-length palindrome centered at characters\n // i and i+1\n int[] evenIndices = expandAroundCenter(s, i, i + 1);\n\n // Compare the length of the even-length palindrome with the longest found so\n // far\n if (evenIndices[1] - evenIndices[0] > longestPalindromeIndices[1] - longestPalindromeIndices[0]) {\n // Update the longest palindrome indices if the even-length one is longer\n longestPalindromeIndices = evenIndices;\n }\n }\n }\n\n // Extract and return the longest palindrome substring using the indices\n return s.substring(longestPalindromeIndices[0], longestPalindromeIndices[1] + 1);\n }\n\n // Helper function to find and return the indices of the longest palindrome\n // extended from s[i..j] (inclusive) by expanding around the center\n private int[] expandAroundCenter(final String s, int i, int j) {\n // Expand the palindrome by moving outward from the center while the characters\n // match\n while (i >= 0 && j < s.length() && s.charAt(i) == s.charAt(j)) {\n i--; // Move the left index to the left\n j++; // Move the right index to the right\n }\n // Return the indices of the longest palindrome found\n return new int[] { i + 1, j - 1 };\n }\n}\n\n```\n``` C++ []\nclass Solution {\npublic:\n std::string longestPalindrome(std::string s) {\n // Check if the input string is empty, return an empty string if so\n if (s.empty())\n return "";\n\n // Initialize variables to store the indices of the longest palindrome found\n std::vector<int> longestPalindromeIndices = {0, 0};\n\n for (int i = 0; i < s.length(); ++i) {\n // Find the indices of the longest palindrome centered at character i\n std::vector<int> currentIndices = expandAroundCenter(s, i, i);\n\n // Compare the length of the current palindrome with the longest found so far\n if (currentIndices[1] - currentIndices[0] > longestPalindromeIndices[1] - longestPalindromeIndices[0]) {\n longestPalindromeIndices = currentIndices;\n }\n\n // Check if there is a possibility of an even-length palindrome centered at\n // character i and i+1\n if (i + 1 < s.length() && s[i] == s[i + 1]) {\n // Find the indices of the longest even-length palindrome centered at characters\n // i and i+1\n std::vector<int> evenIndices = expandAroundCenter(s, i, i + 1);\n\n // Compare the length of the even-length palindrome with the longest found so far\n if (evenIndices[1] - evenIndices[0] > longestPalindromeIndices[1] - longestPalindromeIndices[0]) {\n longestPalindromeIndices = evenIndices;\n }\n }\n }\n\n // Extract and return the longest palindrome substring using the indices\n return s.substr(longestPalindromeIndices[0], longestPalindromeIndices[1] - longestPalindromeIndices[0] + 1);\n }\n\nprivate:\n // Helper function to find and return the indices of the longest palindrome\n // extended from s[i..j] (inclusive) by expanding around the center\n std::vector<int> expandAroundCenter(const std::string &s, int i, int j) {\n while (i >= 0 && j < s.length() && s[i] == s[j]) {\n --i;\n ++j;\n }\n return {i + 1, j - 1};\n }\n};\n\n```\n``` Python []\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n # Check if the input string is empty, return an empty string if so\n if not s:\n return ""\n\n # Initialize variables to store the indices of the longest palindrome found\n longest_palindrome_indices = [0, 0]\n\n def expand_around_center(s, i, j):\n # Helper function to find and return the indices of the longest palindrome\n # extended from s[i..j] (inclusive) by expanding around the center\n while i >= 0 and j < len(s) and s[i] == s[j]:\n i -= 1\n j += 1\n return [i + 1, j - 1]\n\n for i in range(len(s)):\n current_indices = expand_around_center(s, i, i)\n\n # Compare the length of the current palindrome with the longest found so far\n if current_indices[1] - current_indices[0] > longest_palindrome_indices[1] - longest_palindrome_indices[0]:\n longest_palindrome_indices = current_indices\n\n if i + 1 < len(s) and s[i] == s[i + 1]:\n even_indices = expand_around_center(s, i, i + 1)\n\n # Compare the length of the even-length palindrome with the longest found so far\n if even_indices[1] - even_indices[0] > longest_palindrome_indices[1] - longest_palindrome_indices[0]:\n longest_palindrome_indices = even_indices\n\n # Extract and return the longest palindrome substring using the indices\n return s[longest_palindrome_indices[0]:longest_palindrome_indices[1] + 1]\n\n```\n``` JavaScript []\nvar longestPalindrome = function(s) {\n // Check if the input string is empty, return an empty string if so\n if (s.length === 0)\n return "";\n\n // Initialize variables to store the indices of the longest palindrome found\n let longestPalindromeIndices = [0, 0];\n\n // Loop through the characters in the input string\n for (let i = 0; i < s.length; ++i) {\n // Find the indices of the longest palindrome centered at character i\n let currentIndices = expandAroundCenter(s, i, i);\n\n // Compare the length of the current palindrome with the longest found so far\n if (currentIndices[1] - currentIndices[0] > longestPalindromeIndices[1] - longestPalindromeIndices[0]) {\n // Update the longest palindrome indices if the current one is longer\n longestPalindromeIndices = currentIndices;\n }\n\n // Check if there is a possibility of an even-length palindrome centered at\n // character i and i+1\n if (i + 1 < s.length && s[i] === s[i + 1]) {\n // Find the indices of the longest even-length palindrome centered at characters\n // i and i+1\n let evenIndices = expandAroundCenter(s, i, i + 1);\n\n // Compare the length of the even-length palindrome with the longest found so\n // far\n if (evenIndices[1] - evenIndices[0] > longestPalindromeIndices[1] - longestPalindromeIndices[0]) {\n // Update the longest palindrome indices if the even-length one is longer\n longestPalindromeIndices = evenIndices;\n }\n }\n }\n\n // Extract and return the longest palindrome substring using the indices\n return s.slice(longestPalindromeIndices[0], longestPalindromeIndices[1] + 1);\n}\n\n// Helper function to find and return the indices of the longest palindrome\n// extended from s[i..j] (inclusive) by expanding around the center\nfunction expandAroundCenter(s, i, j) {\n // Expand the palindrome by moving outward from the center while the characters match\n while (i >= 0 && j < s.length && s[i] === s[j]) {\n i--; // Move the left index to the left\n j++; // Move the right index to the right\n }\n // Return the indices of the longest palindrome found\n return [i + 1, j - 1];\n}\n\n```\n``` C# []\npublic class Solution {\n public string LongestPalindrome(string s) {\n // Check if the input string is empty, return an empty string if so\n if (string.IsNullOrEmpty(s))\n return "";\n\n // Initialize variables to store the indices of the longest palindrome found\n int[] longestPalindromeIndices = { 0, 0 };\n\n // Loop through the characters in the input string\n for (int i = 0; i < s.Length; ++i) {\n // Find the indices of the longest palindrome centered at character i\n int[] currentIndices = ExpandAroundCenter(s, i, i);\n\n // Compare the length of the current palindrome with the longest found so far\n if (currentIndices[1] - currentIndices[0] > longestPalindromeIndices[1] - longestPalindromeIndices[0]) {\n // Update the longest palindrome indices if the current one is longer\n longestPalindromeIndices = currentIndices;\n }\n\n // Check if there is a possibility of an even-length palindrome centered at\n // character i and i+1\n if (i + 1 < s.Length && s[i] == s[i + 1]) {\n // Find the indices of the longest even-length palindrome centered at characters\n // i and i+1\n int[] evenIndices = ExpandAroundCenter(s, i, i + 1);\n\n // Compare the length of the even-length palindrome with the longest found so\n // far\n if (evenIndices[1] - evenIndices[0] > longestPalindromeIndices[1] - longestPalindromeIndices[0]) {\n // Update the longest palindrome indices if the even-length one is longer\n longestPalindromeIndices = evenIndices;\n }\n }\n }\n\n // Extract and return the longest palindrome substring using the indices\n return s.Substring(longestPalindromeIndices[0], longestPalindromeIndices[1] - longestPalindromeIndices[0] + 1);\n }\n\n // Helper function to find and return the indices of the longest palindrome\n // extended from s[i..j] (inclusive) by expanding around the center\n private int[] ExpandAroundCenter(string s, int i, int j) {\n // Expand the palindrome by moving outward from the center while the characters match\n while (i >= 0 && j < s.Length && s[i] == s[j]) {\n i--; // Move the left index to the left\n j++; // Move the right index to the right\n }\n // Return the indices of the longest palindrome found\n return new int[] { i + 1, j - 1 };\n }\n}\n```\n``` PHP []\nclass Solution {\n public function longestPalindrome($s) {\n // Check if the input string is empty, return an empty string if so\n if (empty($s)) {\n return "";\n }\n\n // Initialize variables to store the indices of the longest palindrome found\n $longestPalindromeIndices = array(0, 0);\n\n // Loop through the characters in the input string\n for ($i = 0; $i < strlen($s); ++$i) {\n // Find the indices of the longest palindrome centered at character i\n $currentIndices = $this->expandAroundCenter($s, $i, $i);\n\n // Compare the length of the current palindrome with the longest found so far\n if ($currentIndices[1] - $currentIndices[0] > $longestPalindromeIndices[1] - $longestPalindromeIndices[0]) {\n // Update the longest palindrome indices if the current one is longer\n $longestPalindromeIndices = $currentIndices;\n }\n\n // Check if there is a possibility of an even-length palindrome centered at\n // character i and i+1\n if ($i + 1 < strlen($s) && $s[$i] == $s[$i + 1]) {\n // Find the indices of the longest even-length palindrome centered at characters\n // i and i+1\n $evenIndices = $this->expandAroundCenter($s, $i, $i + 1);\n\n // Compare the length of the even-length palindrome with the longest found so\n // far\n if ($evenIndices[1] - $evenIndices[0] > $longestPalindromeIndices[1] - $longestPalindromeIndices[0]) {\n // Update the longest palindrome indices if the even-length one is longer\n $longestPalindromeIndices = $evenIndices;\n }\n }\n }\n\n // Extract and return the longest palindrome substring using the indices\n return substr($s, $longestPalindromeIndices[0], $longestPalindromeIndices[1] - $longestPalindromeIndices[0] + 1);\n }\n\n // Helper function to find and return the indices of the longest palindrome\n // extended from s[i..j] (inclusive) by expanding around the center\n private function expandAroundCenter($s, $i, $j) {\n // Expand the palindrome by moving outward from the center while the characters match\n while ($i >= 0 && $j < strlen($s) && $s[$i] == $s[$j]) {\n $i--; // Move the left index to the left\n $j++; // Move the right index to the right\n }\n // Return the indices of the longest palindrome found\n return array($i + 1, $j - 1);\n }\n}\n```\n![vote.jpg]()\n\n---\n\n# 2nd Method :- Manacher\'s Algorithm \uD83D\uDEA9\n\n## Intuition \uD83D\uDE80:\nThe code implements Manacher\'s algorithm, which is designed to find the longest palindromic substring in a given string. The algorithm is an efficient way to tackle this problem and is based on the following key ideas:\n\n1. Utilize symmetry: Palindromes have a property of symmetry, which means their left and right sides are mirror images of each other. Manacher\'s algorithm takes advantage of this property to optimize the process.\n\n2. Avoid redundant computations: The algorithm uses previously computed information to avoid redundant checks, which makes it more efficient than brute force methods.\n\n## Approach \uD83D\uDE80:\n\n1. **Preprocessing**:\n - The input string `s` is preprocessed to create a modified string `T` with special characters (^, #, and dollar ) inserted between each character to simplify palindrome detection.\n\n2. **Initialization**:\n - Initialize variables:\n - `strLength` for the length of the modified string `T`.\n - `palindromeLengths`, an array to store the lengths of palindromes centered at each position in `T`.\n - `center` for the current center of the palindrome being processed.\n - `rightEdge` for the rightmost edge of the palindrome found so far.\n\n3. **Palindrome Detection**:\n - Loop through the modified string `T` to find palindromes centered at each position.\n - Calculate the length of the palindrome at the current position `i` based on previously computed information and expand it if possible. This is done by comparing characters around the current position.\n - Update `center` and `rightEdge` if a longer palindrome is found.\n\n4. **Find the Longest Palindrome**:\n - After processing the entire modified string `T`, identify the longest palindrome by searching the `palindromeLengths` array for the maximum value.\n - Determine the center of this longest palindrome.\n\n5. **Extract the Result**:\n - Use the information about the longest palindrome (center and length) in the modified string `T` to extract the corresponding substring from the original input string `s`.\n\nThe code effectively implements this approach to find and return the longest palindromic substring in the input string `s`. Manacher\'s algorithm is more efficient than naive methods because it takes advantage of the properties of palindromes and avoids redundant comparisons, making it a good choice for solving this problem.\n\n\n## Complexity \uD83D\uDE81\n### \uD83C\uDFF9 Time complexity: O(N)\nThe time complexity of Manacher\'s algorithm is O(N), where N is the length of the input string `s`. This is because the algorithm processes each character of the modified string exactly once (with some constant factor overhead) in a linear pass. The key factor in achieving this efficiency is the "center expansion" technique used to find palindromes, which avoids unnecessary character comparisons. \n\n### \uD83C\uDFF9 Space complexity: O(N)\nThe space complexity of the code is O(N) as well. This is primarily due to the creation of the modified string `T`, which is constructed by adding extra characters, such as \'^\', \'#\', and \'$\', to the original string. The `P` array used to store the lengths of palindromes at each position also has a space complexity of O(N) because it is an array of the same length as the modified string. The other variables used in the algorithm (e.g., `C`, `R`, and loop counters) have constant space requirements and do not significantly contribute to the space complexity.\n\nSo, in terms of both time and space complexity, this code is very efficient for finding the longest palindromic substring in a string.\n\n\n## Code \u2712\uFE0F\n``` Java []\npublic class Solution {\n public String longestPalindrome(String s) {\n // Step 1: Preprocess the input string\n StringBuilder processedStr = new StringBuilder("^#");\n for (char c : s.toCharArray()) {\n processedStr.append(c).append("#");\n }\n processedStr.append("$");\n String modifiedString = processedStr.toString();\n\n // Step 2: Initialize variables for the algorithm\n int strLength = modifiedString.length();\n int[] palindromeLengths = new int[strLength];\n int center = 0; // Current center of the palindrome\n int rightEdge = 0; // Rightmost edge of the palindrome\n\n // Step 3: Loop through the modified string to find palindromes\n for (int i = 1; i < strLength - 1; i++) {\n palindromeLengths[i] = (rightEdge > i) ? Math.min(rightEdge - i, palindromeLengths[2 * center - i]) : 0;\n \n // Expand the palindrome around the current character\n while (modifiedString.charAt(i + 1 + palindromeLengths[i]) == modifiedString.charAt(i - 1 - palindromeLengths[i])) {\n palindromeLengths[i]++;\n }\n \n // Update the rightmost edge and center if necessary\n if (i + palindromeLengths[i] > rightEdge) {\n center = i;\n rightEdge = i + palindromeLengths[i];\n }\n }\n\n // Step 4: Find the longest palindrome and its center\n int maxLength = 0;\n int maxCenter = 0;\n for (int i = 0; i < strLength; i++) {\n if (palindromeLengths[i] > maxLength) {\n maxLength = palindromeLengths[i];\n maxCenter = i;\n }\n }\n \n // Step 5: Extract the longest palindrome from the modified string\n int start = (maxCenter - maxLength) / 2;\n int end = start + maxLength;\n\n // Return the longest palindrome in the original string\n return s.substring(start, end);\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n std::string longestPalindrome(std::string s) {\n // Step 1: Preprocess the input string\n std::string processedStr = "^#";\n for (char c : s) {\n processedStr.push_back(c);\n processedStr.push_back(\'#\');\n }\n processedStr.push_back(\'$\');\n\n // Step 2: Initialize variables for the algorithm\n int strLength = processedStr.length();\n std::vector<int> palindromeLengths(strLength, 0);\n int center = 0; // Current center of the palindrome\n int rightEdge = 0; // Rightmost edge of the palindrome\n\n // Step 3: Loop through the modified string to find palindromes\n for (int i = 1; i < strLength - 1; i++) {\n palindromeLengths[i] = (rightEdge > i) ? std::min(rightEdge - i, palindromeLengths[2 * center - i]) : 0;\n\n // Expand the palindrome around the current character\n while (processedStr[i + 1 + palindromeLengths[i]] == processedStr[i - 1 - palindromeLengths[i]]) {\n palindromeLengths[i]++;\n }\n\n // Update the rightmost edge and center if necessary\n if (i + palindromeLengths[i] > rightEdge) {\n center = i;\n rightEdge = i + palindromeLengths[i];\n }\n }\n\n // Step 4: Find the longest palindrome and its center\n int maxLength = 0;\n int maxCenter = 0;\n for (int i = 0; i < strLength; i++) {\n if (palindromeLengths[i] > maxLength) {\n maxLength = palindromeLengths[i];\n maxCenter = i;\n }\n }\n\n // Step 5: Extract the longest palindrome from the modified string\n int start = (maxCenter - maxLength) / 2;\n int end = start + maxLength;\n\n // Return the longest palindrome in the original string\n return s.substr(start, end - start);\n }\n};\n```\n``` Python []\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n # Step 1: Preprocess the input string\n processed_str = "^#"\n for c in s:\n processed_str += c + "#"\n processed_str += "$"\n\n # Step 2: Initialize variables for the algorithm\n str_length = len(processed_str)\n palindrome_lengths = [0] * str_length\n center = 0 # Current center of the palindrome\n right_edge = 0 # Rightmost edge of the palindrome\n\n # Step 3: Loop through the modified string to find palindromes\n for i in range(1, str_length - 1):\n palindrome_lengths[i] = min(right_edge - i, palindrome_lengths[2 * center - i]) if right_edge > i else 0\n\n # Expand the palindrome around the current character\n while processed_str[i + 1 + palindrome_lengths[i]] == processed_str[i - 1 - palindrome_lengths[i]]:\n palindrome_lengths[i] += 1\n\n # Update the rightmost edge and center if necessary\n if i + palindrome_lengths[i] > right_edge:\n center = i\n right_edge = i + palindrome_lengths[i]\n\n # Step 4: Find the longest palindrome and its center\n max_length = 0\n max_center = 0\n for i in range(str_length):\n if palindrome_lengths[i] > max_length:\n max_length = palindrome_lengths[i]\n max_center = i\n\n # Step 5: Extract the longest palindrome from the modified string\n start = (max_center - max_length) // 2\n end = start + max_length\n\n # Return the longest palindrome in the original string\n return s[start:end]\n```\n``` JavaScript []\nclass Solution {\n longestPalindrome(s) {\n // Step 1: Preprocess the input string\n let processedStr = "^#";\n for (let i = 0; i < s.length; i++) {\n processedStr += s[i] + "#";\n }\n processedStr += "$";\n let modifiedString = processedStr;\n\n // Step 2: Initialize variables for the algorithm\n let strLength = modifiedString.length;\n let palindromeLengths = new Array(strLength).fill(0);\n let center = 0; // Current center of the palindrome\n let rightEdge = 0; // Rightmost edge of the palindrome\n\n // Step 3: Loop through the modified string to find palindromes\n for (let i = 1; i < strLength - 1; i++) {\n palindromeLengths[i] = (rightEdge > i) ? Math.min(rightEdge - i, palindromeLengths[2 * center - i]) : 0;\n\n // Expand the palindrome around the current character\n while (modifiedString[i + 1 + palindromeLengths[i]] === modifiedString[i - 1 - palindromeLengths[i]]) {\n palindromeLengths[i]++;\n }\n\n // Update the rightmost edge and center if necessary\n if (i + palindromeLengths[i] > rightEdge) {\n center = i;\n rightEdge = i + palindromeLengths[i];\n }\n }\n\n // Step 4: Find the longest palindrome and its center\n let maxLength = 0;\n let maxCenter = 0;\n for (let i = 0; i < strLength; i++) {\n if (palindromeLengths[i] > maxLength) {\n maxLength = palindromeLengths[i];\n maxCenter = i;\n }\n }\n\n // Step 5: Extract the longest palindrome from the modified string\n let start = (maxCenter - maxLength) / 2;\n let end = start + maxLength;\n\n // Return the longest palindrome in the original string\n return s.substring(start, end);\n }\n}\n```\n``` C# []\npublic class Solution {\n public string LongestPalindrome(string s) {\n // Step 1: Preprocess the input string\n StringBuilder processedStr = new StringBuilder("^#");\n foreach (char c in s) {\n processedStr.Append(c).Append("#");\n }\n processedStr.Append("$");\n string modifiedString = processedStr.ToString();\n\n // Step 2: Initialize variables for the algorithm\n int strLength = modifiedString.Length;\n int[] palindromeLengths = new int[strLength];\n int center = 0; // Current center of the palindrome\n int rightEdge = 0; // Rightmost edge of the palindrome\n\n // Step 3: Loop through the modified string to find palindromes\n for (int i = 1; i < strLength - 1; i++) {\n palindromeLengths[i] = (rightEdge > i) ? Math.Min(rightEdge - i, palindromeLengths[2 * center - i]) : 0;\n\n // Expand the palindrome around the current character\n while (modifiedString[i + 1 + palindromeLengths[i]] == modifiedString[i - 1 - palindromeLengths[i]]) {\n palindromeLengths[i]++;\n }\n\n // Update the rightmost edge and center if necessary\n if (i + palindromeLengths[i] > rightEdge) {\n center = i;\n rightEdge = i + palindromeLengths[i];\n }\n }\n\n // Step 4: Find the longest palindrome and its center\n int maxLength = 0;\n int maxCenter = 0;\n for (int i = 0; i < strLength; i++) {\n if (palindromeLengths[i] > maxLength) {\n maxLength = palindromeLengths[i];\n maxCenter = i;\n }\n }\n\n // Step 5: Extract the longest palindrome from the modified string\n int start = (maxCenter - maxLength) / 2;\n int end = start + maxLength;\n\n // Return the longest palindrome in the original string\n return s.Substring(start, end - start);\n }\n}\n```\n``` PHP []\nclass Solution {\n public function longestPalindrome($s) {\n // Step 1: Preprocess the input string\n $processedStr = "^#";\n for ($i = 0; $i < strlen($s); $i++) {\n $processedStr .= $s[$i] . "#";\n }\n $processedStr .= "$";\n $modifiedString = $processedStr;\n\n // Step 2: Initialize variables for the algorithm\n $strLength = strlen($modifiedString);\n $palindromeLengths = array_fill(0, $strLength, 0);\n $center = 0; // Current center of the palindrome\n $rightEdge = 0; // Rightmost edge of the palindrome\n\n // Step 3: Loop through the modified string to find palindromes\n for ($i = 1; $i < $strLength - 1; $i++) {\n $palindromeLengths[$i] = ($rightEdge > $i) ? min($rightEdge - $i, $palindromeLengths[2 * $center - $i]) : 0;\n\n // Expand the palindrome around the current character\n while ($modifiedString[$i + 1 + $palindromeLengths[$i]] == $modifiedString[$i - 1 - $palindromeLengths[$i]]) {\n $palindromeLengths[$i]++;\n }\n\n // Update the rightmost edge and center if necessary\n if ($i + $palindromeLengths[$i] > $rightEdge) {\n $center = $i;\n $rightEdge = $i + $palindromeLengths[$i];\n }\n }\n\n // Step 4: Find the longest palindrome and its center\n $maxLength = 0;\n $maxCenter = 0;\n for ($i = 0; $i < $strLength; $i++) {\n if ($palindromeLengths[$i] > $maxLength) {\n $maxLength = $palindromeLengths[$i];\n $maxCenter = $i;\n }\n }\n\n // Step 5: Extract the longest palindrome from the modified string\n $start = ($maxCenter - $maxLength) / 2;\n $end = $start + $maxLength;\n\n // Return the longest palindrome in the original string\n return substr($s, $start, $end - $start);\n }\n}\n```\n\n![upvote.png]()\n# Up Vote Guys\n
434
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
9,619
37
# Intuition\nWhen tackling the problem of finding the longest palindromic substring, one might initially think of generating all possible substrings and checking each for palindromicity. However, this approach is inefficient. A more nuanced understanding would lead us to the realization that for each character in the string, it could potentially be the center of a palindrome. Using this intuition, we can attempt to expand around each character to check for palindromes. But how can we make sure to handle palindromes of both even and odd lengths? This is where Manacher\'s algorithm comes in, transforming the string in a way that we only need to handle palindromes centered around a single character.\n\n## Live Codding & Comments\n\n\n# Approach\n\n**Manacher\'s Algorithm** is a powerful technique that allows us to find the longest palindromic substring in a given string in linear time. Here\'s a detailed breakdown of the algorithm\'s approach:\n\n### 1. String Transformation\nWe first transform the original string to simplify the algorithm. This transformation achieves two things:\n- It ensures that every potential center of a palindrome is surrounded by identical characters (`#`), which simplifies the process of expanding around a center.\n- It adds special characters `^` at the beginning and `$` at the end of the string to avoid any boundary checks during the palindrome expansion.\n\nFor instance, the string `"babad"` is transformed into `"^#b#a#b#a#d#$"`.\n\n### 2. Initialization\nWe maintain an array `P` with the same length as the transformed string. Each entry `P[i]` denotes the radius (half-length) of the palindrome centered at position `i`.\n\nWe also introduce two critical pointers:\n- `C`: The center of the palindrome that has the rightmost boundary.\n- `R`: The right boundary of this palindrome.\n\nBoth `C` and `R` start at the beginning of the string.\n\n### 3. Iterating Through the String\nFor every character in the transformed string, we consider it as a potential center for a palindrome.\n\n**a. Using Previously Computed Information**: \nIf the current position is to the left of `R`, its mirror position about the center `C` might have information about a palindrome centered at the current position. We can leverage this to avoid unnecessary calculations.\n\n**b. Expanding Around the Center**: \nStarting from the current radius at position `i` (which might be derived from its mirror or initialized to 0), we attempt to expand around `i` and check if the characters are the same.\n\n**c. Updating `C` and `R`**: \nIf the palindrome centered at `i` extends beyond `R`, we update `C` to `i` and `R` to the new boundary.\n\n### 4. Extracting the Result\nOnce we\'ve computed the palindromic radii for all positions in the transformed string, we find the position with the largest radius in `P`. This position represents the center of the longest palindromic substring. We then extract and return this palindrome from the original string.\n\n# Complexity\n- Time complexity: $O(n)$\nManacher\'s algorithm processes each character in the transformed string once, making the time complexity linear.\n\n- Space complexity: $O(n)$\nWe use an array `P` to store the palindrome radii, making the space complexity linear as well.\n\n# Code\n``` Python []\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n T = \'#\'.join(\'^{}$\'.format(s))\n n = len(T)\n P = [0] * n\n C = R = 0\n \n for i in range(1, n-1):\n P[i] = (R > i) and min(R - i, P[2*C - i])\n while T[i + 1 + P[i]] == T[i - 1 - P[i]]:\n P[i] += 1\n \n if i + P[i] > R:\n C, R = i, i + P[i]\n \n max_len, center_index = max((n, i) for i, n in enumerate(P))\n return s[(center_index - max_len) // 2: (center_index + max_len) // 2]\n```\n``` Go []\nfunc longestPalindrome(s string) string {\n T := "^#" + strings.Join(strings.Split(s, ""), "#") + "#$"\n n := len(T)\n P := make([]int, n)\n C, R := 0, 0\n \n for i := 1; i < n-1; i++ {\n if R > i {\n P[i] = min(R-i, P[2*C-i])\n }\n for T[i+1+P[i]] == T[i-1-P[i]] {\n P[i]++\n }\n if i + P[i] > R {\n C, R = i, i + P[i]\n }\n }\n \n maxLen := 0\n centerIndex := 0\n for i, v := range P {\n if v > maxLen {\n maxLen = v\n centerIndex = i\n }\n }\n return s[(centerIndex-maxLen)/2 : (centerIndex+maxLen)/2]\n}\n\nfunc min(a, b int) int {\n if a < b {\n return a\n }\n return b\n}\n```\n``` Java []\npublic class Solution {\n public String longestPalindrome(String s) {\n StringBuilder sb = new StringBuilder("^#");\n for (char c : s.toCharArray()) {\n sb.append(c).append("#");\n }\n sb.append("$");\n String T = sb.toString();\n \n int n = T.length();\n int[] P = new int[n];\n int C = 0, R = 0;\n \n for (int i = 1; i < n-1; i++) {\n P[i] = (R > i) ? Math.min(R - i, P[2*C - i]) : 0;\n while (T.charAt(i + 1 + P[i]) == T.charAt(i - 1 - P[i]))\n P[i]++;\n \n if (i + P[i] > R) {\n C = i;\n R = i + P[i];\n }\n }\n \n int max_len = 0, center_index = 0;\n for (int i = 0; i < n; i++) {\n if (P[i] > max_len) {\n max_len = P[i];\n center_index = i;\n }\n }\n return s.substring((center_index - max_len) / 2, (center_index + max_len) / 2);\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n std::string longestPalindrome(std::string s) {\n std::string T = "^#";\n for (char c : s) {\n T += c;\n T += \'#\';\n }\n T += "$";\n\n int n = T.size();\n std::vector<int> P(n, 0);\n int C = 0, R = 0;\n\n for (int i = 1; i < n-1; ++i) {\n P[i] = (R > i) ? std::min(R - i, P[2*C - i]) : 0;\n while (T[i + 1 + P[i]] == T[i - 1 - P[i]])\n P[i]++;\n\n if (i + P[i] > R) {\n C = i;\n R = i + P[i];\n }\n }\n\n int max_len = *std::max_element(P.begin(), P.end());\n int center_index = std::distance(P.begin(), std::find(P.begin(), P.end(), max_len));\n return s.substr((center_index - max_len) / 2, max_len);\n }\n};\n```\n``` PHP []\nclass Solution {\n function longestPalindrome($s) {\n $T = "^#".implode("#", str_split($s))."#$";\n $n = strlen($T);\n $P = array_fill(0, $n, 0);\n $C = $R = 0;\n \n for ($i = 1; $i < $n-1; $i++) {\n $P[$i] = ($R > $i) ? min($R - $i, $P[2*$C - $i]) : 0;\n while ($T[$i + 1 + $P[$i]] == $T[$i - 1 - $P[$i]])\n $P[$i]++;\n \n if ($i + $P[$i] > $R) {\n $C = $i;\n $R = $i + $P[$i];\n }\n }\n \n $max_len = max($P);\n $center_index = array_search($max_len, $P);\n return substr($s, ($center_index - $max_len) / 2, $max_len);\n }\n}\n```\n``` C# []\npublic class Solution {\n public string LongestPalindrome(string s) {\n string T = "^#" + string.Join("#", s.ToCharArray()) + "#$";\n int n = T.Length;\n int[] P = new int[n];\n int C = 0, R = 0;\n \n for (int i = 1; i < n-1; i++) {\n P[i] = (R > i) ? Math.Min(R - i, P[2*C - i]) : 0;\n while (T[i + 1 + P[i]] == T[i - 1 - P[i]])\n P[i]++;\n \n if (i + P[i] > R) {\n C = i;\n R = i + P[i];\n }\n }\n \n int max_len = P.Max();\n int center_index = Array.IndexOf(P, max_len);\n return s.Substring((center_index - max_len) / 2, max_len);\n }\n}\n```\n``` JavaScript []\nvar longestPalindrome = function(s) {\n let T = "^#" + s.split("").join("#") + "#$";\n let n = T.length;\n let P = new Array(n).fill(0);\n let C = 0, R = 0;\n \n for (let i = 1; i < n-1; i++) {\n P[i] = (R > i) ? Math.min(R - i, P[2*C - i]) : 0;\n while (T[i + 1 + P[i]] === T[i - 1 - P[i]])\n P[i]++;\n \n if (i + P[i] > R) {\n C = i;\n R = i + P[i];\n }\n }\n \n let max_len = Math.max(...P);\n let center_index = P.indexOf(max_len);\n return s.substring((center_index - max_len) / 2, (center_index + max_len) / 2);\n }\n```\n\n# Performance\n| Language | Runtime (ms) | Memory (MB) |\n|------------|--------------|-------------|\n| Go | 5 | 5.2 |\n| Java | 8 | 43.2 |\n| C++ | 11 | 8.7 |\n| PHP | 18 | 19.4 |\n| C# | 67 | 40.5 |\n| JavaScript | 71 | 45.6 |\n| Python3 | 90 | 16.4 |\n\n![v445.png]()\n\n\n# What did we learn?\nWe learned about Manacher\'s algorithm, a linear-time solution to the longest palindromic substring problem. By transforming the string and leveraging the properties of palindromes, we can efficiently determine the longest palindrome without checking every possible substring.\n\n# Why does it work?\nManacher\'s algorithm works by taking advantage of the symmetrical nature of palindromes. It avoids redundant checks by using the information from previously computed palindromes. The transformation of the string ensures that we don\'t need to separately handle even and odd length palindromes.\n\n# What is the optimization here?\nThe brilliance of Manacher\'s algorithm lies in its ability to reduce the problem from quadratic to linear time. By using the palindrome information already computed and the nature of palindromes themselves, the algorithm avoids unnecessary checks, making it one of the most optimal solutions for this problem.
436
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
116,124
722
#### Approach (implemented Dp rules)\n* ##### Definition : the row and col in the dp table represent the slicing index on the string s (inclusive)\n* ##### example s = \'babad\' -- > dp[2][3] = s[2:3] = ba\n##### Steps : \n* ##### Fill the diagonal with True, b/c every single character by itself is palindrom \n* ##### Don\'t traverse in the bottom part of the diagonal \n\t* ##### Becuase, that represent reverse slicing (which is not valid)\n##### \n* ##### Iterate backward starting from the most right bottom cell to top (only on the right side of the digonal) \n\t* ##### How ? \n\t\t* ##### \t\tStart itertating backward for the outer loop (i) and for the inner loop (j) iterate forward starting from the index of outer loop ) : see the code (the for loops) \n##### \n* ##### - Pick character from the input string based on the at i and j position, If the characters matches : you need to check two conditions\n\t* ##### 1. If the length of the sub_string is just one (a letter matching is good to be a palindrom)\n\t* ##### 2. But if the length of the sub_string is > 1 \n\t\t* ##### - You need to check if the inner sub_sting is also palindrom\n\t\t* ##### - How ?\n\t\t\t* ##### - You go to the left bottom corner and check if it is True \n\t\t\t* ##### - Left bottom corrner represent the inner sub_string of the current_sub_string \n\t\t\t\t* ##### -Eg. if dp[i][j]= cur_sub_string = \'ababa\' --> True because dp[i+1][j-1] is True\n\t\t\t\t* ##### dp[i+1][j-1] = \'bab\' = True\n\t\t\t\t* ##### .Howerver if dp[i][j]= cur_sub_string = \'abaca\' --> False because dp[i+1][j-1] is False\n\t\t\t\t* ##### dp[i+1][j-1] = \'bac\' = False --> not palindrom \n\t\t* ##### \n\t\t* ##### If dp[i+1][j-1] == True:\n\t\t\t* ##### Ok that means the current sub_string is also palindrom \n\t\t* ##### - Now compare the length of the current_palindrom sub_string with the prvious longest one and take the max\n* ##### - Else : the characters don\'t match\n\t* ##### Just pass\n* ##### - Finally return the maximum number in the dp\n* ##### If this solution/explanation helps you, don\'t forget to upvote as appreciation\n\n```\ndef longestPalindrome(self, s):\n longest_palindrom = \'\'\n dp = [[0]*len(s) for _ in range(len(s))]\n #filling out the diagonal by 1\n for i in range(len(s)):\n dp[i][i] = True\n longest_palindrom = s[i]\n\t\t\t\n # filling the dp table\n for i in range(len(s)-1,-1,-1):\n\t\t\t\t# j starts from the i location : to only work on the upper side of the diagonal \n for j in range(i+1,len(s)): \n if s[i] == s[j]: #if the chars mathces\n # if len slicied sub_string is just one letter if the characters are equal, we can say they are palindomr dp[i][j] =True \n #if the slicied sub_string is longer than 1, then we should check if the inner string is also palindrom (check dp[i+1][j-1] is True)\n if j-i ==1 or dp[i+1][j-1] is True:\n dp[i][j] = True\n # we also need to keep track of the maximum palindrom sequence \n if len(longest_palindrom) < len(s[i:j+1]):\n longest_palindrom = s[i:j+1]\n \n return longest_palindrom\n```
437
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
146,748
1,167
Intuitively, we list all the substrings, pick those palindromic, and get the longest one. This approach takes O(n^3) time complexity, where n is the length of `s`.\n\n# Dynamic Programming\nThe problem can be broken down into subproblems which are reused several times. Overlapping subproblems lead us to Dynamic Programming.\n\nWe decompose the problem as follows:\n\n- State variable\nThe `start` index and `end` index of a substring can identify a state, which **influences our decision**.\nSo the state variable is `state(start, end)` indicates whether `s[start, end]` inclusive is palindromic\n\n- Goal state\n`max(end - start + 1)` for all `state(start, end) = true`\n\n- State transition\n```\nfor start = end (e.g. \'a\'), state(start, end) is True\nfor start + 1 = end (e.g. \'aa\'), state(start, end) is True if s[start] = s[end]\nfor start + 2 = end (e.g. \'aba\'), state(start, end) is True if s[start] = s[end] and state(start + 1, end - 1)\nfor start + 3 = end (e.g. \'abba\'), state(start, end) is True if s[start] = s[end] and state(start + 1, end - 1)\n...\n```\n\nThis approach takes O(n^2) time complexity, O(n^2) space complexity, where n is the length of `s`.\n\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n n = len(s)\n dp = [[False] * n for _ in range(n)]\n for i in range(n):\n dp[i][i] = True\n longest_palindrome_start, longest_palindrome_len = 0, 1\n\n for end in range(0, n):\n for start in range(end - 1, -1, -1):\n # print(\'start: %s, end: %s\' % (start, end))\n if s[start] == s[end]:\n if end - start == 1 or dp[start + 1][end - 1]:\n dp[start][end] = True\n palindrome_len = end - start + 1\n if longest_palindrome_len < palindrome_len:\n longest_palindrome_start = start\n longest_palindrome_len = palindrome_len\n return s[longest_palindrome_start: longest_palindrome_start + longest_palindrome_len]\n```\n\n# Two pointers\nThis approach takes O(n^2) time complexity, O(1) space complexity, where n is the length of `s`.\n\nFor each character `s[i]`, we get the first character to its right which isn\'t equal to `s[i]`.\nThen `s[i, right - 1]` inclusive are equal characters e.g. "aaa".\nThen we make `left = i - 1`, while s[left] == s[right], s[left, right] inclusive is palindrome, and we keep extending both ends by `left -= 1, right += 1`.\nFinally we update the tracked longest palindrome if needed.\n\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n n = len(s)\n longest_palindrome_start, longest_palindrome_len = 0, 1\n\n for i in range(0, n):\n right = i\n while right < n and s[i] == s[right]:\n right += 1\n # s[i, right - 1] inclusive are equal characters e.g. "aaa"\n \n # while s[left] == s[right], s[left, right] inclusive is palindrome e.g. "baaab"\n left = i - 1\n while left >= 0 and right < n and s[left] == s[right]:\n left -= 1\n right += 1\n \n # s[left + 1, right - 1] inclusive is palindromic\n palindrome_len = right - left - 1\n if palindrome_len > longest_palindrome_len:\n longest_palindrome_len = palindrome_len\n longest_palindrome_start = left + 1\n \n return s[longest_palindrome_start: longest_palindrome_start + longest_palindrome_len]\n \n```\n
438
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
698
5
# Hello LeetCode fans,\nBelow I presented a solution to the problem (5.Longest Palindromic Substring).\nIf you found it `useful or informative`,\nClick the "`UPVOTE`" button below and it means I was able to `help someone`.\nYour UPVOTES encourage me and others who are`working hard` to improve their problem solving skills.\n\n# Code\n# Solution C++\n```\nclass Solution {\npublic:\n string ans = "";\n void expand(string &s , int left ,int right)\n {\n while(left >= 0 && right < s.size())\n {\n if(s[left] != s[right])\n break;\n left--,right++;\n }\n if(ans.size() < right - left )\n ans = s.substr(left + 1 , right - left - 1);\n }\n string longestPalindrome(string s) {\n for(int i = 0 ; i < s.size() ; i++)\n {\n expand(s , i , i);\n expand(s , i , i+1);\n }\n return ans;\n }\n};\n```\n# Solution JAVA\n````\nclass Solution {\n int maxLen = 0;\n int lo = 0;\n public String longestPalindrome(String s) {\n char[] input = s.toCharArray();\n if(s.length() < 2) {\n return s;\n }\n \n for(int i = 0; i<input.length; i++) {\n expandPalindrome(input, i, i);\n expandPalindrome(input, i, i+1);\n }\n return s.substring(lo, lo+maxLen);\n }\n \n public void expandPalindrome(char[] s, int j, int k) {\n while(j >= 0 && k < s.length && s[j] == s[k]) {\n j--;\n k++;\n }\n if(maxLen < k - j - 1) {\n maxLen = k - j - 1;\n lo = j+1;\n }\n }\n}\n````\n# Solution Python\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n ans=\'\'\n for i in range(len(s)):\n ans=max(ans,expand(s,i,i), expand(s,i,i+1), key=len)\n return ans\n \ndef expand(s,i,j):\n while i>=0 and j<len(s) and s[i]==s[j]:\n i-=1\n j+=1\n return s[i+1:j]\n\n```\n# Solution C\n```\nint maxVal(int a, int b) {\n return a > b ? a : b;\n}\n\nint extend(char *s, int start, int end) {\n int len = strlen(s);\n for(; start >= 0 && end < len; start--, end++) {\n if(*(s + start) != *(s + end))\n break;\n }\n return end - start - 1;\n}\n\nchar * longestPalindrome(char * s){\n int max = 0, idx = 0, len = strlen(s);\n for(int i = 0; i < len; i++) {\n int len1 = extend(s, i, i); /* For even string */\n int len2 = extend(s, i, i + 1); /* For odd string */\n if (max < maxVal(len1, len2)) {\n idx = (len1 > len2) ? (i - len1 / 2) : (i - len2 / 2 + 1);\n max = maxVal(len1, len2);\n }\n }\n char *res = malloc((max+1) *sizeof(char));\n memcpy(res, &s[idx], max);\n res[max] = \'\\0\';\n return res;\n}\n```\n![image.png]()\n\n# Thanks for all!\n
439
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
473,730
1,347
The performance is pretty good, surprisingly.\n\n public class Solution {\n\tprivate int lo, maxLen;\n\t\n public String longestPalindrome(String s) {\n \tint len = s.length();\n \tif (len < 2)\n \t\treturn s;\n \t\n for (int i = 0; i < len-1; i++) {\n \textendPalindrome(s, i, i); //assume odd length, try to extend Palindrome as possible\n \textendPalindrome(s, i, i+1); //assume even length.\n }\n return s.substring(lo, lo + maxLen);\n }\n\n\tprivate void extendPalindrome(String s, int j, int k) {\n\t\twhile (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) {\n\t\t\tj--;\n\t\t\tk++;\n\t\t}\n\t\tif (maxLen < k - j - 1) {\n\t\t\tlo = j + 1;\n\t\t\tmaxLen = k - j - 1;\n\t\t}\n\t}}
443
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
3,086
20
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe given code is an implementation of the "Expand Around Center" approach for finding the longest palindromic substring in a given string. This approach works by iterating through each character in the string and expanding around it to check for palindromes. It takes advantage of the fact that a palindrome can be centered around a single character (in the case of odd-length palindromes) or between two characters (in the case of even-length palindromes). By expanding from each character, it identifies the longest palindrome.\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. The `expandAroundCenter` function takes a string `s` and two indices `left` and `right`. It starts from the characters at these indices and expands outwards while checking if the characters are the same. When different characters are encountered, the function returns the substring between `left` and `right`, which is a palindrome.\n\n2. The `longestPalindrome` function initializes an empty string longest to keep track of the `longest` palindromic substring found.\n\n3. It iterates through the characters of the input string s. For each character, it calls `expandAroundCenter` twice, once assuming an odd-length palindrome (with the character as the center) and once assuming an even-length palindrome (with the character and the next character as the center).\n\n4. If the length of the palindrome found (either odd or even) is greater than the length of the `longest` palindrome found so far, it updates the `longest` substring.\n\n5. After iterating through all characters, it returns the longest palindromic substring found.\n\n---\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this code is O(n^2), where \'n\' is the length of the input string \'s\'. This is because, in the worst case, for each of the \'n\' characters in \'s\', we may expand to both the left and the right, resulting in a quadratic time complexity.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of this code is O(1) because it doesn\'t use any additional data structures that grow with the input size. The space is primarily used for the variables and temporary substrings, which don\'t depend on the input size.\n\n---\n\n# \uD83D\uDCA1If you have come this far, then i would like to request you to please upvote this solution\u2763\uFE0F\uD83D\uDCA1So that it could reach out to another one\uD83D\uDD25\uD83D\uDD25\n\n---\n\n```C++ []\n#include <iostream>\nusing namespace std;\n\nclass Solution {\npublic:\nstring expandAroundCenter(string s, int left, int right) {\n while (left >= 0 && right < s.length() && s[left] == s[right]) {\n left--;\n right++;\n }\n return s.substr(left + 1, right - left - 1);\n}\n\nstring longestPalindrome(string s) {\n string longest = "";\n for (int i = 0; i < s.length(); i++) {\n string odd = expandAroundCenter(s, i, i);\n string even = expandAroundCenter(s, i, i + 1);\n if (odd.length() > longest.length()) longest = odd;\n if (even.length() > longest.length()) longest = even;\n }\n return longest;\n}\n};\n```\n```Java []\npublic class Solution {\n public String expandAroundCenter(String s, int left, int right) {\n while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {\n left--;\n right++;\n }\n return s.substring(left + 1, right);\n }\n\n public String longestPalindrome(String s) {\n String longest = "";\n for (int i = 0; i < s.length(); i++) {\n String odd = expandAroundCenter(s, i, i);\n String even = expandAroundCenter(s, i, i + 1);\n if (odd.length() > longest.length()) {\n longest = odd;\n }\n if (even.length() > longest.length()) {\n longest = even;\n }\n }\n return longest;\n }\n\n public static void main(String[] args) {\n Solution solution = new Solution();\n String s = "babad";\n String result = solution.longestPalindrome(s);\n System.out.println("Longest Palindromic Substring: " + result);\n }\n}\n\n```\n```Python []\nclass Solution:\n def expandAroundCenter(self, s, left, right):\n while left >= 0 and right < len(s) and s[left] == s[right]:\n left -= 1\n right += 1\n return s[left + 1:right]\n\n def longestPalindrome(self, s):\n longest = ""\n for i in range(len(s)):\n odd = self.expandAroundCenter(s, i, i)\n even = self.expandAroundCenter(s, i, i + 1)\n if len(odd) > len(longest):\n longest = odd\n if len(even) > len(longest):\n longest = even\n return longest\n\nsolution = Solution()\ns = "babad"\nresult = solution.longestPalindrome(s)\nprint("Longest Palindromic Substring:", result)\n\n```\n```Javascript []\n/**\n * @param {string} s\n * @return {string}\n */\nvar longestPalindrome = function(s) {\n function expandAroundCenter(left, right) {\n while (left >= 0 && right < s.length && s[left] === s[right]) {\n left--;\n right++;\n }\n return s.substring(left + 1, right);\n }\n\n let longest = "";\n\n for (let i = 0; i < s.length; i++) {\n let odd = expandAroundCenter(i, i);\n let even = expandAroundCenter(i, i + 1);\n\n if (odd.length > longest.length) {\n longest = odd;\n }\n\n if (even.length > longest.length) {\n longest = even;\n }\n }\n\n return longest;\n};\n\n// Example usage\nconst s = "babad";\nconst result = longestPalindrome(s);\nconsole.log("Longest Palindromic Substring: " + result);\n\n```\n```Ruby []\n# @param {String} s\n# @return {String}\ndef longest_palindrome(s)\n def expand_around_center(s, left, right)\n while left >= 0 && right < s.length && s[left] == s[right]\n left -= 1\n right += 1\n end\n s[left + 1...right]\n end\n\n longest = ""\n\n (0...s.length).each do |i|\n odd = expand_around_center(s, i, i)\n even = expand_around_center(s, i, i + 1)\n\n if odd.length > longest.length\n longest = odd\n end\n\n if even.length > longest.length\n longest = even\n end\n end\n\n return longest\nend\n\n# Example usage\ns = "babad"\nresult = longest_palindrome(s)\nputs "Longest Palindromic Substring: #{result}"\n\n```\n```Typescript []\nfunction longestPalindrome(s: string): string {\n function expandAroundCenter(left: number, right: number): string {\n while (left >= 0 && right < s.length && s[left] === s[right]) {\n left--;\n right++;\n }\n return s.substring(left + 1, right);\n }\n\n let longest = "";\n\n for (let i = 0; i < s.length; i++) {\n let odd = expandAroundCenter(i, i);\n let even = expandAroundCenter(i, i + 1);\n\n if (odd.length > longest.length) {\n longest = odd;\n }\n\n if (even.length > longest.length) {\n longest = even;\n }\n }\n\n return longest;\n}\n\n// Example usage\nconst s = "babad";\nconst result = longestPalindrome(s);\nconsole.log("Longest Palindromic Substring: " + result);\n\n```
444
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
2,421
15
![Screenshot 2023-10-26 095237.png]()\n\n# YouTube Video Explanation:\n[]()\n\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: \n\n*Subscribe Goal: 150 Subscribers*\n*Current Subscribers: 133*\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires us to find the longest palindromic substring within a given string. A simple approach is to check every possible substring within the given string and determine if it\'s a palindrome. However, this brute-force approach results in a time complexity of O(n^3), which is highly inefficient.\n\nA more efficient approach is to use dynamic programming, which allows us to optimize the solution to O(n^2). The key idea is to recognize that a palindrome reads the same backward as forward. Therefore, we can efficiently identify palindromes by expanding around a center. We start with a single character as a center and expand it in both directions, keeping track of the longest palindrome found.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. Initialize two variables, maxLen and lo, to keep track of the maximum palindrome length and the starting index of the longest palindrome.\n2. Iterate through the characters of the input string.\n3. For each character, expand around the center, considering both odd and even-length palindromes.\n4. While expanding, check if the substring is a palindrome.\n5. If a longer palindrome is found, update maxLen and lo accordingly.\n6. After iterating through all characters, return the longest palindrome substring using the lo and maxLen variables.\n\n\n# Complexity\n- Time Complexity: O(n^2) - We expand around each character once, leading to a quadratic time complexity.\n- Space Complexity: O(1) - We use a constant amount of extra space.\n\nThis optimized solution efficiently finds the longest palindromic substring in a given string.\n\n# Code\n## Java\n```\nclass Solution {\n int maxLen = 0;\n int lo = 0;\n\n public String longestPalindrome(String s) {\n char[] input = s.toCharArray();\n if (s.length() < 2) {\n return s;\n }\n\n for (int i = 0; i < input.length; i++) {\n expandPalindrome(input, i, i);\n expandPalindrome(input, i, i + 1);\n }\n return s.substring(lo, lo + maxLen);\n }\n\n public void expandPalindrome(char[] s, int j, int k) {\n while (j >= 0 && k < s.length && s[j] == s[k]) {\n j--;\n k++;\n }\n if (maxLen < k - j - 1) {\n maxLen = k - j - 1;\n lo = j + 1;\n }\n }\n}\n\n```\n## C++\n```\nclass Solution {\npublic:\n string longestPalindrome(string s) {\n if (s.length() < 2) {\n return s;\n }\n \n int maxLen = 0;\n int lo = 0;\n std::string result = s;\n \n for (int i = 0; i < s.length(); i++) {\n expandPalindrome(s, i, i, maxLen, lo);\n expandPalindrome(s, i, i + 1, maxLen, lo);\n }\n \n return result.substr(lo, maxLen);\n }\n \n void expandPalindrome(const std::string& s, int j, int k, int& maxLen, int& lo) {\n while (j >= 0 && k < s.length() && s[j] == s[k]) {\n j--;\n k++;\n }\n if (maxLen < k - j - 1) {\n maxLen = k - j - 1;\n lo = j + 1;\n }\n }\n};\n```\n## JavaScript\n```\n/**\n * @param {string} s\n * @return {string}\n */\nvar longestPalindrome = function(s) {\n if (s.length < 2) {\n return s;\n }\n\n let maxLen = 0;\n let lo = 0;\n let result = s;\n\n const expandPalindrome = (j, k) => {\n while (j >= 0 && k < s.length && s[j] === s[k]) {\n j--;\n k++;\n }\n if (maxLen < k - j - 1) {\n maxLen = k - j - 1;\n lo = j + 1;\n }\n };\n\n for (let i = 0; i < s.length; i++) {\n expandPalindrome(i, i);\n expandPalindrome(i, i + 1);\n }\n\n return result.substring(lo, lo + maxLen);\n};\n```\n## Python3\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n def expand(l,r):\n while l >=0 and r < len(s) and s[l] == s[r]:\n l -= 1\n r += 1\n return s[l+1:r]\n \n res = \'\'\n\n for i in range(len(s)):\n sub1 = expand(i,i)\n if len(sub1) > len(res):\n res = sub1\n sub2 = expand(i,i+1)\n if len(sub2) > len(res):\n res = sub2\n return res\n```\n---\n![upvote1.jpeg]()
446
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
9
7
\n# Code\n```\nclass Solution {\n public function longestPalindrome($s) {\n // Check if the input string is empty, return an empty string if so\n if (empty($s)) {\n return "";\n }\n\n // Initialize variables to store the indices of the longest palindrome found\n $longestPalindromeIndices = array(0, 0);\n\n // Loop through the characters in the input string\n for ($i = 0; $i < strlen($s); ++$i) {\n // Find the indices of the longest palindrome centered at character i\n $currentIndices = $this->expandAroundCenter($s, $i, $i);\n\n // Compare the length of the current palindrome with the longest found so far\n if ($currentIndices[1] - $currentIndices[0] > $longestPalindromeIndices[1] - $longestPalindromeIndices[0]) {\n // Update the longest palindrome indices if the current one is longer\n $longestPalindromeIndices = $currentIndices;\n }\n\n // Check if there is a possibility of an even-length palindrome centered at\n // character i and i+1\n if ($i + 1 < strlen($s) && $s[$i] == $s[$i + 1]) {\n // Find the indices of the longest even-length palindrome centered at characters\n // i and i+1\n $evenIndices = $this->expandAroundCenter($s, $i, $i + 1);\n\n // Compare the length of the even-length palindrome with the longest found so\n // far\n if ($evenIndices[1] - $evenIndices[0] > $longestPalindromeIndices[1] - $longestPalindromeIndices[0]) {\n // Update the longest palindrome indices if the even-length one is longer\n $longestPalindromeIndices = $evenIndices;\n }\n }\n }\n\n // Extract and return the longest palindrome substring using the indices\n return substr($s, $longestPalindromeIndices[0], $longestPalindromeIndices[1] - $longestPalindromeIndices[0] + 1);\n }\n\n // Helper function to find and return the indices of the longest palindrome\n // extended from s[i..j] (inclusive) by expanding around the center\n private function expandAroundCenter($s, $i, $j) {\n // Expand the palindrome by moving outward from the center while the characters match\n while ($i >= 0 && $j < strlen($s) && $s[$i] == $s[$j]) {\n $i--; // Move the left index to the left\n $j++; // Move the right index to the right\n }\n // Return the indices of the longest palindrome found\n return array($i + 1, $j - 1);\n }\n}\n```
450
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
197
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {string} s\n * @return {string}\n */\nvar longestPalindrome = function(s) {\n let longstring =\'\'\n let substring =\'\'\n for(let i=0; i < s.length;i++){\n for(let j=s.length; j >i ; j--){\n\n substring = s.slice(i,j)\n if(ispallindrome(substring)&& longstring.length < substring.length ){\n longstring = substring\n }\n \n }\n }\n\n\n return longstring\n \n};\n\nfunction ispallindrome(substring){\n \n for(let i=0;i < substring.length/2;i++){\n if(substring[i] != substring[substring.length-(1+i)]){\n return false\n }\n }\n\n return true\n}\n\n\n\n\n\n```
451
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
3,537
13
\n\n# Code\n```\nclass Solution {\n public String longestPalindrome(String s) {\n int start = 0, end = 0;\n for(int i = 0; i < s.length(); i ++) {\n char c = s.charAt(i);\n int left = i;\n int right = i;\n while(left >= 0 && s.charAt(left) == c) left --;\n while(right < s.length() && s.charAt(right) == c) right ++;\n while(left >= 0 && right < s.length()) {\n if(s.charAt(left) != s.charAt(right)) break;\n left --;\n right ++;\n }\n left += 1;\n if(end - start < right - left) {\n start = left;\n end = right;\n }\n } \n return s.substring(start, end);\n }\n}\n```\n# PLEASE UPVOTE IF IT WAS HELPFULL
452
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
2,081
7
# **PLEASE UPVOTE MY SOLUTION IG YOU LIKE IT**\n# **CONNECT WITH ME**\n# **[]()**\n# **[]()**\n# Approach\nInitialize start and maxLen variables to keep track of the starting index and maximum length of the palindromic substring found.\n\nLoop through each character c in the string s (from index 0 to n-1), treating it as the potential center of a palindrome.\n\nFor each center c, expand around it to find the longest palindromic substring. Check for both odd-length and even-length palindromes:\n\na. Odd-length palindrome: Expand around c by moving the left pointer left towards the left and the right pointer right towards the right, while checking if the characters at s[left] and s[right] are the same.\n\nb. Even-length palindrome: Expand around the center between c and c+1 by moving the left pointer left towards the left and the right pointer right towards the right, while checking if the characters at s[left] and s[right] are the same.\n\nCalculate the length of the palindrome found using right - left - 1.\n\nCompare the length of the current palindrome with the maxLen. If it\'s greater, update maxLen and calculate the new start index of the longest palindrome.\n\nAfter iterating through all possible centers, use the start and maxLen to extract the longest palindromic substring using s.substr(start, maxLen).\n\nReturn the longest palindromic substring.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:0(n*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string longestPalindrome(string s) {\n int n = s.size();\n int start = 0, maxLen = 0;\n\n for (int i = 0; i < n; i++) {\n // Check for odd length palindromes centered at i\n int len1 = expandAroundCenter(s, i, i);\n // Check for even length palindromes centered between i and i+1\n int len2 = expandAroundCenter(s, i, i + 1);\n\n int len = max(len1, len2);\n if (len > maxLen) {\n maxLen = len;\n // Calculate starting index based on palindrome length\n start = i - (len - 1) / 2;\n }\n }\n\n return s.substr(start, maxLen);\n }\n\nprivate:\n int expandAroundCenter(const string& s, int left, int right) {\n while (left >= 0 && right < s.size() && s[left] == s[right]) {\n left--;\n right++;\n }\n // Return the length of the palindrome found\n return right - left - 1;\n }\n};\n\n```\n\n# Approach\nint n = s.size();: This calculates the length of the input string s.\n\nstring ans; int maxi=0;: Initialize variables ans to store the longest palindromic substring found so far and maxi to store its length.\n\nvector<vector<int>> dp(n, vector<int>(n, 0));: Initialize a 2D vector dp of size n x n with all elements initially set to 0. The element dp[i][j] will store information about whether the substring from index i to index j is a palindrome and its length.\n\nThe nested loops using variables diff, i, and j iterate over different possible substrings of s.\n\ndiff represents the difference between j and i, indicating the length of the current substring being considered.\n\ni and j represent the starting and ending indices of the current substring under consideration.\n\nInside the loops, the code checks three cases to determine if the current substring is a palindrome:\n\nIf i and j are the same (i.e., single character), then the substring is a palindrome of length 1, so dp[i][j] is set to 1.\n\nIf the difference between j and i is 1 and the characters at these positions are the same, then the substring is a palindrome of length 2, so dp[i][j] is set to 2.\n\nFor other cases, the code checks if the characters at positions i and j are the same and if the substring within these positions (i+1 to j-1) is a palindrome. If both conditions are met, dp[i][j] is set to dp[i+1][j-1] + 2, indicating that the current substring is a palindrome of length dp[i+1][j-1] + 2.\n\nAfter updating dp[i][j], the code checks if the substring from index i to j is a palindrome (i.e., dp[i][j] is not 0) and if its length is greater than the current maxi. If both conditions are met, it updates maxi and sets ans to the substring using s.substr(i, maxi).\n\nFinally, the function returns the longest palindromic substring ans.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:0(n*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(n*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string longestPalindrome(string s) {\n int n = s.size();\n string ans;\n int maxi=0;\n vector<vector<int>>dp(n,vector<int>(n,0));\n for(int diff=0;diff<n;diff++)\n {\n for(int i =0,j=i+diff;j<n;i++,j++)\n {\n if(i==j)\n {\n // single letter is always a palindrome\n dp[i][j]=1;\n }\n else if(diff==1)\n {\n // if true then store 2 else 0 \n dp[i][j]=(s[i]==s[j])?2:0;\n }\n else\n {\n if(s[i]==s[j] && dp[i+1][j-1]!=0)\n {\n dp[i][j]=dp[i+1][j-1]+2;\n }\n }\n if(dp[i][j] && j-i+1>maxi)\n {\n maxi=j-i+1;\n ans=s.substr(i,maxi);\n }\n }\n }\n return ans;\n }\n};\n```
453
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
195,986
1,043
\n def longestPalindrome(self, s):\n res = ""\n for i in xrange(len(s)):\n # odd case, like "aba"\n tmp = self.helper(s, i, i)\n if len(tmp) > len(res):\n res = tmp\n # even case, like "abba"\n tmp = self.helper(s, i, i+1)\n if len(tmp) > len(res):\n res = tmp\n return res\n \n # get the longest palindrome, l, r are the middle indexes \n # from inner to outer\n def helper(self, s, l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]:\n l -= 1; r += 1\n return s[l+1:r]
454
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
201,221
907
`dp(i, j)` represents whether `s(i ... j)` can form a palindromic substring, `dp(i, j)` is true when `s(i)` equals to `s(j)` and `s(i+1 ... j-1)` is a palindromic substring. When we found a palindrome, check if it's the longest one. Time complexity O(n^2).\n\n public String longestPalindrome(String s) {\n int n = s.length();\n String res = null;\n \n boolean[][] dp = new boolean[n][n];\n \n for (int i = n - 1; i >= 0; i--) {\n for (int j = i; j < n; j++) {\n dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]);\n \n if (dp[i][j] && (res == null || j - i + 1 > res.length())) {\n res = s.substring(i, j + 1);\n }\n }\n }\n \n return res;\n }
465
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
2,653
21
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n# Expand around Center Approach\nUse each character of input as middle, and expand both side to find the palindrome.\nKeep track of length and starting index of longest palindrome found.\n\n# Upvote if it helped \uD83D\uDE0A\n\n# Approach\n\n1. Initialize two variables: `start` to keep track of the starting index of the longest palindrome found so far, and `max` to keep track of its length. Initially, both are set to 0.\n\n2. Check the length of the input string `s`. If it has a length less than 2, return it immediately as it\'s already a palindrome (or an empty string).\n\n3. Convert the input string `s` into a character array `chars` to make it easier to manipulate.\n\n4. Iterate through each character in the string using a for loop. For each character at index `i`, do the following:\n\n - **Find odd-length palindromes**: Call the `findPalindrome` function with the current character as both the left and right center (i.e., `findPalindrome(chars, i, i)`). This function will expand outwards from this center to find the longest palindrome centered at this character.\n\n - **Find even-length palindromes**: Call the `findPalindrome` function with the current character and the next character as the left and right centers (i.e., `findPalindrome(chars, i, i+1)`). This covers the case of even-length palindromes.\n\n5. The `findPalindrome` function takes a character array `chars` and two indices `j` and `k` as input. It uses these indices to expand outwards from the center and checks if the characters at `j` and `k` are equal. If they are equal, it means a longer palindrome is found, so it expands further by incrementing `k` and decrementing `j`. This process continues until the characters at `j` and `k` are no longer equal or until `j` becomes negative or `k` goes beyond the length of the string.\n\n6. Inside the `findPalindrome` function, if a palindrome longer than the previously recorded maximum is found, it updates the `max` variable with the new length and the `start` variable with the new starting index of the longest palindrome.\n\n7. After iterating through the entire string and calling `findPalindrome` for all possible centers, the `start` and `max` variables will hold the starting index and length of the longest palindromic substring in the input string.\n\n8. Finally, use the `start` and `max` values to extract the longest palindromic substring from the original input string `s` and return it.\n# Example\n\n**Example Input String**: "babad"\n\n1. character array: `chars = [\'b\', \'a\', \'b\', \'a\', \'d\']`.\n\n2. Iterate through the characters in the string:\n\n - **Iteration 1 (i = 0, char = \'b\')**:\n\n - Find odd-length palindrome by calling `findPalindrome(chars, 0, 0)`. The center is \'b\'.\n\n - Expand outwards: \'b\' == \'b\'.\n\n - Continue expanding: \'a\' != \'d\'. Stop.\n\n - Find even-length palindrome by calling `findPalindrome(chars, 0, 1)`. The centers are \'b\' and \'a\'.\n\n - Expand outwards: \'b\' != \'a\'. Stop.\n\n - **Iteration 2 (i = 1, char = \'a\')**:\n\n - Find odd-length palindrome by calling `findPalindrome(chars, 1, 1)`. The center is \'a\'.\n\n - Expand outwards: \'a\' == \'a\'.\n\n - Continue expanding: \'b\' != \'d\'. Stop.\n\n - Find even-length palindrome by calling `findPalindrome(chars, 1, 2)`. The centers are \'a\' and \'b\'.\n\n - Expand outwards: \'a\' != \'b\'. Stop.\n\n - **Iteration 3 (i = 2, char = \'b\')**:\n\n - Find odd-length palindrome by calling `findPalindrome(chars, 2, 2)`. The center is \'b\'.\n\n - Expand outwards: \'b\' == \'b\'.\n\n - Continue expanding: \'a\' == \'a\'.\n\n - Continue expanding: \'b\' != \'d\'. Stop.\n\n - Find even-length palindrome by calling `findPalindrome(chars, 2, 3)`. The centers are \'b\' and \'a\'.\n\n - Expand outwards: \'b\' != \'a\'. Stop.\n\n - **Iteration 4 (i = 3, char = \'a\')**:\n\n - Find odd-length palindrome by calling `findPalindrome(chars, 3, 3)`. The center is \'a\'.\n\n - Expand outwards: \'a\' == \'a\'.\n\n - Continue expanding: \'b\' != \'d\'. Stop.\n\n - Find even-length palindrome by calling `findPalindrome(chars, 3, 4)`. The centers are \'a\' and \'d\'.\n\n - Expand outwards: \'a\' != \'d\'. Stop.\n\n - **Iteration 5 (i = 4, char = \'d\')**:\n\n - Find odd-length palindrome by calling `findPalindrome(chars, 4, 4)`. The center is \'d\'.\n\n - Expand outwards: \'d\' == \'d\'.\n\n - No more characters to expand. Stop.\n\n - Find even-length palindrome by calling `findPalindrome(chars, 4, 5)`. The centers are \'d\' and out of bounds.\n\n - Out of bounds, so stop.\n\n3. After completing the iterations, the `max` variable holds the length of the longest palindrome found (3), and the `start` variable holds the starting index of that palindrome (1).\n\n4. Return the substring of the input string using `start` and `max`, which is "bab". This is the longest palindromic substring.\n\nSo, in this example, the algorithm correctly identifies "bab" as the longest palindromic substring, which is both odd and even in length. The algorithm efficiently explores all possible centers to find palindromes and keeps track of the longest one encountered.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n*n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution {\n int start = 0; // Initialize the start index for the longest palindrome.\n int max = 0; // Initialize the length of the longest palindrome.\n\n public String longestPalindrome(String s) {\n if(s.length() < 2)\n return s; \n\n char[] chars = s.toCharArray();\n\n for(int i = 0; i < chars.length; i++){\n // Find odd length palindrome\n findPalindrome(chars, i, i); // current character as the center of the palindrome\n\n // Find even length palindrome\n findPalindrome(chars, i, i+1); // current character and the next character as the centers of the palindrome.\n }\n \n // Return the longest palindromic substring by using the start and max indices.\n return s.substring(start, start + max);\n }\n\n private void findPalindrome(char[] chars, int j, int k){\n // Expand the palindrome by checking characters at indices j and k.\n while( j >= 0 && k < chars.length && chars[j] == chars[k]){\n j--;\n k++;\n }\n \n // Check if the current palindrome length is greater than the previously recorded maximum.\n if(max < k - j - 1){\n max = k - j - 1; // Update the length of the longest palindrome.\n start = j + 1; // Update the start index of the longest palindrome.\n }\n }\n}\n\n```
467
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
59,555
337
**Subscribe to my youtube channel for tech related content:** [here]()\n\n```\n// \n\n/*\nSolution 1: Brute Force Approach (Give TLE)\n\nGenerate all substring and check it is palindrome or not.\nIf it is palindrome then check it is longest or not.\n\nTime Complexity - O(N^3), O(N^2) to generate all substring and O(N) to check it is palindrome or not.\nSpace complexity - O(1).\n*/\n\nclass Solution\n{\npublic:\n bool isPalindrome(string s)\n {\n int i = 0, j = s.size() - 1;\n\n while (i < j)\n {\n if (s[i++] != s[j--])\n return false;\n }\n return true;\n }\n\n string longestPalindrome(string s)\n {\n int n = s.size();\n if (n == 0)\n return "";\n\n if (n == 1)\n return s;\n\n string result = "";\n for (int i = 0; i < n - 1; i++)\n {\n for (int j = 1; j <= n - i; j++)\n {\n if (isPalindrome(s.substr(i, j)))\n {\n if (result.size() < j)\n result = s.substr(i, j);\n }\n }\n }\n return result;\n }\n};\n\n/*\nAbove Solution Give TLE....\n\nHow Can we optimise our code?\n\nGot it in above solution, we do unnecessary recompution while validating palindomes.\nFor example : if we know string "aba" is palindrome then "cabac" must be palindrome as left and right are equal.\n\nSolution 2: Using DP\n\nP(i, j) == P(i+1, j-1) && s[i] == s[j];\n\nBase cases :\n\n//One character\nP(i, i) = true;\n\n//Two character\nP(i, i+1) = s[i] == s[i+1];\n\nTime Complexity - O(N^2), Space Complexity - O(N^2) (caching all substring)\n*/\n\nclass Solution\n{\npublic:\n string longestPalindrome(string s)\n {\n int n = s.size();\n if (n == 0)\n return "";\n\n // dp[i][j] will be \'true\' if the string from index i to j is a palindrome.\n bool dp[n][n];\n\n //Initialize with false\n\n memset(dp, 0, sizeof(dp));\n\n //Every Single character is palindrome\n for (int i = 0; i < n; i++)\n dp[i][i] = true;\n\n string ans = "";\n ans += s[0];\n\n for (int i = n - 1; i >= 0; i--)\n {\n for (int j = i + 1; j < n; j++)\n {\n if (s[i] == s[j])\n {\n //If it is of two character OR if its susbtring is palindrome.\n if (j - i == 1 || dp[i + 1][j - 1])\n {\n //Then it will also a palindrome substring\n dp[i][j] = true;\n\n //Check for Longest Palindrome substring\n if (ans.size() < j - i + 1)\n ans = s.substr(i, j - i + 1);\n }\n }\n }\n }\n return ans;\n }\n};\n```\n\n**If you like the solution. Please Upvote :)**
469
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
449
5
# Approach\n<!-- Describe your approach to solving the problem. -->\nWe start by iterating through each character in the input string s. For each character, we treat it as the potential center of a palindrome and try to expand around it to find palindromes.\n\nTo handle both odd-length and even-length palindromes, we define two helper functions, expandAroundCenter(s, left, right) and expandAroundCenter(s, left, right + 1). These functions check for palindromes by comparing characters on both sides of the center (the current character or the space between two characters).\n\nFor each character in s, we use these helper functions to find the lengths of the palindromes (if any) centered at that character.\n\nWe maintain two variables, maxLen and start, to keep track of the length of the longest palindrome found so far and its starting index, respectively.\n\nWhile iterating through the characters, we update maxLen and start whenever we find a longer palindrome.\n\nFinally, we return the substring of s that corresponds to the longest palindrome using the start and maxLen values.\n\n# Complexity\n- Time complexity:O(kn) and k << n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\nprivate:\n int expandAroundCenter(const string& s, int left, int right) {\n while (left >= 0 && right < s.size() && s[left] == s[right]) {\n left--;\n right++;\n }\n return right - left - 1;\n }\npublic:\n string longestPalindrome(string s) {\n int n = s.size();\n int maxLen = 0;\n int start = 0; \n\n for (int i = 0; i < n; i++) {\n int len1 = expandAroundCenter(s, i, i);\n int len2 = expandAroundCenter(s, i, i + 1);\n int len = max(len1, len2);\n \n if (len > maxLen) {\n maxLen = len;\n start = i - (len - 1) / 2;\n }\n }\n \n return s.substr(start, maxLen);\n }\n};\n\n```
471
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
338
6
\n\n# Code\n```\npublic class Solution {\n public String longestPalindrome(String s) {\n // Insert boundary characters to handle even-length palindromes\n StringBuilder modifiedString = new StringBuilder("^#");\n for (char c : s.toCharArray()) {\n modifiedString.append(c).append("#");\n }\n modifiedString.append("$");\n String modifiedStr = modifiedString.toString();\n \n int len = modifiedStr.length();\n int[] palindromeLengths = new int[len];\n int center = 0, rightBoundary = 0;\n \n for (int i = 1; i < len - 1; i++) {\n if (i < rightBoundary) {\n int mirror = 2 * center - i;\n palindromeLengths[i] = Math.min(rightBoundary - i, palindromeLengths[mirror]);\n }\n \n // Attempt to expand palindrome centered at i\n while (modifiedStr.charAt(i + 1 + palindromeLengths[i]) == modifiedStr.charAt(i - 1 - palindromeLengths[i])) {\n palindromeLengths[i]++;\n }\n \n // If this palindrome\'s right boundary exceeds the rightmost boundary so far,\n // adjust center and right boundary\n if (i + palindromeLengths[i] > rightBoundary) {\n center = i;\n rightBoundary = i + palindromeLengths[i];\n }\n }\n \n // Find the maximum length of palindromic substring\n int maxLen = 0;\n int centerIndex = 0;\n for (int i = 0; i < len; i++) {\n if (palindromeLengths[i] > maxLen) {\n maxLen = palindromeLengths[i];\n centerIndex = i;\n }\n }\n \n // Calculate original string indices from modified string\n int start = (centerIndex - maxLen) / 2;\n int end = start + maxLen;\n return s.substring(start, end);\n }\n}\n\n```\n
489
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
1,986
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nC++ solution is accepted with TC $O(n^2)$\n2nd approach uses Manacher\'s Algorithm with TC $O(n)$.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis class contains two methods: `PalindromeC()` and `longestPalindrome()`.\n\n`PalindromeC()`\n\nThis method takes three arguments:\n\n`i`: The left index of the substring to check.\n`j`: The right index of the substring to check.\n`s`: The string to check.\nIt returns a pair of integers, where the first integer is the left index of the longest palindrome substring found, and the second integer is the right index of the longest palindrome substring found.\n\nThe method works by expanding the substring from the center outwards, checking if the characters at the left and right indices of the substring are equal. If they are, the method expands the substring further. If they are not, the method returns the left and right indices of the longest palindrome substring found so far.\n\n`longestPalindrome()`\n\nThis method takes one argument:\n\n`s`: The string to find the longest palindrome substring of.\nIt returns the longest palindrome substring of the given string.\n\nThe method works by iterating over the given string, calling the `PalindromeC()` method to find the longest palindrome substring centered at each index. The method then compares the length of each longest palindrome substring found, and returns the longest palindrome substring.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n^2)\\to O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(1)$ vs $O(n)$\n# Code Runtime 10ms Beats 86.21%->9ms Beats 87.92%\n```\n#pragma GCC optimize("O3") // Add this using O3 optimization\nclass Solution {\npublic:\n pair<int, int> PalindromeC(int i, int j, string& s) {\n int l = i, r = j;\n while (l >= 0 && r < s.size() && s[l] == s[r]) {\n l--;\n r++;\n }\n return { l + 1, r - 1 };\n }\n\n string longestPalindrome(string s) {\n int ll = 0, rr = INT_MIN;\n #pragma unroll// Add this faster\n for (int i = 0; i < s.size(); i++) {\n auto [l, r] = PalindromeC(i, i, s);\n if (r - l > rr - ll) {\n ll = l;\n rr = r;\n }\n tie(l, r) = PalindromeC(i, i + 1, s);\n if (r - l > rr - ll) {\n ll = l;\n rr = r;\n }\n }\n return s.substr(ll, rr - ll + 1);\n }\n};\n\n```\n# Code using Manacher\'s Algorithm runs in 3ms & beats 99.43%\n```\n#pragma GCC optimize("O3")\n//Manacher\'s Algorithm\nclass Solution {\npublic:\n string longestPalindrome(string s) {\n string t="_";\n for (char c: s){\n t.push_back(c);\n t.push_back(\'_\');\n }\n\n int n=t.size();\n vector<int> pRad(n, 0);\n int c=0, radius=0;\n #pragma unroll\n for(int i=0; i<n; i++){\n int reflex=2*c-i;\n if (i<radius) pRad[i]=min(radius-i, pRad[reflex]);\n while(i+1+pRad[i]<n && i-1-pRad[i]>=0 &&\n t[i+1+pRad[i]]==t[i-1-pRad[i]])\n pRad[i]++;\n if (i+pRad[i]>radius){\n c=i;\n radius=i+pRad[i];\n }\n }\n\n int maxLen=0, cIdx=0;\n #pragma unroll\n for(int i=0; i<n; i++)\n if (pRad[i]>maxLen){\n maxLen=pRad[i];\n cIdx=i;\n }\n \n int l=(cIdx-maxLen)/2;\n return s.substr(l, maxLen);\n }\n};\n\n```
490
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
673
5
# Code\nTime complexity : O(n)\nSpace complexity : O(n)\n```\nclass Solution {\npublic:\n string longestPalindrome(string s) {\n int st=0, n=s.length(), max_len=1;\n for(int i=0 ; i<n ; i++){\n int l=i, r=i;\n while(r<n-1 && s[r]==s[r+1]){\n r++;\n }\n i=r;\n while(l>0 && r<n-1 && s[l-1]==s[r+1]){\n l--;r++;\n }\n if(max_len < r-l+1){\n st=l;\n max_len=r-l+1;\n }\n }\n return s.substr(st, max_len);\n }\n};\n```\nOther approaches :\nTime complexity : O(n^2)\nSpace complexity : O(n)\n```\nclass Solution {\npublic:\n string longestPalindrome(string s) {\n int n=s.length();\n vector<bool> dp(n);\n int max_len=1, st=0;\n for(int i=n-1 ; i>=0 ; i--){\n for(int j=n-1 ; j>=i ; j--){\n if(i==j){\n dp[j]=1;\n }else if(j-i<=2){\n dp[j] = s[i]==s[j];\n }else{\n dp[j] = (s[i]==s[j] && dp[j-1]);\n }\n if(dp[j] && max_len < j-i+1){\n st=i;\n max_len = j-i+1;\n }\n }\n }\n return s.substr(st, max_len);\n }\n};\n```\nTime complexity : O(n^2)\nSpace complexity : O(n^2)\n```\nclass Solution {\npublic:\n string longestPalindrome(string s) {\n int n=s.length();\n vector<vector<bool>> dp(n, vector<bool>(n));\n int max_len=1, st=0;\n for(int i=n-1 ; i>=0 ; i--){\n for(int j=i ; j<n ; j++){\n if(i==j){\n dp[i][j]=1;\n }else if(j-i==1){\n dp[i][j] = s[i]==s[j];\n }else{\n dp[i][j] = (s[i]==s[j] && dp[i+1][j-1]);\n }\n if(dp[i][j] && max_len < j-i+1){\n st=i;\n max_len = j-i+1;\n }\n }\n }\n return s.substr(st, max_len);\n }\n};\n```\n
493
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
15,730
202
I had trouble understanding this question, as I am not much good when it comes to DP, and also because no solution offered enough explanation for DP newbies, so here I am going to try my best to explain it in detail.\n\n**Question Interpretation:** To solve a question , we first have to understand it! \nHere we are being asked to calculate longest substring which is a Palindrome(Palindrome is a string which is read same forwards and backwards), among all the Palindromes that exist!!\n\n**Intuition:** Now, we can solve this question in two ways that come at first glance:\n* Use `Brute Force` : Check for every corresponding element in string the longest palindrome possible and do it till the end.\n* `DP`: Since we are essentially looping over every element in `Brute Force`, maybe we can somehow use the result from our previous iteration to simplify the current one, right?? This gives us a nudge to look for a pattern and hence we go for DP.\n\n**Analysis:**\nLets see both the approaches one by one !!!\n\n1.)`Brute Force:` Instead of directly going to code and finding a problem later, lets stop and think about the concept we intend to use here .\n\n*Concept:* We will go through **all** possible element in string and find the longest palindrome amongst them.\n\n*Review:* To calculate **all** the possible substrings in a string of length `n` ,number of combinations generated are:\n`1+2+3+4+..........n`=`n(n-1)/2`. \n`==>` To check all the substrings for Palindrome, we will have to go through **all the `n` characters**\n`==>` **Total** Combinations: `n*n(n-1)/2`= `O(n^3)`\n\n*Conclusion:* Since the time complexity is `O(n^3)`, hence we will not discuss on this approach, and our energy would be better spent looking at `DP` solution .\n\n2.)`DP:` Instead of going through all the previous Palindromes again and again, how about we save them somewhere and calculate the new ones based on them, but how do we d that? Lets see it below \n \n*Concept:* To check a Palindrome of length ,say `l`, we just have to check if \ni.) `s[first character]==s[last character]`\nii.) `s[first character+1, last charcter -1]` is a Palindrome\n\nFor example : say s=" balab"\nNow, to check , if "s" is Palindrome or not, we just have to look at\ni.) `s[first character]==s[last character]` -> b==b -> True\nii.)`s[first character+1, last charcter -1]` is a Palindrome --> "aba" is a Palindrome??\nTo check for "aba", a==a--> True , and "b" is a Palindrome(of length 1)\n==> `s` is a Plaindrome\n\n*Review:* We will make a table `dp` containing if the string from `left` to `right` is a Pal. or not, and to do that, we will fill in the table with `1` or `0`.\nLets look at an example of how the table looks like for `s:"geeks"`\n![image]()\n\nFor `s:geeks:` \n`dp[i][i]`=1, as single letters are always Palindromes\n`dp[1][2]` : string from starting position 1 to ending position 2 are Pal. or not (since "ee" is, hence we fill the table with "1") \nand likewise for others.\n\nThis reduces our time from `O(n^3)` to `O(n^2)` as we dont have to check every possible combination now, instead we can directly check the value being 1 or 0.\n\n**Code:**\n```\nclass Solution {\npublic:\n string longestPalindrome(string s) \n{ \n int len = s.size();\n int dp[len][len];\n memset(dp,0,sizeof(dp));\n int end=1;\n int start=0;\n\t\n for(int i=0;i<len;i++)\n {\n dp[i][i] = 1;\n }\n for(int i=0;i<len-1;i++)\n {\n if(s[i]==s[i+1])\n { dp[i][i+1]=1;start=i;end=2;}\n }\n \n for(int j=2;j<len;j++)\n {\n for(int i=0;i< len-j;i++)\n { \n int left=i; //start point\n int right = i+j; //ending point\n \n if(dp[left+1][right-1]==1 && s[left]==s[right]) \n {\n dp[left][right]=1; start=i; end=j+1; \n } \n }\n }\n return s.substr(start, end);\n}\n};\n```\n\nIf you liked this post, please **UPVOTE** \nHappy coding :))
496
Longest Palindromic Substring
longest-palindromic-substring
Given a string s, return the longest palindromic substring in s.
String,Dynamic Programming
Medium
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
2,792
16
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing bottom-up approach and The main idea behind this is to divide string into smaller palindromic substrings and build up the solution iteratively from smaller palindromes to larger ones.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initializing variables `start` with 0 (Starting index of the longest palindromic substring) and `longlen` with 1, which will contain the length of longest palindromic substring.\n2. Initially, All substrings of length 1 are palindromic so mark them true.\n3. then, check Check for substrings of length 2, if `ith` and `i+1th` matches then update `start` with i and `longlen` will be 2.\n4. Now, Check for substrings of length 3 or more. in this we\'ll check if the substring from `i` to `j` is a palindrome where `j` is ending index of current substring. \n5. and then if substring is palindrome then update maxLength`longlen` n `start`.\n6. Finally, return the string starting from `start`th index till length of `longlen` from Original string , which will contain the longest palindromic substring in the input string.\n\n# Complexity\n- Time complexity:\ncode uses two nested loops to iterate.\nO(n^2).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\ncode uses a 2D boolean table dp of size n x n.\ntherefore, O(n^2).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n//bottom-up approach\nclass Solution {\npublic:\n string longestPalindrome(string s) {\n int n = s.size();\n int start = 0; // Starting index of the longest palindromic substring\n int longlen = 1; // Length of the longest palindromic substring (initialize to 1, as each character is a palindrome by itself)\n \n // Create a table to store the results of subproblems\n vector<vector<bool>> t(n, vector<bool>(n, false));\n \n // All substrings of length 1 are palindromic\n for (int i = 0; i < n; i++)\n t[i][i] = true;\n \n // Check for substrings of length 2\n for (int i = 0; i < n - 1; i++) \n {\n if (s[i] == s[i + 1])\n {\n t[i][i+1] = true;\n start = i;\n longlen = 2;\n }\n }\n \n // Check for substrings of length 3 or more\n for (int l = 3; l <= n; l++) \n {\n for (int i = 0; i < n - l + 1; i++) \n {\n int j = i + l - 1; // Ending index of the current substring\n // Check if the substring from i to j is a palindrome\n if (s[i] == s[j] && t[i + 1][j - 1]) \n {\n t[i][j] = true;\n if (l > longlen) \n {\n longlen = l;\n start = i;\n }\n }\n }\n }\n \n //Extract the longest palindromic substring from original string\n return s.substr(start, longlen);\n }\n};\n\n```
497
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
1,266
15
# Intuition\nThe task is to convert a string into a zigzag pattern with a specified number of rows. The approach involves iterating through the string and placing characters in the appropriate rows based on the zigzag pattern.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n### 1. Create an Array of StringBuffers:\n\nCreate an array of StringBuffer to represent each row in the zigzag pattern.\n### 2. Iterate Through the String:\n\nUse a loop to iterate through each character in the string.\nAppend characters to the rows in a zigzag pattern: vertically downward and then bent upward.\n### 3. Concatenate the Rows:\n\nConcatenate the rows to form the final zigzag pattern.\n### 4. Return the Result:\n\nReturn the concatenated string as the result.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: **O(N)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(N)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String convert(String s, int numRows) {\n int n = s.length();\n StringBuffer [] arr = new StringBuffer[numRows]; \n for(int i=0; i<numRows; i++) arr[i] = new StringBuffer();\n\n int i=0;\n while(i<n){\n /// verticaly downword\n for(int ind=0; ind<numRows && i<n; ind++){\n arr[ind].append(s.charAt(i++));\n }\n /// bent upword\n for(int ind=numRows-2; ind>0 && i<n; ind--){\n arr[ind].append(s.charAt(i++));\n }\n }\n StringBuffer ans = new StringBuffer();\n for(StringBuffer el : arr){\n ans.append(el);\n }\n return ans.toString();\n }\n}\n```\n\uD83D\uDE80![WhatsApp Image 2023-12-03 at 12.33.52.jpeg]()\n
500
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
54,347
393
\n\n\n\n**PLEASE DO UPVOTE!!!!!**\n\n**Connect with Me on Linkedin -> **\n# Code\n```\n\n\nclass Solution {\npublic:\n\n string convert(string s, int numRows) {\n \n if(numRows <= 1) return s;\n\n vector<string>v(numRows, ""); \n\n int j = 0, dir = -1;\n\n for(int i = 0; i < s.length(); i++)\n {\n\n if(j == numRows - 1 || j == 0) dir *= (-1); \n\t\t \n v[j] += s[i];\n\n if(dir == 1) j++;\n\n else j--;\n }\n\n string res;\n\n for(auto &it : v) res += it; \n\n return res;\n\n }\n};\n\n\n```\n![b62ab1be-232a-438f-9524-7d8ca4dbd5fe_1675328166.1161866.png]()\n
501
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
982
17
\n\nThe key to solving this problem is to understand that we assign characters to rows by <i>oscillating</i> between the top and bottom rows. In other words, if we traversed the string and looked at which row each character belonged to (let\u2019s say numRows is 3), the pattern would be 1 2 3 2 1 2 3 2 1.. so the first character goes in row 1, the second character goes in rows 2, the third character goes in row 3 - which is the bottom row - so now you go back up to row 2, then row 1.\n\nTo represent the rows, we\u2019ll use a 2D array named `rows`, where each inner list represents a row. We then use a variable called `index` that will oscillate between the top and bottom rows and assign characters to rows.\n\nWe\u2019ll control the direction that index moves by using a variable called `step`. `step` will either be 1 or -1, where a value of 1 means we need to increment the index (so move DOWN a row) and a value of -1 means we need to decrement the index (move UP a row). Whenever we reach either the first or last row, we\'ll switch the direction to move `index` in the opposite direction.\n\nA common mistake I see is creating a 1D list and initializing an empty string for each row. Then, instead of appending to a list, each character is added by using string concatenation. While this works, this is not O(n) because strings are immutable. In other words, string concatenation allocates new memory and copies over each character from both strings to create an entirely new string. That means that the string concatenation runs in O(n), so the overall algorithm runs in O(n<sup>2</sup>) time.\n\nInstead, by using lists (since lists are mutable), appending to a list runs in constant time - or more precisely, the amortized complexity of appending to a list is constant. So that allows everything inside the loop to run in constant time, so the algorithm now runs in O(n) time. \n\n# Code\n```\nclass Solution(object):\n def convert(self, s, numRows):\n if numRows == 1 or numRows >= len(s):\n return s\n \n rows = [[] for row in range(numRows)]\n index = 0\n step = -1\n for char in s:\n rows[index].append(char)\n if index == 0:\n step = 1\n elif index == numRows - 1:\n step = -1\n index += step\n\n for i in range(numRows):\n rows[i] = \'\'.join(rows[i])\n return \'\'.join(rows)\n```
503
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
1,855
12
# Intuition \u2714\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires converting a given string into a zigzag pattern with a specified number of rows and then reading the characters row by row to form a resulting string. The zigzag pattern involves characters moving diagonally up and down.\n\n---\n\n# Approach \u2714\n<!-- Describe your approach to solving the problem. -->\n1. Special Cases:\n\n- If the number of rows (numRows) is 1 or greater than or equal to the length of the input string (s.length()), return the input string as it is, as there is no zigzag pattern to form.\n\n2. Initialize variables:\n\n- Create an empty string result to store the resulting zigzag pattern.\n- Find the length of the input string n.\n- Calculate the cycle length cycleLen as 2 * numRows - 2. This represents the number of characters in each complete cycle of the zigzag pattern.\n\n3. Iterate through each row (from 0 to numRows - 1):\n\n- Inside the outer loop, iterate through the characters of the input string with a step size of cycleLen.\n- In each iteration, append the character at index j + i to the result, where j is the current position within the cycle and i is the current row.\n- If the current row is not the first row (i.e., i != 0) and not the last row (i.e., i != numRows - 1), and there is a valid character at the index j + cycleLen - i, append that character as well. This accounts for the diagonal movement in the zigzag pattern.\n\n4. After completing both loops, the result string will contain the zigzag pattern.\n\n5. Return the result string as the final output.\n\n---\n\n# Complexity \u2714\n1. Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- The code iterates through the input string s once, performing constant-time operations within the loops.\n- Therefore, the time complexity of this solution is O(n), where n is the length of the input string s.\n2. Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n- The space complexity mainly depends on the additional space used to store the result string.\n- In the worst case, the result string can have the same length as the input string, so the space complexity is O(n), where n is the length of the input string s.\n- The space used for other variables is constant and does not significantly impact the space complexity.\n\n---\n# Do upvote if you like the solution and explanation \u2714\n---\n\n\n# Code \u2714\n```\nclass Solution {\npublic:\n string convert(string s, int numRows) {\n if (numRows == 1 || numRows >= s.length()) {\n return s;\n }\n \n string result;\n int n = s.length();\n int cycleLen = 2 * numRows - 2;\n \n for (int i = 0; i < numRows; i++) {\n for (int j = 0; j + i < n; j += cycleLen) {\n result.push_back(s[j + i]);\n if (i != 0 && i != numRows - 1 && j + cycleLen - i < n) {\n result.push_back(s[j + cycleLen - i]);\n }\n }\n }\n \n return result;\n }\n};\n\n```
513
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
3,842
7
This problem is the Daily LeetCoding Challenge for February, Day 3. Feel free to share anything related to this problem here! You can ask questions, discuss what you've learned from this problem, or show off how many days of streak you've made! --- If you'd like to share a detailed solution to the problem, please create a new post in the discuss section and provide - **Detailed Explanations**: Describe the algorithm you used to solve this problem. Include any insights you used to solve this problem. - **Images** that help explain the algorithm. - **Language and Code** you used to pass the problem. - **Time and Space complexity analysis**. --- **📌 Do you want to learn the problem thoroughly?** Read [**⭐ LeetCode Official Solution⭐**]() to learn the 3 approaches to the problem with detailed explanations to the algorithms, codes, and complexity analysis. <details> <summary> Spoiler Alert! We'll explain this 0 approach in the official solution</summary> </details> If you're new to Daily LeetCoding Challenge, [**check out this post**]()! --- <br> <p align="center"> <a href="" target="_blank"> <img src="" width="560px" /> </a> </p> <br>
515
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
278
8
\n# Code\n```\nclass Solution {\n public String convert(String s, int numRows) {\n String[] strArr = new String[numRows];\n Arrays.fill(strArr, "");\n int j = 0;\n int i;\n while(j < s.length()){\n i = 0;\n while(i < numRows && j < s.length()){\n strArr[i++] += s.charAt(j++);\n }\n i--;\n while(i > 1 && j < s.length()){\n strArr[--i] += s.charAt(j++);\n }\n }\n String res = "";\n for(String s1 : strArr){\n res += s1;\n }\n return res;\n }\n}\n```
524
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
15,118
96
![image]()\n\n\nThings become clear with the above image.\n\n# Intuition:\n1. Just look at the top row what is the difference b/w each char i.e A and I and I and Q = 8\n 5*2-2 == numberOf rows *2 - 2 (The corner elements are excluded).\nSimilarly for each row i.e B and J the diff is 8, C and K is 8\n2. The interesting part comes when the char in the diagnoal has to be added, but even this has a pattern\n\t\n\tThere will be no char in between for row 0 and row n.\n\tThere can be only one diagonal char and the diagonal diff is original diff -2 at each step or diff - (rowNumber*2);\n\n# Approach\n\n1. Create an empty StringBuilder which is our ans.\n2. Calculate the diff = numRows*2 -2;\n3. Iterate over 0 to rowNumber in a for loop \nThe first char will be row number or i (append to String)\n4. Write a while loop in the above for loop :\n5. The first char will be row number or i (append to String)\n6. Calculate the diagonalDiff if any and append to the String.\n7. Increase the index by diff and return ans.\n\n\n\n# If you find this useful\n![image]()\n\n```\nclass Solution {\n public String convert(String s, int numRows) {\n if (numRows == 1) {\n return s;\n }\n \n StringBuilder answer = new StringBuilder();\n int n = s.length();\n int diff = 2 * (numRows - 1);\n int diagonalDiff = diff;\n int secondIndex;\n int index;\n for (int i = 0; i < numRows; i++) {\n index = i;\n\n while (index < n) {\n answer.append(s.charAt(index));\n if (i != 0 && i != numRows - 1) {\n diagonalDiff = diff-2*i;\n secondIndex = index + diagonalDiff;\n \n if (secondIndex < n) {\n answer.append(s.charAt(secondIndex));\n }\n }\n index += diff;\n }\n }\n \n return answer.toString();\n }\n}\n```\n\n```\nclass Solution {\npublic:\n string convert(string s, int numRows) {\n if (numRows == 1) {\n return s;\n }\n \n stringstream answer;\n int n = s.length();\n int diff = 2 * (numRows - 1);\n int diagonalDiff = diff;\n int secondIndex;\n int index;\n for (int i = 0; i < numRows; i++) {\n index = i;\n\n while (index < n) {\n answer << s[index];\n if (i != 0 && i != numRows - 1) {\n diagonalDiff = diff-2*i;\n secondIndex = index + diagonalDiff;\n \n if (secondIndex < n) {\n answer << s[secondIndex];\n }\n }\n index += diff;\n }\n }\n \n return answer.str();\n }\n};\n\n```\n\n```\nclass Solution:\n def convert(self, s: str, numRows: int) -> str:\n if numRows == 1:\n return s\n answer = \'\'\n n = len(s)\n diff = 2 * (numRows - 1)\n diagonal_diff = diff\n second_index = 0\n index = 0\n for i in range(numRows):\n index = i\n while index < n:\n answer += s[index]\n if i != 0 and i != numRows - 1:\n diagonal_diff = diff - 2 * i\n second_index = index + diagonal_diff\n if second_index < n:\n answer += s[second_index]\n index += diff\n return answer\n```\n
531
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
555
6
# Intuition & Approach\n\n\n# Code\n```\nclass Solution {\npublic:\n string convert(string s, int numRows) {\n if (numRows == 1)\n return s;\n \n vector<string> rows(numRows);\n bool moveDown = true;\n int rowIdx = 0;\n \n for (auto &ch : s) {\n rows[rowIdx] += ch;\n \n if (rowIdx == numRows - 1)\n moveDown = false;\n else if (rowIdx == 0)\n moveDown = true;\n\n rowIdx += (moveDown ? 1 : -1);\n }\n\n string ret = "";\n for (int i = 0; i < numRows; ++i)\n ret += rows[i];\n \n return ret;\n }\n};\n```
532
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
138,812
816
Create nRows StringBuffers, and keep collecting characters from original string to corresponding StringBuffer. Just take care of your index to keep them in bound.\n\n public String convert(String s, int nRows) {\n char[] c = s.toCharArray();\n int len = c.length;\n StringBuffer[] sb = new StringBuffer[nRows];\n for (int i = 0; i < sb.length; i++) sb[i] = new StringBuffer();\n \n int i = 0;\n while (i < len) {\n for (int idx = 0; idx < nRows && i < len; idx++) // vertically down\n sb[idx].append(c[i++]);\n for (int idx = nRows-2; idx >= 1 && i < len; idx--) // obliquely up\n sb[idx].append(c[i++]);\n }\n for (int idx = 1; idx < sb.length; idx++)\n sb[0].append(sb[idx]);\n return sb[0].toString();\n }
544
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
235
5
\n# Code\n```\nobject Solution {\n import collection.immutable.SortedSet\n def convert(s: String, numRows: Int): String =\n if(numRows==1) s else\n (0 until numRows).flatMap{r =>(r until s.length by ((numRows-1)*2)).flatMap{i =>\n SortedSet(i, i + (numRows-1-r)*2%((numRows-1)*2) )\n }}.filter(_ < s.length).map(s).mkString\n}\n```
545
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
600
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe can follow the array approach\neg: PAYPALISHIRING\nhere num of rows is 3, so we have 3 arrays\narray1: pahn\narray2:aplsiig\narray3:yir\n\nso to divide this,i have used two variables j(acts as index to which array)\nand direction(decides whether to move up or down)\n\n\nnext step is to merge this array\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n public String convert(String s, int numRows) {\n if (numRows == 1 || numRows >= s.length()) {\n return s;\n }\n StringBuilder[] strings = new StringBuilder[numRows];\n for(int i=0;i<numRows;i++)\n {\n strings[i] = new StringBuilder();\n }\n int j =0;\n int direction =1;\n for(int i=0;i<s.length();i++)\n {\n strings[j].append(s.charAt(i));\n if(j==0)\n {\n direction = 1;\n }\n if(j == numRows-1)\n {\n direction = -1;\n }\n j +=direction;\n }\n StringBuilder result = new StringBuilder();\n for (StringBuilder sb : strings) {\n result.append(sb);\n }\n\n return result.toString();\n }\n}\n```
549
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
1,532
11
## **\u2705\u2705C++ || No Extra Space Solution || \uD83D\uDCAF\uD83D\uDCAFGCD Approach || Heavily Commented**\n# **Please Upvote as it really motivates me**\n<iframe src="" frameBorder="0" width="800" height="660"></iframe>\n\n\n![image]()\n\n\n
550
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
63,666
573
class Solution(object):\n def convert(self, s, numRows):\n """\n :type s: str\n :type numRows: int\n :rtype: str\n """\n if numRows == 1 or numRows >= len(s):\n return s\n \n L = [''] * numRows\n index, step = 0, 1\n \n for x in s:\n L[index] += x\n if index == 0:\n step = 1\n elif index == numRows -1:\n step = -1\n index += step\n \n return ''.join(L)
551
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
773
7
# Intuition\nThink of it like bouncing a ball: it goes down, hits the floor, and bounces back up. This is like our zigzag pattern with the string.\n\n# Approach\n1. If we only have one row or more rows than letters, just give back the original word.\n2. I used a jump thing to know if I should go up or down. If I\'m at the top, I\'ll go down. If I\'m at the bottom, I\'ll go up.\n3. For each letter in the word, I put it in the right row and then decide if I should move up or down next.\n4. After placing all the letters, I put all the rows together for the final word.\n\n# Complexity\n- Time complexity:\nIt\'s pretty quick. It goes through the word once, so $$O(n)$$.\n\n- Space complexity:\nI saved space. I only made room for the letters in the word, so $$O(n)$$ space.\n\n# Code\n```\nclass Solution(object):\n def convert(self, s, numRows):\n """\n :type s: str\n :type numRows: int\n :rtype: str\n """\n if numRows == 1 or numRows >= len(s):\n return s\n result = [\'\'] * numRows\n row, jump = 0, 1\n\n for char in s:\n result[row] += char\n if row == 0:\n jump = 1\n elif row == numRows - 1:\n jump = -1\n row += jump\n \n return \'\'.join(result)\n```
554
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
344
5
public class Solution {\n public String convert(String s, int nRows) {\n String[] helper = new String[nRows];\n for (int i = 0; i < nRows; i ++){\n helper[i] = "";\n }\n int row = 0;\n int delta = 1;\n for (int i = 0; i < s.length(); i ++){\n char c = s.charAt(i);\n helper[row] += c;\n if (row == nRows - 1){\n delta = -1;\n }\n else if (row == 0){\n delta = 1;\n }\n row = row + delta;\n row = Math.max(0, row);\n }//for\n String result = "";\n for (int i = 0; i < nRows && s.length() > 0; i ++){\n result += helper[i];\n }\n return result;\n }\n}
555
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
86,079
565
/*n=numRows\n \u0394=2n-2 1 2n-1 4n-3\n \u0394= 2 2n-2 2n 4n-4 4n-2\n \u0394= 3 2n-3 2n+1 4n-5 .\n \u0394= . . . . .\n \u0394= . n+2 . 3n .\n \u0394= n-1 n+1 3n-3 3n-1 5n-5\n \u0394=2n-2 n 3n-2 5n-4\n */\nthat's the zigzag pattern the question asked!\nBe careful with nR=1 && nR=2\n\n----------\n\n\n----------\n\n\n----------\n\n\n----------\n\n\n----------\n\n\n----------\n\n\n----------\n\n\n----------\n\n\nmy 16ms code in c++:\n\n class Solution {\n public:\n string convert(string s, int numRows) {\n string result="";\n if(numRows==1)\n \t\t\treturn s;\n int step1,step2;\n int len=s.size();\n for(int i=0;i<numRows;++i){\n step1=(numRows-i-1)*2;\n step2=(i)*2;\n int pos=i;\n if(pos<len)\n result+=s.at(pos);\n while(1){\n pos+=step1;\n if(pos>=len)\n break;\n \t\t\t\tif(step1)\n \t\t\t\t\tresult+=s.at(pos);\n pos+=step2;\n if(pos>=len)\n break;\n \t\t\t\tif(step2)\n \t\t\t\t\tresult+=s.at(pos);\n }\n }\n return result;\n }\n };
556
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
1,538
10
# Approach\n<!-- Describe your approach to solving the problem. -->\n- calculate how many increments you have to do to get to the next row element \n- after calculating we found that no of jumps for rows other than the top and bottom rows is diffrent \n- So use the diffrent formula for middle rows \n- Rest is easy just keep check if the incements are in range\n\n# :) up-Vote if it Helps\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string convert(string s, int numRows) {\n if (numRows == 1) return s;\n string ans = "";\n for (int i = 0; i < numRows; i++) {\n int jumps = 2 * (numRows - 1); //no of jumps to do for reaching the next element of row\n for (int j = i; j < s.length(); j += jumps) { // increment j always by jumps\n ans += s[j];\n int midJumps = j + jumps - 2 * i; // jumps for middle rows \n if (i > 0 && i < numRows - 1 && midJumps < s.length()) // check if middle jumps are in range\n ans += s[midJumps];\n }\n }\n return ans;\n }\n};\n\n```
557
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
171
5
# Complexity\n- Time complexity:\n$$O(n)$$ \n\n- Space complexity:\n$$O(1)$$ (if we don\'t count the result as the additional memory)\n\n# Approach\nOur first step is to find the formula that we can apply for finding the next position in the string that we should add to the result. Look at the zigzag:\n```\nP I N\nA L S I G\nY A H R\nP I\n```\nIf you count letters from \'P\' to \'I\' (both in the first row) and then do the same thing from \'I\' to \'N\', you\'ll notice that the distance between each of them is 6.\nNow let\'s do the same thing for the second row of the zigzag. Counting from \'A\' to \'L\' we get 4, and from then \'L\' to \'S\' we get 2. Cool, it means there is some patterny-looking-like thing going on here, but we still need more data to find the pattern.\nIf we count the steps for each row with different numbers of rows for the zigzag, we get the following table:\n| numRows (input) | First step | Second step |\n|----------|----------|----------|\n| First Row | | |\n| 2 | 2 | - |\n| 3 | 4 | - |\n| 4 | 6 | - |\n| 5 | 8 | - |\n| Second Row | | |\n| 2 | 2 | - |\n| 3 | 2 | 2 |\n| 4 | 4 | 2 |\n| 5 | 6 | 2 |\n| Third Row | | |\n| 3 | 4 | - |\n| 4 | 2 | 4 |\n| 5 | 4 | 4 |\n\nNow it\'s pretty easy to find some formulas for the program. First, we might need to find the ```step``` formula. ```Step``` represents the size of a single part of a zigzag. In our example above, that would be the part lasting from \'P\' to \'I\'. According to the data we got, the \'step\' formula goes like follows:\n```\nstep := numRows * 2 - 2\n```\n\nNow, for each row between the first and the last, we need two different steps that will consistently follow each other. It\'s clear that they all sum up to the ```step```. And the ```firstStep``` is always ```step - (currentZigZagRow * 2)```. After we found it, it\'s easy to find the second step: ```secondStep = step - firstStep```, because ```firstStep + secondStep = step```, according to the data. Actually, this formula is applicable to all the consecutive steps.\nBut we still have some exceptions, namely the first and last rows of the zigzag. Here, the first step and the second step will always be ```step```, so our previous formulas won\'t work in a loop.\nI\'m sure there is some mathematical solution for this, but I decided to use a simple if statement for that case. Please let me know in the comments if you\'ve found a better solution.\n\nThe algorithm is as follows:\n1. Find the ```step``` by using the above formula.\n2. Initialize the string builder and grow it to the length of the original string.\n3. In the main loop, go from 0 to numRows: we\'re going to get the result row by row.\n4. Get the first step using the formulas above.\n5. In the second loop, start the ```position``` from ```row``` and go to ```len(s)```, incrementing the ```position``` by the ```nextStep``` variable.\n6. Use the ```position``` to get the character from the string and append it to the result.\n7. Apply the above formulas to find the ```nextStep```.\n\n\n# Code\n```golang\nimport "strings"\n\nfunc convert(s string, numRows int) string {\n if numRows == 1 {\n return s\n }\n\n var b strings.Builder\n b.Grow(len(s))\n step := numRows * 2 - 2\n\n for row := 0; row < numRows; row++ {\n nextStep := 0\n if row == 0 || row == numRows - 1 {\n nextStep = step\n } else {\n nextStep = row * 2\n }\n for pos := row; pos < len(s); pos += nextStep {\n b.WriteByte(s[pos])\n if row == 0 || row == numRows - 1 {\n nextStep = step\n } else { \n nextStep = step - nextPos\n }\n }\n }\n\n return b.String()\n}\n\n```
560
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
2,129
6
# Intuition\nJust create a vector of strings and make the zigzag patter in that vector, after doing that we just need to append those stings and return the ans.\n\n# Approach\ncreate a vector of strings,use a while loop to iterate over the string\nin first itteration just keep adding the character from the string to respective string in the vector i.e v[i].push_back(s[a]),a++ (where i is the number of rows in incresing order and a is the current character),\nin the same while loop we itterate string again but from the back from\nn-2 t0 1 (i--),and add this character to their respective string i.e \nv[i].push_back(s[a]),a++ .on all these loops we add a condition on iterator over string to not go over s.lenth(),if iterator goes over s.length() we break the loop and return string ans. \n\n# Complexity\n- Time complexity:\no(n);\n\n- Space complexity:\no(n)\n\n# Code\n```\nclass Solution {\npublic:\n string convert(string s, int numRows) {\n \n vector <string> v(numRows);\n\n int n=s.length();\n int a=0;\n if(numRows==1){\n return s;\n }\n while(a<n){\n \n for(int i=0;i<numRows;i++){\n if(a<n){v[i].push_back(s[a]);\n a++;\n }else{\n break;\n }\n }\n for(int i=numRows-2;i>0;i--){\n if(a<n){\n v[i].push_back(s[a]);\n a++;\n }else{\n break;\n }\n }\n }\n string ans="";\n\n for(int i=0;i<v.size();i++){\n for(int j=0;j<v[i].size();j++){\n ans.push_back(v[i][j]);\n }\n }\n return ans;\n }\n};\n```
561
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
7,443
20
\n# Intuition:\nThe problem asks to convert a given string into a zigzag pattern with a given number of rows, and then read the converted string row by row. One way to approach the problem is to simulate the process of converting the given string into the zigzag pattern by iterating over the string and filling each row in the pattern.\n\n# Approach:\nWe can use two nested loops, one for iterating over the rows, and one for iterating over the characters in each row. We can also use a variable to keep track of the length of each cycle, which is 2 * numRows - 2 in this case. In each iteration, we can add the character to the corresponding row in the pattern, and also add the corresponding character in the next cycle if it exists.\n\n- For each row, we need to skip characters for the first and last row, as there is no corresponding character in the next cycle.\n- For the rows in between, we need to add the corresponding character in the next cycle.\n- We can use a string variable to store the converted string, and return it at the end.\n# Complexity:\n\n- Time Complexity: O(n), where n is the length of the input string. We iterate over each character in the string once.\n- Space Complexity: O(n), where n is the length of the input string. We use a string variable to store the converted string, which takes O(n) space.\n\n# C++\n```\nclass Solution {\npublic:\n string convert(string s, int numRows) {\n if (numRows == 1) {\n return s;\n }\n string result;\n int n = s.length();\n int cycleLen = 2 * numRows - 2;\n for (int i = 0; i < numRows; i++) {\n for (int j = 0; j + i < n; j += cycleLen) {\n result += s[j + i];\n if (i != 0 && i != numRows - 1 && j + cycleLen - i < n) {\n result += s[j + cycleLen - i];\n }\n }\n }\n return result;\n } \n};\n```\n\n---\n# Java\n```\npublic class Solution {\n public String convert(String s, int numRows) {\n if (numRows == 1) {\n return s;\n }\n StringBuilder result = new StringBuilder();\n int n = s.length();\n int cycleLen = 2 * numRows - 2;\n for (int i = 0; i < numRows; i++) {\n for (int j = 0; j + i < n; j += cycleLen) {\n result.append(s.charAt(j + i));\n if (i != 0 && i != numRows - 1 && j + cycleLen - i < n) {\n result.append(s.charAt(j + cycleLen - i));\n }\n }\n }\n return result.toString();\n }\n}\n\n```\n\n---\n# Python\n```\nclass Solution(object):\n def convert(self, s, numRows):\n if numRows == 1:\n return s\n result = \'\'\n n = len(s)\n cycleLen = 2 * numRows - 2\n for i in range(numRows):\n for j in range(0, n - i, cycleLen):\n result += s[j + i]\n if i != 0 and i != numRows - 1 and j + cycleLen - i < n:\n result += s[j + cycleLen - i]\n return result\n\n```\n---\n# JavaScript\n```\nvar convert = function(s, numRows) {\n if (numRows === 1) {\n return s;\n }\n let result = \'\';\n const n = s.length;\n const cycleLen = 2 * numRows - 2;\n for (let i = 0; i < numRows; i++) {\n for (let j = 0; j + i < n; j += cycleLen) {\n result += s[j + i];\n if (i !== 0 && i !== numRows - 1 && j + cycleLen - i < n) {\n result += s[j + cycleLen - i];\n }\n }\n }\n return result;\n}\n```
568
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
9,467
171
In this question the most important thing is getting the pattern correct. It is very easy to go down the wrong path and spend 10 minutes trying to figure out how to make a complicated algorithm work when a very easy one would suffice.\n\n> Thinking process\n\n1. First I looked at the problem and thought about how the printed pattern looked like it would be mapped out on a matrix. I wrote out the number of "main" columns and then the number of "middle" columns\n ```\n P I N\n A L S I G\n Y A H R\n P I\n ------------------------\n 4 2 4 2 2(*)\n ``` \n The last line is 2 only because the word ends, but we can see that the pattern is `4-2-4-2-4-...`. When drawing it out for `numRows = 3`, the pattern became \n\n ```\n P A H N\n A P L S I I G\n Y I R\n ---------------------------------\n 3 1 3 1 3 1 2(*)\n ``` \n Again we can see the pattern is `3-1-3-1-3-...`\n\n So the pattern of "main" rows to "mid" rows is `n, n-2, n, n-2, ...`\n\n When I tried to build an algorithm for this pattern I got stuck. How would I make the index move up `n`, then down `n-2` without confusing myself or missing edge cases?\n2. Next I tried to write out the row of each letter in the string. For numRows = 4, it became:\n ```\n P A Y P A L I S H I R I N G\n -----------------------------------------\n 1 2 3 4 3 2 1 2 3 4 3 2 1 2\n ```\n For numRows = 3, it became:\n ```\n P A Y P A L I S H I R I N G\n -----------------------------------------\n 1 2 3 2 1 2 3 2 1 2 3 2 1 2\n ```\n\n This is where I found the correct pattern. Basically instead of worrying about "main" rows vs. "mid" rows, it easily maps into moving the index from 1 -> numRows, and then from numRows -> 1. We don\'t even need to think about a matrix and worrying about rows vs. columns.\n\n> Algorithm\n\nAt first I thought about how to make the different rows as strings. How would I make `row1`, `row2`, `row3`? Sure if there were only a few rows I could hardcode them, but then how would I be able to add the character to each row easily? It is too difficult, so I thought using an array would be much better. \n\nThen I thought how would we make sure that we are going up and down in the correct pattern? The easiest way was to use a `going_up` flag to make sure to switch the direction of the index.\n\nLastly the only thing to check was edge cases, which by this point was pretty easy with a simple run through of the algorithm.\n\n> Code:\n\n```py\nclass Solution:\n def convert(self, s: str, numRows: int) -> str:\n if numRows == 1:\n return s\n \n row_arr = [""] * numRows\n row_idx = 1\n going_up = True\n\n for ch in s:\n row_arr[row_idx-1] += ch\n if row_idx == numRows:\n going_up = False\n elif row_idx == 1:\n going_up = True\n \n if going_up:\n row_idx += 1\n else:\n row_idx -= 1\n \n return "".join(row_arr)\n```\n\n> Time & Space Complexity\n\nTime: `O(n)`\n- We run through the whole string once: `O(n)`\n - everything we do inside the for loop: `O(1)`\n- Finally we join the whole array int a string: `O(n)`\n\nSpace: `O(n)`\n- We are creating a new array: `O(n)`\n- We are using join to put it back into a string: `O(n)`
569
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
4,391
50
```\nclass Solution:\n def convert(self, s: str, numRows: int) -> str:\n template = list(range(numRows)) + list(range(numRows - 2, 0, -1))\n\n result = [\'\'] * numRows\n for i, char in enumerate(s):\n result[template[i % len(template)]] += char\n return \'\'.join(result)\n```\n![image]()
570
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
1,640
10
```\nclass Solution:\n def convert(self, s: str, numRows: int) -> str:\n if numRows == 1: return s\n curr=(2*numRows)-2\n res=""\n for i in range(numRows):\n j=0\n while i+j<len(s): \n res+=s[j+i]\n sec=(j-i)+curr\n if i!=0 and i!=numRows-1 and sec<len(s):\n res+=s[sec]\n j+=curr\n return res\n```
571
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
8,204
51
[]()
574
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
4,245
37
\uD83D\uDD34 Check out [LeetCode The Hard Way]() for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our [Discord Study Group]() for live discussion.\n\uD83D\uDFE2 Give a star on [Github Repository]() and upvote this post if you like it.\n\uD83D\uDD35 Check out [Screencast]() if you are interested.\n\n**Python**\n\n```py\n# simulate and add each character to the corresponding row\n# go down -> reach bottom -> go up -> reach top -> go down ...\nclass Solution:\n def convert(self, s: str, n: int) -> str:\n # edge case\n if n == 1: return s\n rows = [\'\' for _ in range(n)]\n # j is the index to track which rows a character should be added to\n # d is the direction: -1 means go up, 1 means go down\n j, d = 0, 1\n for i in range(len(s)):\n # add the current character to corresponding row\n rows[j] += s[i]\n # if it reaches to the last row, we need to go up\n if j == n - 1: d = -1\n # if it reaches to the first row, we need to go down\n elif j == 0: d = 1\n # move j pointer\n j += d;\n # rows would look like below in the first example\n # [\'PAHN\', \'APLSIIG\', \'YIR\']\n # we use join to build the final answer\n return \'\'.join(rows)\n```\n\n**C++ (Modified from Dev_1)**\n\n```cpp\n// simulate and add each character to the corresponding row\n// go down -> reach bottom -> go up -> reach top -> go down ...\nclass Solution {\npublic:\n string convert(string s, int n) {\n // edge case\n if (n == 1) return s;\n vector<string> rows(n);\n // j is the index to track which rows a character should be added to\n // d is the direction: -1 means go up, 1 means go down\n int j = 0, d = 1;\n for (int i = 0; i < s.size(); i++) {\n // add the current character to corresponding row\n rows[j] += s[i];\n // if it reaches to the last row, we need to go up\n if(j == n - 1) d = -1;\n // if it reaches to the first row, we need to go down\n else if(j == 0) d = 1;\n // move j pointer\n j += d;\n }\n // rows would look like below in the first example\n // [\'PAHN\', \'APLSIIG\', \'YIR\']\n // we use `accumulate` to build the final answer (in C++ 20, it takes O(n) only)\n return accumulate(rows.begin(), rows.end(), string{});\n }\n};\n```
577
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
3,193
20
[](Watch)\n**Watch this video for the better explanation of the code.**\n\n\nAlso you can **SUBSCRIBE \uD83E\uDC81 \uD83E\uDC81 \uD83E\uDC81** this channel for the daily leetcode challange solution.\n\n \u2B05\u2B05 Telegram link to discuss leetcode daily questions and other dsa problems\nIf you find my solution helpful please upvote it.\n\n# Code\n```\nclass Solution {\npublic:\n string convert(string s, int numRows) {\n if(numRows<2) return s;\n int t[numRows][s.size()];\n memset(t,-1, sizeof(t));\n string ans;\n\n for(int i=0, changer=1, row=0; i<s.size(); i++){\n \n t[row][i]= s[i];\n if(row==numRows-1) changer =-1;\n if(row==0) changer=1;\n row= row+ changer;\n\n }\n\n for(int i=0; i<numRows; i++){\n for(int j=0; j<s.size();j++){\n if(t[i][j]!=-1)ans.push_back(t[i][j]);\n }\n }\n\n return ans;\n\n }\n};\n```
585
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
1,368
15
**Explanation :**\n* As you can see in this picture we have to convert given string into a ZigZag form with the given row.\n* Starting index is always 0 so i have taken ```startIndex``` variable and initialize with zero.\n* And Created ```idx``` variable to get current index characher in ```ans``` string.\n* As you can observe in the given row the next index is always comes at ```idx += row + (row - 2)``` , so i used this formula. when ```startIndex = 0 or startIndex = row - 1``` then we don\'t need to take between character\'s.\n* and for when ```startIndex is between 1 and row-2``` we have to take between character\'s.\n* and you can observe there is a difference between middle character and next columns character is two and it by two always by row wise. So i have taken ```count``` variable to count their difference.\n* For the first time we have to always take columns characher an then middle character so for this condition i have used ```flag``` logic.\n* if our curret index ie. ```idx``` is reached out off index then i just increased ```startIndex``` by 1 and ```idx = startIndex``` and also increase ```count``` variable by 2\n\n\nI hope you understand my explanation.\nIf any Doubts or Suggestions Put in Comments..\n\nPlease **UpVote**, if it helps a little to you **:)**\n![image]()\n\n**Solution :**\n```\n def convert(self, s, row):\n n = len(s)\n if n <= row: #this is base contions if row is greater than the length of string. so just return string\n return s\n ans, startIndex, idx, flag, count = \'\', 0, 0, 0, 2\n for i in range(n):\n if startIndex == 0 or startIndex == row-1:\n ans += s[idx]\n idx += row + (row - 2)\n if i == n-1: break\n if idx > n - 1 or idx <= 0: #this another or condition is for when we have given two length string and row is 1 \n\t\t\t\t\t\t\t\t\t\t\t#then for the second time that idx value goes to -ve that\'s why it is written\n startIndex += 1\n idx = startIndex\n else:\n if flag == 0:\n ans += s[idx]\n flag = 1\n idx += row + (row - 2) - count\n else:\n ans += s[idx]\n idx += count\n flag = 0\n if idx > n-1 or idx <= 0:\n startIndex += 1\n idx, flag = startIndex, 0\n count += 2\n return ans\n```\n**UpVote :)**
586
Zigzag Conversion
zigzag-conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
String
Medium
null
1,864
8
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string convert(string s, int numRows) {\n if(numRows==1) return s;\n bool down=true;\n string arr[numRows];\n int row=0;\n for(int i=0; i<s.size(); i++) {\n arr[row].push_back(s[i]);\n if(row==numRows-1) down=false;\n else if (row==0) down=true;\n if(down) row++;\n else row--;\n }\n string res="";\n for(int i=0; i<numRows; i++) {\n res += arr[i];\n }\n return res;\n }\n};\n```\nPlease upvote to motivate me to write more solutions
594
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
696
5
\n\nStep 1: Extract the digit in the ones place of `x` by using the modulo operator and store it in `digit`\n\nStep 2: Add that digit to `reverse` as the rightmost digit\n\nStep 3: Remove the ones digit from `x` and continue until `x` equals 0.\n\nIn Python, the modulo operator works slightly differently than other languages (such as Java or C) when it comes to negative numbers. Basically, you will get weird results if you try to do [positive number] mod [negative number]. If you want the modulo to behave the same way with negative numbers as it does with positive numbers, but just have the result be negative, then you need to make sure the divisor is also negative, since the modulo operation will always return a number with the same sign as the divisor.\n\nLastly, I use `math.trunc` instead of just using floor division `//` because of negative numbers. When dividing `x` by 10 and truncating the decimal, if the number is negative, then it would round down <i>away</i> from zero, when really, we want it to round up <i>towards</i> zero.\n\n# Code\n```\nclass Solution:\n def reverse(self, x: int) -> int:\n MAX_INT = 2 ** 31 - 1 # 2,147,483,647\n MIN_INT = -2 ** 31 #-2,147,483,648\n reverse = 0\n\n while x != 0:\n if reverse > MAX_INT / 10 or reverse < MIN_INT / 10:\n return 0\n digit = x % 10 if x > 0 else x % -10\n reverse = reverse * 10 + digit\n x = math.trunc(x / 10)\n\n return reverse\n\n```
601
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
88,541
482
- Linkedin Profile ()\n//-------------> \uD83D\uDC7B Pls Upvote if it is helpful for You \uD83D\uDC7B <-----------------//\n# Approach\n 1. First we decleare a variable r and initilise it to 0\n2. Then each time find remainder Using modulus Operator \n3. Then add remainder to r Lets Understand with example\n\n \n![WhatsApp Image 2023-01-26 at 2.59.34 AM.jpeg]()\n\n - Then compare The value of r to check it is inside the 32-bit integer range [-2^31, 2^31 - 1] Then return r \n - Otherwise return 0;\n\n<!-- Decribe your approach to solving the problem. -->\n - Space complexity: O(1) \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code using 64 bit integer\n``` \nclass Solution { \npublic:\n int reverse(int x) {\n long r=0; // decleare r \n while(x){\n r=r*10+x%10; // find remainder and add its to r\n x=x/10; // Update the value of x\n }\n if(r>INT_MAX || r<INT_MIN) return 0; // check range if r is outside the range then return 0 \n return int(r); // if r in the 32 bit range then return r\n }\n}; \n``` \n ** \n \n# Code using 32 bit integer\n``` \nclass Solution { \npublic:\n int reverse(int x) {\n int r=0; // decleare r \n while(x){\n if (r>INT_MAX/10 || r<INT_MIN/10) return 0; // check 32 bit range if r is outside the range then return 0 \n r=r*10+x%10; // find remainder and add its to r\n x=x/10; // Update the value of x\n } \n return r; // if r in the 32 bit range then return r\n }\n}; \n``` \n ** \n \n\n---\n\n* \uD83D\uDC7B IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION\uD83D\uDC7B*\n![image.png]()\n\n
602
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
613
6
\n# Code\n```\nclass Solution {\n //max = 2147483647\n //min =-2147483648\n public int reverse(int no) {\n int rev = 0;\n int max = Integer.MAX_VALUE;\n int min = Integer.MIN_VALUE;\n\n while(no != 0){\n int lastDigit = no%10;\n\n if(rev > max/10 || (rev == max/10 && lastDigit > 7)){\n return 0; //positive\n }\n if(rev < min/10 || (rev == min/10 && lastDigit < -8)){\n return 0; //negative\n }\n\n rev = rev * 10 + lastDigit;\n\n no = no/10;\n }\n return rev;\n }\n}\n```
607
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
59,023
271
\n# Approach\nThis is a solution in Java that reverses an integer and checks if the result is within the range of a 32-bit signed integer.\n\nThe approach involves using a while loop to extract the last digit of the input integer x and add it to a variable finalNum. At each iteration, finalNum is multiplied by 10 so that the next extracted digit can be added as the next significant digit. After the loop, finalNum is divided by 10 to remove the extra trailing zero.\n\nNext, the solution checks if finalNum is greater than the maximum value of a 32-bit signed integer (Integer.MAX_VALUE) or less than its minimum value (Integer.MIN_VALUE). If either of these conditions is met, the function returns 0 as the result will not fit within the range of a 32-bit signed integer.\n\nFinally, if x is negative, the solution returns -1 * finalNum as a negative result. If x is positive, the solution returns finalNum as the final answer.\n\n\n\n\n\n# Time and Space Complexity\n- Time complexity:\nThe time complexity of this solution is O(log(x)) where x is the input integer. This is because each iteration of the while loop processes the last digit of x and reduces the size of x by a factor of 10. The number of iterations is logarithmic with respect to the size of x, thus making the time complexity O(log(x)).\n\n- Space complexity:\nThe space complexity of this solution is O(1) because only a few variables are used (x, lastDig, and finalNum) and their sizes are constant and do not grow with the size of the input.\n\n![upvote.jpeg]()\n\n\n# Code\n```\nclass Solution {\n public int reverse(int x) {\n long finalNum = 0;\n while(x!=0){\n int lastDig = x%10;\n finalNum += lastDig;\n finalNum = finalNum*10;\n x= x/10;\n }\n finalNum = finalNum/10;\n if(finalNum > Integer.MAX_VALUE || finalNum<Integer.MIN_VALUE){\n return 0;\n }\n if(x<0){\n return (int)(-1*finalNum);\n }\n return (int)finalNum;\n }\n}\n```
608
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
2,241
16
# Intuition\nI thought of finding a simple solution for this medium level problem and to my surprise I was able to crack it with some basic operations.\nPlease upvote if you find it helpful.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1.Convert the integer into a string\n\n2.Reverse the string\n\n3.Convert the string back into an integer\n\n4.Check if the result is within the 32 bit limit\n\n5.Check if the result is positive or negative and return the result accordingly.\nPlease upvote if you find it helpful.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(log(x))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} x\n * @return {number}\n */\nvar reverse = function(x) {\n\n let bit = Math.pow(2,31) - 1 \n\n let rev= x.toString().split(\'\').reverse().join(\'\') \n \n let result = parseInt(rev)\n\n if(result > (bit) || result < -(bit)){\n return 0\n }\n\n if(x<0){\n return -result\n }else{\n return result\n }\n};\n```
612
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
7,367
36
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int reverse(int x) {\n StringBuilder s = new StringBuilder();\n s.append(Math.abs(x));\n s.reverse();\n if (s.length() >= 10 ){\n int c1 = Integer.parseInt(s.substring(0 , 5) );\n int c2 = Integer.parseInt(s.substring(5 , 10) );\n if (c1 > 21474 || c2 > 83647){\n return 0;\n }\n }\n\n int num = Integer.parseInt(s.toString());\n \n return (x < 0) ? -num : num ;\n }\n}\n```\n\n## For additional problem-solving solutions, you can explore my repository on GitHub: [GitHub Repository]()\n\n\n![abcd1.jpeg]()\n
613
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
247,832
1,293
Only 15 lines.\nIf overflow exists, the new result will not equal previous one.\nNo flags needed. No hard code like 0xf7777777 needed.\nSorry for my bad english.\n\n public int reverse(int x)\n {\n int result = 0;\n\n while (x != 0)\n {\n int tail = x % 10;\n int newResult = result * 10 + tail;\n if ((newResult - tail) / 10 != result)\n { return 0; }\n result = newResult;\n x = x / 10;\n }\n\n return result;\n }
614
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
26
7
\n# Code\n```\nobject Solution {\n def reverse(x: Int): Int = {\n val s = if (x < 0) x.toString.tail else x.toString\n val d = s.reverse.toDouble * x.signum\n if (d.isValidInt) d.toInt else 0\n }\n}\n```
615
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
2,286
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution { \npublic:\n int reverse(int x) {\n long r=0; // decleare r \n while(x){\n r=r*10+x%10; // find reminder and add its to r\n x=x/10; // Update the value of x\n }\n if(r>INT_MAX || r<INT_MIN) return 0; // check 32 bit range \n return int(r);\n }\n}; \n```\nPlease upvote to motivate me to write more solutions\n\n
629
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
1,243
6
```\nclass Solution {\n public int reverse(int x) {\n if (x == Integer.MIN_VALUE){\n return 0;\n }\n else{\n int flag = 1;\n if (x < 0){\n flag = -1;\n x = -x;\n }\n int result = 0;\n while(x > 0){\n int digit = x % 10;\n int newresult = result * 10 + digit; \n if (result != (newresult - digit) / 10){\n result = 0;\n break;\n }\n result = newresult;\n x = x / 10;\n }\n result = result * flag;\n return result;\n }\n\n }\n}\n```
630
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
2,438
5
\n```\nclass Solution {\npublic:\n int reverse(int x) {\n int r=0,num;\n if(x==INT_MIN) //INT_MAX=2147483647 and INT_MIN = -2147483648 we wil be leaving out -2147483648 when multiplying by -1 in next step\n return 0;\n\n if(x<0)//we will find reverse considering it a positive no\n num=x*(-1);\n else\n num=x;\n while(num!=0){\n if( r>(INT_MAX/10) || r>( (INT_MAX/10)+num%10) ) //if out of 32-bit int range\n return 0;\n r=r*10 + num%10;\n num=num/10;\n }\n if(x<0)//as we calculated num as positive no\n return r*(-1);\n return r;\n }\n};\n```
632
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
4,208
13
\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int reverse(int n) {\n bool neg = n<0;\n n=abs(n);\n \n int ans=0;\n int temp;\n while(n>0)\n {\n temp=n%10;\n if((double)INT_MAX/ans<=10.0)\n return 0;\n ans*=10;\n ans+=temp;\n n/=10;\n }\n \n if(!neg)\n return ans;\n return ans*-1;\n }\n};\n```
643
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
2,156
11
```\npublic int reverse(int x) {\n long rev=0;\n while(x!=0){\n \n int rem=x%10;\n rev=rev*10+rem;\n x=x/10;\n if(rev>Integer.MAX_VALUE || rev<Integer.MIN_VALUE) return 0;\n \n \n \n }\n return (int)rev;\n }\n}
649
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
2,560
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int reverse(int n) {\n bool neg = n<0;\n n=abs(n);\n \n int ans=0;\n int temp;\n while(n>0)\n {\n temp=n%10;\n if((double)INT_MAX/ans<=10.0)\n return 0;\n ans*=10;\n ans+=temp;\n n/=10;\n }\n \n if(!neg)\n return ans;\n return ans*-1;\n }\n};\n```
650
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
3,886
47
# Complexity\n- Time complexity: $$O(log(n))$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\npublic class Solution \n{\n public int Reverse(int x)\n {\n var result = 0;\n\n while (x != 0)\n {\n var remainder = x % 10;\n var temp = result * 10 + remainder;\n\n // in case of overflow, the current value will not be equal to the previous one\n if ((temp - remainder) / 10 != result)\n {\n return 0;\n }\n\n result = temp;\n x /= 10;\n }\n \n return result;\n }\n}\n```\n\n![pleaseupvote.jpg]()\n
656
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
2,410
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nAfter reading the problem, I find that we need to check two things:\n1. Whether the number is positive or negative.\n2. Whether the reversed number is greater than INTEGER range. \n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe will work on the "Ones place" of number i.e. the last digit.\nSuppose the number is 321, we need to follow the following steps:\n\n 1. Make a long integer num initialized with 0. (long num = 0).\n 2. Store the ones place of "321" in variable r. (int r = num%10).\n 3. Multiply num by 10. (num *= 10).\n 4. Add the remainder r to num. (num += r).\n 3. Divide "321" by 10. Then it will become "32". (x /= 10).\n 4. Continue the above steps untill x becomes 0.\nYou will get your answer.\n \n **If this solution helped you, give it a like to help others.**\n\n\n\n# Complexity\n- Time complexity: O(n) (where n is the total no. of digits)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int reverse(int x) {\n\n boolean flag = true;\n if(x < 0) flag = false; // if x is -ve then flag is false;\n\n x = Math.abs(x);\n\n long num = 0;\n int r;\n\n while(x > 0)\n {\n num *= 10; \n r = x % 10; // r = remainder;\n num += r; // remainder is added;\n x /= 10; // x is divided by 10;\n }\n if(num > Integer.MAX_VALUE) // if reversed is greater then 0 is returned;\n return 0;\n\n int result = (int)num;\n\n if(!flag) // if the no. is -ve. Subtract it two times;\n {\n result -= num;\n result -= num; \n }\n\n return result;\n \n }\n}\n```
662
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
1,335
5
```\nclass Solution \n{\npublic:\n int reverse(int x) \n {\n long long int x1=abs(x);\n long long int ans=0;\n while(x1>0)\n {\n long long int temp=x1%10;\n ans=ans*10+temp;\n x1/=10;\n }\n if(ans>-pow(2,31) && ans<pow(2,31)-1){if(x<0){return (-1)*ans;}else{return ans;}}\n return 0;\n }\n};\n```
664
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
2,451
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int reverse(int x) {\n int sum=0, r;\n \n while(x!=0){\n r=x%10;\n \n x=x/10;\n if (sum > Integer.MAX_VALUE/10 || (sum == Integer.MAX_VALUE / 10 && r > 7)) \n return 0;\n if (sum < Integer.MIN_VALUE/10 || (sum == Integer.MIN_VALUE / 10 && r < -8)) \n return 0;\n sum= sum*10+r;\n }\n \n \n return sum;\n }\n}\n```
665
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
2,085
6
\n# Approach\nFirst of all I have chosen the basic formula for reverseing integers,\nthen as the questing says (after reversing) if the reversed integer is out \nof range then it should return 0, so for that i have used conditional statement for checking MIN and MAX range .\nAnd if its in range then it returned reversed integer.\n\n# Complexity\n- Time complexity:\nO(n)\n\n\n- Space complexity:\nO(1)\n\n\n# Code\n```\nclass Solution {\n public int reverse(int x) {\n \n long reversedx=0;\n int remainder=0;\n\n int temp = x;\n\n while (temp != 0) {\n remainder = temp % 10;\n reversedx = (reversedx * 10) + remainder;\n temp /= 10;\n }\n if(reversedx > Integer.MAX_VALUE || reversedx < Integer.MIN_VALUE)\n return 0;\n return (int)reversedx;\n }\n}\n```
675
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
1,364
5
```\n int reverse(int x) {\n int ans = 0;\n while(x!=0){\n int digit = x%10;\n if(ans>INT_MAX/10 || ans<INT_MIN/10){\n return 0;\n }\n ans = (ans*10)+ digit;\n x /= 10;\n }\n return ans;\n }\n```
677
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
704
5
\n# Code\n```\nclass Solution {\npublic:\n int reverse(int x) {\n int ans=0;\n while(x)\n {\n int r=x%10;\n if(ans>INT_MAX/10 || ans<INT_MIN/10)\n return 0;\n if(ans==INT_MAX/10 && r>7)\n return 0;\n ans=ans*10+r;\n x/=10;\n }\n return ans;\n }\n};\n```\nPlease **UPVOTE** if it helps \u2764\uFE0F\uD83D\uDE0A\nThank You and Happy To Help You!!
682
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
64,658
230
```python3\nclass Solution:\n def reverse(self, x):\n """\n :type x: int\n :rtype: int\n """\n sign = [1,-1][x < 0]\n rst = sign * int(str(abs(x))[::-1])\n return rst if -(2**31)-1 < rst < 2**31 else 0\n```
683
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
13,279
20
# Intuition:\nThe problem asks to reverse the digits of a given integer. The approach is to extract the digits one by one using modulo operator and then add them in reverse order.\n\n# Approach:\n\n1. Initialize a variable \'reverse\' to 0. This variable will hold the reversed integer.\n\n2. Initialize another variable \'num\' to the given integer. We will use \'num\' to avoid modifying the original input integer.\n\n3. While the \'num\' is not equal to 0, extract the rightmost digit of \'num\' using the modulo operator (%). Store this digit in a variable called \'digit\'.\n\n4. Multiply \'reverse\' by 10 and add the extracted digit \'digit\' to it.\n\n5. Divide \'num\' by 10 and update \'num\' with the quotient. This will remove the rightmost digit of \'num\' in each iteration.\n\n6. Repeat steps 3-5 until \'num\' becomes 0.\n\n7. Check if the reversed integer \'reverse\' is within the range of a 32-bit signed integer. If it is not, return 0.\n\n8. Return the reversed integer \'reverse\'.\n\n# Complexity:\n- Time Complexity: The time complexity of the solution is O(log(x)). We need to extract the digits of the integer one by one until there are no more digits left. This process continues until the integer becomes 0. The number of iterations required depends on the number of digits in the integer, which is proportional to log(x) with base 10.\n- Space Complexity: The space complexity of the solution is O(1). We are only using a constant amount of extra space to store the reversed integer and a few other variables.\n---\n# C++\n```cpp\nclass Solution {\npublic:\n int reverse(int x) {\n long reverse = 0;\n while(x!=0){\n int digit = x%10;\n reverse = reverse*10 + digit;\n x=x/10;\n }\n if(reverse>INT_MAX || reverse<INT_MIN) return 0;\n return reverse;\n }\n};\n```\n\n---\n# JAVA\n```java\nclass Solution {\n public int reverse(int x) {\n long reverse = 0;\n while (x != 0) {\n int digit = x % 10;\n reverse = reverse * 10 + digit;\n x = x / 10;\n }\n if (reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE) return 0;\n return (int) reverse;\n }\n}\n\n```\n---\n# Python\n```py\nclass Solution(object):\n def reverse(self, x):\n reverse = 0\n sign = -1 if x < 0 else 1\n x = abs(x)\n while x:\n digit = x % 10\n reverse = reverse * 10 + digit\n x /= 10\n result = sign * reverse\n if result > 2 ** 31 - 1 or result < -(2 ** 31):\n return 0\n return result\n\n```\n---\n# JavaScript\n```js\nvar reverse = function(x) {\n let rev = 0;\n const sign = x < 0 ? -1 : 1;\n x = Math.abs(x);\n while (x !== 0) {\n const digit = x % 10;\n rev = rev * 10 + digit;\n x = Math.floor(x / 10);\n }\n const result = sign * rev;\n if (result > 2 ** 31 - 1 || result < -(2 ** 31)) return 0;\n return result;\n}\n```
685
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
1,741
7
```\nclass Solution {\n public int reverse(int n) {\n \n // Constraints GIVEN In Question: -231 <= x <= 231 - 1\n if(n>= Integer.MAX_VALUE || n<=Integer.MIN_VALUE)\n return 0;\n \n int num = n; \n if(num<0){\n n=n*(-1); // make number positive and reverse it.\n }\n\n // REVERSE LOGIC :\n long rev=0;\n while(n > 0) {\n long digit=n%10;\n rev = rev*10 + digit;\n n/=10;\n\n if(rev>= Integer.MAX_VALUE) // If during reversing, value of number becomes greater than MAX_VALUE -> return 0\n return 0;\n }\n\n //If Original Number is negative - then convert reverse also number to negative. \n \n if(num<0)\n rev=rev*(-1); \n \n return (int)rev; \n }\n}```
687
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
4,371
12
# Intuition\nEasy solution in python\n\n# Code\n```\nMIN=-2**31\nMAX=(2**31)-1\nclass Solution:\n def __init__(self):\n self.rev=0\n self.is_neg=False\n def reverse(self, x: int) -> int:\n if x < 0:\n self.is_neg=True\n x=abs(x)\n while(x!=0):\n digit=x%10\n x=x//10\n\n if self.rev > MAX//10 or (self.rev==MAX//10 and digit>MAX%10):\n return 0\n if self.rev<MIN//10 or (self.rev==MIN//10 and digit <MIN%10):\n return 0\n \n self.rev=10*self.rev+digit\n if self.is_neg:\n self.rev=-self.rev\n return self.rev\n \n```\n\n\n![upvote.jpg]()\n
688
Reverse Integer
reverse-integer
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 [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Math
Medium
null
1,475
17
```\nint reverse(int n) {\n int rev = 0;\n \n while(n !=0) {\n \n if( (rev > INT_MAX/10) || (rev < INT_MIN/10) ){\n return 0;\n }\n \n rev = (rev * 10) + (n % 10);\n n /= 10;\n }\n \n return rev; \n }\n```\nPlease upvote if you find the solution useful, means a lot.
695